See this for Why use a for loop instead of a while loop?
.
Now, coming to your question:
You are initializing i
variable in each iteration of your while
loop. Move the definition of i
outside the while loop so that it's value can be updated.
Try this:
#include <iostream>
int main(void)
{
int i = 0;
while (true)
{
++i;
std::cout << i << std::endl;
if (i == 5)
break;
}
return 0;
}
Output:
1
2
3
4
5
Suggestion:
You can also use for
loop as it is more appropriate to print a range of numbers.
#include <iostream>
int main(void)
{
for (int i = 1; i <= 5; i++)
std::cout << i << std::endl;
return 0;
}