if-else statement

Hi,

I wrote the following code. When the counter i==0, the body of the first part of if-statement would execute, which prints i,0 i^2, 0. However, after that, it continues to evaluate the else-statement, which again prints i,0 i^2, 0 the second time. If I add "break;" at the end of the first if-statement, it would break out of the for-loop.

How can I code it so that after it evaluates the if-statement, if the evaluation of (i==0||i==1)is true, it won't continue to evaluate the else-statement while i hasn't incremented and without breaking out of the loop before i==100?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
  int main()
{
    for(int i=0; i<100; ++i)
    {
        int x = 0;
        if (i==0||i==1)
           {
                cout<<"i, " <<i<<"\t" <<"i^2, " <<i<<"\n";

            }

        else
            x = i + i;
            cout<<"i, " <<i<<"\t" <<"i^2, " <<x<<"\n";
    }

    system("pause");
    return 0;
}
You should put your else block in braces. If you don't use braces, only the statement immediate after the else would be used for the else block.
In your case, your code would be like this
1
2
3
4
5
6
...
else
{
  x = i + i;
}
cout << ...


Make it like
1
2
3
4
5
else
{
  x = i + i;
  cout ...
}

So that the second cout statement isn't printed in every loop iteration.
Topic archived. No new replies allowed.