1 2 3 4
|
for(counting vairable; condition; incrementor){
//statements to execute go here after each increment until the condition is true
}
|
So i=0 means that the count starts at 0
while the variable 'i' is less than 5 - This is the condition to be true or false and when true breaks the loop
increment the variable 'i' by 1 while the condition is still false
then execute the statements in the curly brackets
To sum it up, as long as the variable 'i' is less than 5, execute. We increment so we know when to stop, in this case at 5 or while 'i' is less than 5 and when 'i' reaches 5 the loop will break.
To explain the nested you have to understand the above and apply it.
1 2 3 4 5 6 7
|
for (int i=0; i<5; i++)
{
for (int j=0; j<5; j++)
{
cout << i << endl;
}
}
|
The outside will execute first and will execute what is in the brackets while 'i' is less than 5.
Lets look at whats in the brackets.
1 2 3 4
|
for (int j=0; j<5; j++)
{
cout << i << endl;
}
|
The first loop executes this. So looking at it the same way we can say that while 'j' is less than 5 the statement here will execute, which in this case just prints an 'i'.
Since neither statements are true yet it begins at the outside again, the first loop we looked at, and continues.