Nested loop question

#include <iostream>
using namespace std;
void main()
{
int times;
int i, j;

for (i=0; i<3; i++)
{
times = i % 3;
if (times == 0)
cout << "***" << endl;
for (j=0; j<times; j++)
cout << "*t*" << endl;
}
cout << "***" << endl;
}

How come the output is this?:
***
*t*
*t*
*t*
***

If i=0, times would equal 0 and j wouldn't be less than times so why does it output *t*?


Follow the flow of your program:

When i is 0, times is 0, so "***" is output. Next, j=0, which is equal to times, so the loop is skipped.
When i is 1, times is 1, so no "***" is output. j=0, which is less than times (1), so the loop is run and outputs "*t*" every time (once).
When i is 2, times is 2, so no "***" is output. j=0, which is less than times (2), so the loop is run and outputs "*t*" every time (twice).
The outer loop with i exits since i=3 and the condition for continuing the loop is to continue while i<3.
Finally the "***" is written at the end.
Got it, thank you.
Btw, use int main().
Topic archived. No new replies allowed.