Hello everyone , i'm new to programming, and get often stuck when making some programming exercises, but I usually managed to just google the problem. This time I'm stuck with this assignment from CS50 Harvard course called "credit". The code seems to work fine until it needs to check which type of card it is (Visa American Express or Master Card ) . The problem seems to be somewhere in the last part where it checks the conditions for different types of cards (i wrote a comment in red ) .
I know the code isn't very "reader friendly" , but i was trying my best
Code:
int main(void) {
int sum1=0,sum2=0,sum3,arr[20],i, a, i1, total_digits=0;
long long num,num2;
/* asking user for a valid card number */
printf("enter a card number:");
do
{
scanf("%lld",&num);
}
while (num<0);
num2=num;
printf("%lld \n",num2);
/*counting the number of digits in this card number */
while (num2!=0)
{
num2=num2/10;
total_digits++;
}
/*storing those digits in the array*/
for (a=total_digits-1;a>=0;a--)
{
arr[a]=num%10;
num=num/10;
printf ("%i \n",arr[a]);
}
/*algorithm for checking if the card number is valid*/
for (i=total_digits-2;i>=0;i-=2)
{
arr[i]=arr[i]*2;
printf("array[ %i ]= %i",i,arr[i]);
if (arr[i]>9)
{
i1=i;
arr[i1]=arr[i]%10;
sum1+= (1+arr[i1]);
}
else sum1+=arr[i];
printf("sum1 is %i\n",sum1);
}
for (i=total_digits-1;i>=0;i-=2)
{
sum2+=arr[i];
}
printf("sum2 is %d\n",sum2);
sum3=sum2+sum1;
printf("sum3 is %i\n",sum3);
/* From here the code doesn't seem to work, it just prints that something went wrong*/
/*if the result of the algorithm above ends with zero then the card is valid and can be checked for the type */
if ( sum3%10==0 )
{
if (total_digits==16 && arr[total_digits-16]==5 && (arr[total_digits-15]==1 || arr[total_digits-15]==2 ||arr[total_digits-15]==3 ||arr[total_digits-15]==4||arr[total_digits-15]==5))
{
printf("MasterCARD");
}
else if (total_digits==15 && arr[total_digits-15]==3 && (arr[total_digits-14]==4 || arr[total_digits-14]==7))
{
printf("this is AmericanExpress");
}
else if ((total_digits==13 || total_digits==16 ) && (arr[total_digits-13]==4 || arr[total_digits-16]==4))
{
printf("this is visa");
}
else printf("something went wrong \n"); }
else printf("the card is invalid");
return 0;
}