I am studying the Pyramid Numbers in Java which has a code like this.
public class PyramidCharForLup {
public static void main(String[] args) {
int x = 7;
for (int i = 1; i <= x; i++)
{
for (int j = 1; j <= x - i; j++)
System.out.print(" ");
for (int k = i; k >= 1; k--)
System.out.print((k >=10) ?+ k : " " + k);
for (int k = 2; k <=i; k++)
System.out.print((k>= 10) ?+ k : " " + k);
System.out.println();
}
}
}
The output is
1
2 1 2
3 2 1 2 3
4 3 2 1 2 3 4
5 4 3 2 1 2 3 4 5
6 5 4 3 2 1 2 3 4 5 6
7 6 5 4 3 2 1 2 3 4 5 6 7
I chop the code and study it line by line I’m already studying in this line so far.. heheh
So here’s the code that I want to ask.
public class PyramidCharForLup {
public static void main(String[] args)
{
int x = 7;
for (int i = 1; i <= x; i++) {
for (int j = 1; j <= x - i; j++)
System.out.print(j);
}
}
}
the output of this is 123456123451234123121 for clarification if you are to arrange
123456 12345 1234 123 12 1
First Question: is i in the code for (int j = 1; j <= x - i; j++) become i= 1234567?
Second Question: from the initialization which is one if increment 1..2..3..5..6..7.. are the increment subtracting the last number from 1234567 like
1234567-1… 123456 – 1 … 12345 – 1 … 1234 – 1 … 123 – 1 … 12-1…1-0…. till false Am I right?
and that’s the reason why i got this output 123456 12345 1234 123 12 1
Your code has two nested loops (one loop runs inside the other). This is what happens:
This goes on until j is 6.
11 j (1) is printed.
12 j is increase by one and is now 2. Since 2 < 6 the loop continues.
This goes on until i reaches 7. When i the is increased by 1 it is 8 which is not <= 7 so the outer loop also exists and your program is done.
Your program will count and write the digits from 1..6, then from 1..5 until it reaches 1..1