1
1 2 1
1 2 4 2 1
1 2 4 8 4 2 1
1 2 4 8 16 8 4 2 1
1 2 4 8 16 32 16 8 4 2 1
1 2 4 8 16 32 64 32 16 8 4 2 1
1 2 4 8 16 32 64 128 64 32 16 8 4 2 1
1 2 4 8 16 32 64 128 256 128 64 32 16 8 4 2 1
By using nested loops, write the code of this triangular shape.
//pattern1
for(int outer=1;outer<=6;outer++) // outer loop controls number of rows
{
for(int inner=1;inner<=outer; inner++) // another loop to control number of numbers in each row.
{
System.out.print(inner);
}
System.out.println(); // move the cursor from the end of the current line to the beggiing to the next line
}
//pattern 2
for(int outer =1; outer<=6 ; outer++) //outer loop controls number of rows
{
//3-1 create spaces before numbers.
for(int space=1; space<=6-outer; space++ ) //group controls number of spaces
{
System.out.print(" ");
}
//3-2 print out real numbers.
for(int inner=1;inner<=outer; inner++) // another loop to control number of numbers in each row.
{
System.out.print(inner);
}
System.out.println();
}
Comments
Leave a comment