I have broken the credit problem into 2 parts

  1. Checking whether the sum after the Luhn’s algorithm has a zero at the end or not
  2. If the inout integer is valid then go ahead and find the card type using switch.

for the 1st part have converted the integer into an array and then performed operations on odd and even numbers in the array to get the sum and check. But while running the code I'm getting the following errors

P.S - this my very first hands on experience at coding so please bear if this is a very native doubt.

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

int main(void)
    long long n;
    int c = 0;

    printf("Enter an integer: ");
    scanf("%lld", &n);

    int numberArray[c];

    while (n != 0)
    numberArray[c] = n % 10;
    n /= 10;
    int sum_odd = 0;
    int sum_even = 0;
    int sum_total = 0;
    for (int i = 1 ; i < c ; i+=2)
        int x1 = 2* numberArray[i]; 
        if (x1 >9)
            x1 = x1%10 + x1%100 ; 
        sum_even = sum_even + x1 ; 
    for (int i = 0 ; i<c ; i+=2)
        sum_odd = sum_odd + numberArray[i];
    sum_total = sum_odd + sum_even; 
    if (sum_total % 10 != 0 )
        printf ("Invalid\n");

enter image description here

1 Answer 1

int c = 0;
int numberArray[c];

By doing this you declare int numberArray[0] that is an array of zero members. So any index is "out of bounds" of this array, that is the mistake you see. Instead, you may want to declare an array of max number of members (16 if I remember correctly), and then fill it with digits (extracting digits from n one by one).

  • Got it, works fine now. But is there any way where i can give the length of the array to be a variable like in the current case the count of digits ? Commented Jul 15, 2017 at 18:50
  • No. This is drawbacks of arrays in C. There are other data structures that will be explained later, that have dynamic size, but they have weaknesses as well.
    – obesman
    Commented Jul 15, 2017 at 18:54
  • Hi , thanks for the help, my code is running fine according to the algo. One problem that m facing is validating the user input in case they type a char or "-" between numbers. Any help there would be very appreciated. Commented Jul 16, 2017 at 9:23
  • If you look at Specification of the problem, you see that user's input is assumed to be numeric (for this and future psets: if you want to pass check50, you should STRICTLY follow Specification. If you add something that might be cool from your point of view, you'll get failures). However, for the sake of learning, you may want to implement it with "-". In that case you should take char [] array as input, instead of int []. Then, look at atoi() function available in stdlib.h (type 'man atoi' in you prompt to see what it is) and transfer char[] to int[] omitting "extra" symbols.
    – obesman
    Commented Jul 16, 2017 at 17:42

You must log in to answer this question.

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