Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/forums/c/)
-   -   would check for me if i did the code in the right way ? (http://www.go4expert.com/forums/check-i-code-t25155/)

 hana89 4Mar2011 23:34

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

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

 jjmcallister 5Mar2011 06:49

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

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 5Mar2011 08:49

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

Jamie Use Code Blocks to format your code

 jjmcallister 5Mar2011 20:35

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

Thanks Shabbir.

Code:

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

 All times are GMT +5.5. The time now is 03:48.