My question is simple. I have a 'for' statement in a c++ program and when I compile ignores my cout.
I am using xcode, compiling with xcode and here is my code:
#include <iostream>
using namespace s开发者_Python百科td;
int main ()
{
cout << this prints" << endl;
for(int i=0; i>10; i++)
{
cout << "this doesn't" << endl;
}
return 0;
}
What is the problem?
for(int i=0; i>10; i++)
You initialize i
to 0
then only enter the body of the loop if i
is greater than 10
.
The loop loops as long as the condition i > 10
is true, not until the condition i > 10
is true. This is how all the loops in C++ work: for
, while
, and do/while
.
Your loop condition is backwards. You want it to be i < 10
.
You have got the condition for loop incorrect. This should work. Check below:
#include <iostream>
using namespace std;
int main ()
{
cout << "this prints" << endl;
for(int i=0; i<= 10; i++) // ------> Check the change in condition here
{
cout << "this doesn't" << endl;
}
return 0;
}
精彩评论