0

I tried writing code for cs50 pset1's problem: credit.c(more comfortable) after week2. My code is given below. The problem is that 'sumx' and 'sumy' are just 0 and hence 'sum' is always equal to 0. So whenever I give a correct credit card number, it is just going to new line and program ends. How can I solve this problem and why are 'sumx' and 'sumy' not adding up to their respective sums as they should according to the algorithm?

My code is:

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

int main(void){

  long long i;
  do{
    printf("Your credit card number:\n");   
    i = get_long_long();
  }
  while(i < 4e12 || i > 5.5e15);
  int count = 0;
  int n;
  long long c = i;

  while(i != 0){
    n = i%10;
    i = i/10;
    count++;
  }
  int x[count];

  for(int j = 0; j < count; j++){
    x[j] = c%10;
    i = c/10;
  }

  int sumx = 0;

  for(int j = 0; j < count - 1; j += 2){
    x[j] = x[j] * 2;
    sumx = sumx + x[j];
    printf("%i", sumx);
  }

  int sumy = 0;

  for(int j = 0; j < count; j += 2){
    sumy = sumy + x[j];
  }  

  int sum;
  sum = sumx + sumy;

  if(sum%10 == 0){
    if((count == 15 && x[14] == 3) && (x[13] == 4 || x[13] == 7)){
        printf("AmEx\n");
    }
    else if((count == 16 && x[15] == 5) && (x[14] > 1 || x[14] < 5)){
        printf("MASTERCARD\n");
    }
    else if((count == 13 && x[12] == 4) || (count == 16 && x[15] == 4)){
        printf("VISA\n");
    }
  }
  else{
    printf("Invalid Number\n");
  }

  return 0;
  }
0

What is the value of i when you exit the while loop?(I mean "while(i != 0)").This is the value that you use in your for loop("x[j] = i%10"). Try the debug50 to check the values. Also, because of this, you enter the if on your last if/else block but nothing is printed because nothing of the nested if/else is true

4
  • Yes, I have corrected that before and it is still faulty. I wonder why
    – Tejesh Atr
    Jun 24 '17 at 8:07
  • First you have a typo, instead of i = c/10 should be c= c/10. Then you should consider the number you get from the multiplication with 2, if it is a two-digit number, you should sum the two digits before adding it to the sum.
    – Endgament
    Jun 24 '17 at 8:31
  • Also you should start to multiply from the second-to-last digit.
    – Endgament
    Jun 24 '17 at 8:33
  • Yes. I have realized that there is a better way to write code than what I have written. I will try to be more efficient this time
    – Tejesh Atr
    Jun 24 '17 at 9:36

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .