Credit Card Checker- Program in C

Credit Card Checker- Program in C

About

During my Harward CS50: Introduction to Computer Science course, in week 1, I was given a very interesting real-world project, which I had to program in C.

The goal was to get a Credit Card number as Input from the user and check if it's a Valid Credit Card Number, and which card network the card belongs to. (Amex, Visa, Mastercard)

I was introduced to a very sophisticated algorithm that checks if the card number is valid or not, the algorithm is called the Luhn algorithm.

I had first to recreate the algorithm in C and check if the card number is valid or not, and then find the card network using another set of rules (starting digits and card number length).

Multiple Errors later, I finally made the program that worked correctly!

It was my first Project in C and I loved it because it was not just another program but one that has a real-world use case.

It might not be the most efficient, but hey! It was my day 2 of learning C.


View on Git Hub

Code

#include <cs50.h>
#include <stdio.h>

int main(void)
{
    long int a = 0;
    long int b = 0;
    int counter = 1;
    long int n = get_long("Number: ");
    long int m = n;
    long int l = n;
    int firsttwo = 0;
    while (m > 0)
    {
        int d = m % 10;
        if (counter % 2 == 0)
        {
            if (d * 2 > 9)
            {
                int sum = (d * 2) - 9;
                a = a + sum;
            }
            else
            {
                a = a + (d * 2);
            }
        }
        else
        {
            b = b + d;
        }
        counter++;
        m = m / 10;
    }
    long int total = a + b;
    if (total % 10 == 0)
    {
        int len = 0;
        while (l != 0)
        {
            if (l > 9 && l < 100)
            {
                firsttwo = l;
            }
            l = l / 10;
            len++;
        }
        if (len == 15 && (firsttwo == 34 || firsttwo == 37))
        {
            printf("AMEX\n");
        }
        else if (len == 13 && firsttwo / 10 == 4)
        {
            printf("VISA\n");
        }
        else if (len == 16)
        {
            if (firsttwo / 10 == 4)
            {
                printf("VISA\n");
            }
            else if (firsttwo >= 51 && firsttwo <= 55)
            {
                printf("MASTERCARD\n");
            }
            else
            {
                printf("INVALID\n");
            }
        }
        else
        {
            printf("INVALID\n");
        }
    }
    else
    {
        printf("INVALID\n");
    }
}        

要查看或添加评论,请登录

Samarjeet Singh Arora的更多文章

社区洞察

其他会员也浏览了