Reputation: 3917
When I run this code, it iterates, but then returns "The answer is 0", when it should be "The answer is 10."
Why is this?
#import <Foundation/Foundation.h>
int main (int argc, const char * argv[])
{
int i;
for (int i = 0; i < 12; i++){
if (i % 3 == 0) {
continue;
}
printf("Checking i = %d\n", i);
if (i + 90 == i * i) {
break;
}
}
printf("The answer is %d.\n", i);
return 0;
}
Upvotes: 1
Views: 105
Reputation: 2635
If you want to use i outside the for loop, do not declare it inside for loop
So your for loop should be like
for (i = 0; i < 12; i++)
Upvotes: 0
Reputation: 21353
You're actually declaring i
again inside the for
loop. Make your for loop like so:
for (i = 0; i < 12; i++)
Then, it will retain its value once you exit the loop.
Upvotes: 1
Reputation: 476990
You have two separate i
s in your code, the inner one hiding the outer one. Moreover, the print statement causes undefined behaviour, because the outer i
is read uninitialized.
Say for (i = 0; i < 12; i++)
to use the outer variable instead of declaring a new variable.
Upvotes: 5
Reputation: 206689
int i;
for (int i = 0; i < 12; i++){
^^^^^
The i
inside the loop is not the same as the i
outside the loop.
Repace that with:
int i;
for (i = 0; i < 12; i++){
Upvotes: 8