for Loop help

Hi Guys

Im new here so nice to meet you. i need some help understanding this for loop for an assignment, I am new to C++ and am enjoying it :D

here is the loop "this cannot be changed"

n = 10

for (int i = 1; i <= n; i++)
if(i < 5 && i != 2)
cout << 'X';

I understand what happens in this loop, but I am worried its a trick question :(

The question is to make sure the loop is executed 10 times.

from my understanding the above "for" loop will be executed 10 times or until i = n,
however the "if" statement is only executed 3 times.

my question is if the "if" statement is only executed 3 times does that mean the "for loop is only executed 3 times?


Im so confused
my question is if the "if" statement is only executed 3 times does that mean the "for loop is only executed 3 times?

No.

You need to think about it logically. The if statement is inside the loop. Evaluating the if statement is therefore part of the loop. The loop runs 10 times, and the if statement is evaluated 10 times.

Just because some conditional code inside the loop isn't executed on every iteration of the loop, doesn't mean those iterations aren't occurring.

EDIT: This would be clearer if you enclosed your blocks in braces, even when they're single lines. It would also be clearer if you used code tags to format your post properly, and used sensible indentation:

1
2
3
4
5
6
7
8
9
n = 10; // <--- Note that I added the missing semicolon here

for (int i = 1; i <= n; i++)
{
   if(i < 5 && i != 2)
   {
      cout << 'X';
   }
}
Last edited on
Thank you very much!! you have cleared a lot up for me.
I am very new to this type of forum so I'm still getting the hang of it, bear with me ^^

Below is the for loop converted into a while loop, am i on the right track?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
int main()
{
    int i;
    i = 1;

    while(i < 10)
        if(i < 5 && i != 2)
        {
            cout << 'x';
            i++;
        }
        else
        {
            i++;
        }

    return 0;
}


I see i am posting in the Incorrect section...apologies.
Last edited on
Below is the for loop converted into a while loop, am i on the right track?


Yes - although your while loop will only iterate 9 times, not 10.

Also, you don't need to put the i++; in each conditional block. You can simply have it after the whole if statement has finished. Generally speaking, it's better not to duplicate code if you can consolidate it logically into one place.
Thanks again MikeyBoy.

I have made the necessary changes and it works perfectly.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
int main()
{
    int i;
    i = 1;

    while(i <= 10)
    {
        if(i < 5 && i != 2)
           cout << 'x';
        i++;
    }
    
    return 0;
}
Topic archived. No new replies allowed.