# would check for me if i did the code in the right way ?

Discussion in 'C' started by hana89, Mar 4, 2011.

1. ### hana89New Member

Joined:
Mar 4, 2011
Messages:
1
0
Trophy Points:
0
this is the question :

1- Write a program to print the following to the screen using nested loop.
Code:
```      *
**
****
********
```
Code:
```#include <iostream>
using namespace std;

int main()
{
int i,j;

for ( i=0; i<1; i++ )
{
for( j=0; j<1; j++ )
{
cout << "*" ;
}

cout << "\n" ;

for( j=0; j<2; j++ )
{
cout << "*" ;
}

cout << "\n" ;

for( j=0; j<4; j++ )
{
cout << "*" ;
}

cout << "\n" ;

for( j=0; j<8; j++ )
{
cout << "*" ;
}

cout << "\n" ;
}

return 0;
}

```
PS: i'm still a beginner in C++... and i'm not sure of this code would any1 help me

thanks

Last edited by a moderator: Mar 5, 2011
2. ### jjmcallisterNew Member

Joined:
Mar 5, 2011
Messages:
2
1
Trophy Points:
0
Hi Hana,

This will mostly work, but you don't quite have a nested loop here and instead have 3 loops nested within one loop. You could simplify it by making one loop nested within the main loop. If you look at the problem, there is actually a pattern to the number of * increasing for each line in that the amount doubles.

Try this:

for ( i=0; i<4; i++ )
....{
........for( k=0; k<j; k++ )
............{
................cout << "*" ;
............}
........j=j*2;
........cout << endl;
....}

In this way, you create a new variable, j, that controls the amount of asterisks for each new line. You now have a single loop nested within a loop.

You can also use "cout << endl;" as an alternative to "\n".

Jamie Jon McAllister
UAT Student

shabbir likes this.

Joined:
Jul 12, 2004
Messages:
15,334
377
Trophy Points:
83
4. ### jjmcallisterNew Member

Joined:
Mar 5, 2011
Messages:
2
1
Trophy Points:
0
Thanks Shabbir.

Code:
```[COLOR=#0000ff] for[/COLOR][SIZE=2] ( i=0; i<4; i++ )[/SIZE]
[SIZE=2]     {[/SIZE]
[COLOR=#0000ff]         for[/COLOR][SIZE=2]( k=0; k<[COLOR=red]j[/COLOR]; k++ )[/SIZE]
[SIZE=2]             {[/SIZE]
[SIZE=2]                 cout << [/SIZE][SIZE=2][COLOR=#a31515][SIZE=2][COLOR=#a31515]"*"[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2] ;[/SIZE]
[SIZE=2]             }[/SIZE]
[SIZE=2][COLOR=red]         j=j*2;[/COLOR][/SIZE]
[SIZE=2]         cout << endl; [/SIZE]
[SIZE=2]     }[/SIZE]
```