For loops

Can someone explain me how the for loops work in this piece for code real quick?

int k;
for(i=1;i<=5;i++)
{
for(j=5;j>i;j--)
cout<<' ';
for(k=1;k<=i;k++)
cout<<'*';
cout<<endl;
}
cout << endl;


for(i=1;i<=5;i++)
{
for(j=5;j>i;j--)
cout<<' ';
for(k=1;k<2*i;k++)
cout<<'*';
cout<<endl;
}
cout << endl;

for(i=1;i<=5;i++)
{
for(j=5;j>i;j--)
cout<<' ';
for(k=1;k<2*i;k++)
cout<<i;
cout<<endl;
}
cout << endl;

int l;
for(i=1;i<=5;i++)
{
for(j=5;j>i;j--)
cout<<' ';
for(k=i;k>=1;k--)
cout<<k;
for(l=2;l<=i;l++)
cout<<l;
cout <<endl;
}
It won't; you need to declare your variables 'i' and 'j'. But after you have that straightened out, the first portion initiates a variable, the second evaluates a condition before each iteration of the loop and the last statement executes a command at the completion of every iteration.
A formatted code is easy to read than unformatted. For example

1
2
3
4
5
6
7
8
int k;
for ( i = 1; i <= 5; i++ )
{
   for ( j = 5; j > i; j-- ) cout << ' ';
   for( k = 1; k <=i; k++ )  cout<< '*';
   cout<<endl;
}
cout << endl;


I think that the autor of the code tried to print out a pyramid. However the output is the following

     *
     **
     ***
     ****
     *****


Edit: Oh, I am sorry. The output is indeed a pyramid

     *
    **
   ***
  ****
 *****


P.S. The output can not be formatted exactly the same way as in the console.
Last edited on
Topic archived. No new replies allowed.