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
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
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]