<>Help with nested loops

#include <iomanip>
using namespace std;
int main()
{
int j,k,l;

for(j=0;j<10;j++)
cout<<"*";
cout<<endl;

for (k=0;k<5;k++)
{
for (l=k;l>=0;l--)
cout<<"=";
cout<<endl;
}
return 0;
}


**********
=
==
===
====
=====


What exactly is being done in the nested loop. The l-- is confusing me, because it is not working like my perception (which is obviously wrong) is telling me it should.
for loop syntax:

1
2
3
4
for( initialization; condition; iteration )
{
   body
}


What it does:

1) initialization is performed
2) condition is checked. If condition is true, continue to step 3. Otherwise, exit the loop
3) perform loop body
4) perform iteration
5) go to step #2


So in your loop here:

for (l=k;l>=0;l--)

You are initializing with l=k
You then continue to loop for as long as l>=0
And every time the loop completes, l is decremented by 1.

So you've essentially constructed a "count down" loop. For instance... if k=5, the loop body will run 6 times:

once when l=5
once when l=4
once when l=3
once when l=2
once when l=1
and once when l=0

then the loop will exit once l=-1 (because your condition is no longer true)



Nesting loops inside each other does not change this fundamental behavior.
Topic archived. No new replies allowed.