0

i have written the program for the credit but is not giving the expected output please let me Know if my code requires any change or if the logic is correct or wrong let me know.

here is what i get when executing. make credit clang -fsanitize=signed-integer-overflow -fsanitize=undefined -ggdb3 -O0 -std=c11 -Wall -Werror -Wextra -Wno-sign-compare -Wno-unused-parameter -Wno-unused-variable -Wshadow credit.c -lcrypt -lcs50 -lm -o credit $ ./credit Number: 1000200030004000 INVALID $ ./credit Number: 4000300020001000 INVALID $

here is my program.

include

include

int main(void) { int count=0; long int credit; int sum = 0; int sum1 = 0; int i=0; long int t,s; do { credit = get_long("Number: "); } while(credit < 1);

while((credit%10) > 0)
{
    count++;
}

if((count != 15) || (count != 16))
{
    printf("INVALID\n");
    return 0;
}
else
{
   while((((credit % 10) > 0) && (i < 15)) || (i < 16))
   {
       i++;
       if(i%2 != 0)
       {
           sum = sum + (credit % 10);
       }
       else
       {
           t = 2 * (credit % 10);
           while(t%10 >= 0){
               sum1 = sum1 + (t%10);
           }
       }
   }
    s = sum + sum1;
    if (s%10 == 0)
    {
        printf("valid credit %ld\n",s);
    }
    else
    {
        printf("invalid credit %ld\n",s);
    }
}

} enter code here

0

The specific reason the program is returning INVALID is because this (count != 15) || (count != 16) is always true. Every integer is not 15 OR not 16. Including 15 (which is != 16) and 16 (which is != 15). But let's back up a moment.

It looks like this loop while((credit%10) > 0) {count++;} is intended to calculate the length of the input credit. But what is it really doing? Remember that credit % 10 gives the remainder when credit is divided by 10. What is the value for 1000200030004000 % 10? It is 0, same for the other input. Therefore count is 0. What would happen if the input was 4111111111111? The program would be stuck in an infinite loop. Since the value of credit never changes, this 4111111111111 % 10 will always evaluate to 1 and it will be stuck in the loop forever.

I don't know where the walkthrough's have got off to in the current version of the course. Perhaps you will find this video helpful for thinking about, designing and programming this pset.

| improve this answer | |

You must log in to answer this question.

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