Break example not quite proper


#1

If I would test on numbers smaller than 10 for instance 9 - I would get a wrong answer

[code]#include <stdio.h>

int main (int argc, const char * argv[])
{
int i;
for (i = 0; i < 9; i++) {
printf(“Checking i = %d\n”,i);
if (i + 90 == i*i){
break;
}

} 
printf("The answer is %d.\n",i);
return 0;

}[/code]

Output:
Checking i = 0
Checking i = 1
Checking i = 2
Checking i = 3
Checking i = 4
Checking i = 5
Checking i = 6
Checking i = 7
Checking i = 8
The answer is 9.

Maybe this is better:

[code]#include <stdio.h>

int main (int argc, const char * argv[])
{
int i;
for (i = 0; i < 9; i++) {
printf(“Checking i = %d\n”,i);
if (i + 90 == ii){
printf(“The answer is %d.\n”,i);
break;
}
}
if (i + 90 != i
i) {
printf(“Sorry - no solution found!\n”);
}

return 0;

}[/code]

OUTPUT:

Checking i = 0
Checking i = 1
Checking i = 2
Checking i = 3
Checking i = 4
Checking i = 5
Checking i = 6
Checking i = 7
Checking i = 8
Sorry - no solution found!
Program ended with exit code: 0

Greetings Matthias


#2

I believe the problem is more serious than that. There is a problem in the code logic, in my opinion. As written in the book, my console output is as follows:Checking i = 0 Checking i = 1 Checking i = 2 Checking i = 3 Checking i = 4 Checking i = 5 Checking i = 6 Checking i = 7 Checking i = 8 Checking i = 9 Checking i = 10 The answer is 0.This is because of the line “int i;” just before the for loop. Since it is initialized outside the loop. its value is, by default, zero. The value for “i” inside the loop changes (as can be seen in the first instance of “printf”) but after the break, the value for the variable created outside the loop remains at zero.

I think the code should be as follows:[code]#include <stdio.h>

int main(int argc, const char * argv[])
{
for (int i = 0; i < 12; i++) {
printf(“Checking i = %d\n”, i);
if (i + 90 == i * i) {
printf(“The answer is %d.\n”, i);
break;
}
}

return 0;

}[/code] The console output is:Checking i = 0 Checking i = 1 Checking i = 2 Checking i = 3 Checking i = 4 Checking i = 5 Checking i = 6 Checking i = 7 Checking i = 8 Checking i = 9 Checking i = 10 The answer is 10.There is no need to initialize “i” before the loop, that is done in the “for (int i = 0; i < 12; i++)” code. The main problem is that the second “printf” should be before the break.

The reason your answer seems “wrong” when you use a number <10 is because the test for the break is based on the value of i squared being 100 (i + 90). Therefore, any value for i that is not 10 will be not be 100. :wink: