0

Credit PSET 1 Hacker:

The below code compiles and executes but in an infinite loop. I've tried writing the while condition a few different ways, but it seems to end up the same. I can get the code to execute fine without the while.

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

int main (void)
{
    unsigned long long CC ;
    int len;

    // Input Section //
    do
    {
        printf ("Give me a credit card number.\n");
        scanf ("%llu", &CC);
        len = (floor (log10 (CC)) + 1);
    }
    while (len != 15 || len != 16 || len != 13);

    printf ("%d\n", len);
}

1 Answer 1

1

Well len can't possibly be in the same time both 15 and 16 and 13 (which is what your condition implies). Instead use

while ( len != 15 && len != 16 && len != 13);

Edit

Let's start with only one variable inside the condition:

do
{
    printf("Give me a number\n");
    scanf ("%d", &number);
}
while (number != 0);

Now the loop will continue executing until I give a number that is not zero, so it will continue executing while the condition is true.


Now let's add another condition:

do
{
    printf("Give me a number\n");
    scanf ("%d", &number);
}
while (number != 0 || number != 1);

If we give the value 0 to number the number != 0 will be false so it would let the loop exit, but number != 1 is true, and true || false is true, so the loop will continue to execute.


Now let's change the || to &&

do
{
    printf("Give me a number\n");
    scanf ("%d", &number);
}
while (number != 0 && number != 1);

If instead we had && and we gave the number 0 to number it would be true && false is false so the loop would exit.

I think you can extrapolate to 3 variables.

3
  • I'm confused by the logic. What I was saying is that the do loop should execute while the len does not = 15 or does not equal 16 or does not equal 13. Doesn't add make it so that all 3 are required instead of just one of the conditions?
    – Mo1
    Commented Jul 29, 2015 at 8:25
  • @Mo1 check the edit.
    – ChrisG
    Commented Jul 29, 2015 at 9:49
  • Makes sense now, thanks.
    – Mo1
    Commented Jul 29, 2015 at 11:14

You must log in to answer this question.

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