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

hana89's Avatar, Join Date: Mar 2011
Newbie Member
this is the question :

1- Write a program to print the following to the screen using nested loop.
Code:
      *
     **
   **** 
********
my answer:
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 shabbir; 5Mar2011 at 08:48.. Reason: Code blocks
0
jjmcallister's Avatar, Join Date: Mar 2011
Newbie Member
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 like this
0
shabbir's Avatar, Join Date: Jul 2004
Go4Expert Founder
Jamie Use Code Blocks to format your code
0
jjmcallister's Avatar, Join Date: Mar 2011
Newbie Member
Thanks Shabbir.

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