#include <iostream>
#include <string>
using namespace std;
int main()
{
int i = 0;
while ( i < 11)
cout << i << '\n';
i++;
}
Why does this code repeatedly output 0 instead of adding 1 to i everytime?
Put your statements in curly braces {. Otherwise you only execute the output statement in the cycle and the increment of i will happen outside of the cycle.
You need to write:
#include <iostream>
#include <string>
using namespace std;
int main()
{
int i = 0;
while ( i < 11){
cout << i << '\n';
i++;
}
}
note the extra bracing after ( i < 11)
Out of interest, it's stylistically preferable to use a for loop here:
int main()
{
for (int i = 0; i < 11; ++i){
cout << i << '\n';
}
}
Note how I've brought i into the loop scope so it cannot be accessed outside the loop; helping program stability. All the things that happen to i (declaration, definition, termination condition and increment) are all on the same line as well; helping readability.
In C++ you have the choice of putting a single statement into braces or not.
However, if you have multiple statements in a loop-body, you must use braces:
while ( i < 11) {
cout << i << '\n';
i++;
}
C++ is not space sensitive like e.g. python, so the following would work, too:
while ( i < 11) {cout << i << '\n';i++;}
while ( i < 11)
{
cout << i << '\n';
i++;
}
while ( i < 11)
{
cout << i << '\n';
i++;
}
The body of a loop can either be a single statement:
while ( i < 11)
cout << i << '\n';
or a compound statement; that is, a group of statements surrounded by braces:
while ( i < 11) {
cout << i << '\n';
i++;
}
You have written the first form when you want the second. Unlike some other languages, indentation has no meaning in C++, and statements are only grouped into blocks when surrounded with {}.
Loops in C++ only loop the immediately-following statement unless they've been put in a code block. That is, you code is equivalent to:
int main()
{
int i = 0;
while ( i < 11)
{
cout << i << '\n';
}
i++;
}
This this instead:
int main()
{
int i = 0;
while ( i < 11)
{
cout << i << '\n';
i++;
}
}
while ( i < 11)
{
cout << i << '\n';
i++;
}