Don't Understand For Loop Condition

Can someone explain to me how the condition for the two for loops works. I don't understand the logic behind it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
 int main()
{
    string namearray[3];
    string enemy;
    
    for (int i = 0; i <= 3; i = i+1)
    {
        cout << "Type the name of someone you hate\n";
        cin >> enemy;
        namearray[i]=enemy;
        }
    for (int i=0; i <= 3; i =i +1)
    {
        cout << namearray[i] << " sounds like the name of a moron.\n";
        
    }
    cout << "\n Press Enter to continue...";
    getchar();
    return 0;
}
Well, firstly, those for loops are causing memory access violations, because the conditions are wrong (it should be i<3 NOT i<=3), meaning that it is accessing elements past the end of your namearray. Basically, the logic that it is meant to perform is that the loops access in the names of people into an array of strings, and then progressively insults them. In answer to your question, " how the condition for the two for loops works", it doesn't.
As NT3 points out, there's a serious problem in your code. You should set i < 3 or i != 3 as the condition, other than i <= 3. Otherwise, you are trying to assign the "fourth" element to your namearray, which actually only holds three elements.

The condition in your for loop means:
1. You initialize an index i to some value, in your case, zero;
2. You test the condition i <= 3. If this condition works, the for block get executed;
3. You increment the index by 1;
4. Go back to step 2 to re-check the condition;
5. If condition still holds, go to step 3;
6. Go back to step 2 to re-check;
7. If condition still holds, go to step 3;
...

This keeps happening until the condition does not hold any longer.
Topic archived. No new replies allowed.