简体   繁体   中英

Looping back even the Condition is true in do while loop

When i input negative integer it still loop back

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

int main() {
    int n,i,z;

    do {
        printf("Input: ");
        scanf(" %d",&n);
        z=z+n;
    } while (n != 0 || n < 0);

    printf("Sum:%d",z);     
}

Your code invokes Undefined Behavior (UB), since it tries to sum into z , while z is used uninitialized.

Initialize it to zero.


This condition says:

while (n != 0 || n < 0);

as long as n has a different value from 0 OR is less than 0, loop again.

I guess you want to stop looping, when input is a negative number, which means that you need this:

while (n >= 0);

which means to continue executing the body of the do-while loop, as long as n is non negative (ie 0 or a positive number).

But, notice that with that structure in your for loop, you will get the negative number (which it seems that you like it to be the break signal for your loop), extracted from your sum, z .

If you don't want that to happen, you can use the keyword break , to stop the loop from executing.

Not sure what you expect this to do:

while (n != 0 || n < 0);

translating it to natural language, it says " loop as long as n either isn't 0 or is smaller than 0 ".

I guess it's now obvious the second condition implies the first one? This loop will only exit when n is exactly 0 .


Note this isn't the only error: You're happily using z without ever initializing it, so you can get any value in the end (the initial value of z is indeterminate )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM