+ 1
How ? in nested loop
How do i write this pattern in nested for loop? Enter the number of row: if its=4 show * *** ***** *******
5 Antworten
+ 2
For an input N, there are N rows, each row containing 2 * rowIndex - 1 asterisks. So the outer loop should run N times, and inside, a inner for loop runs 2 * I - 1 times, where I is the index of the current row, given by the outer for loops running variable.
If you need help with the actual code, post what you have tried so far, so we can see where you are stuck/ what you need help with.
+ 1
thank!! :D
+ 1
what about
* *
*** ***
***** *****
T^T
0
You'll need two inner for loops then. The first one will be responsible for printing whitespaces. Since there are two additional asterisks in each row, each loops prints T - I times two whitespaces at once. As for the second inner loop, it will be responsible for printing the asterisks and the whitespace in the middle. Remember for one side the loop had to run 2 * I - 1, as there are now two sides, it has to run twice the amount, i.e. 2 * ( 2 * I - 1 ) or 4 * I - 2, it's both the same result. The whitespace can be printed by simply checking during each iteration (after having printed the asterisk) if the running variable times two equals the total number of times the loop should run, and if it does, you know you have arrived at the middle row of the pattern.