The values in for don't save outside of it

36 views Asked by At

I'm assigning a value in a variable within a loop but when i print it the value returns as 0.

#include <stdio.h>
int N=0,sum=0;
int main(){
    for(N=1; sum>200; N=N+1){
        sum= sum + N;
}
printf("the last number added to reach 200 is %d with the sum being %d:", N, sum);   
return 0;
}

The variable N when printed is returned as 1 and the variable sum has the value 0 which should be something else

1

There are 1 answers

0
Eric Postpischil On

The second item in a for the is the condition to continue the loop. sum>200 says to continue if sum is greater than 200. sum starts at zero, so it is not greater than 200, so the loop ends immediately.