1. We have moved from vBulletin to XenForo and you are viewing the site in the middle of the move. Though the functional aspect of everything is working fine, we are still working on other changes including the new design on Xenforo.
    Dismiss Notice

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

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

  1. hana89

    hana89 New 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 a moderator: Mar 5, 2011
  2. jjmcallister

    jjmcallister New 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 likes this.
  3. shabbir

    shabbir Administrator Staff Member

  4. jjmcallister

    jjmcallister New Member

    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]
    
     

Share This Page