I'm newbie to programming. So as an exercise, I'm trying to print a number pattern like below
4
34
234
1234
I tried the below code
public static void main(String[] args) {
// TODO Auto-generated method stub
int n =4;
for (int i = 1; i <= n; i++) {
for (int j = i; j <= n; j++) {
System.out.print(" ");
}
int num = 4;
for (int j = 1; j <= i; j++) {
System.out.print(num);
num--;
}
System.out.println("");
}
}
but it is printing in this way.
4
43
432
4321
I think, I have to decrement the value before printing. Please correct me if i'm wrong. But I'm stuck here. Can anyone please help me?
This is the pattern you want to get:
4
34
234
1234
When you describe the pattern in words, it could look like this:
There is already some kind of pattern here. The last two lines look remarkably similar. Let's see whether the first two lines can be brought into the same form:
Now that looks good. The next step is to change the wording to depend on the given line:
I took care not to say 5 instead of the 4 + 1, so that the 4 is still visible. Let's give this 4 another name:
Now you should be able to translate this instruction into Java code.
You only need one inner for-loop.
I use the ternary operator (also called elvis-operator because ?:
) to decide whether to print the number or a blank space:
int n = 7;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
System.out.print(j > n-i ? j : " ");
}
System.out.println();
}
It prints
7
67
567
4567
34567
234567
1234567
You actually only need one nested loop in this situation:
int n = 4;
for (int i = n; i > 0; i--) {
for (int j = 1; j <= n; j++) {
if (j < i) {
System.out.print(" ");
} else {
System.out.print(j);
}
}
System.out.println();
}
So loop from 0
to n
and either print a space, or print the number if the inner counter is less than i
.
Output:
4
34
234
1234
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.