Reputation: 1
my project to create a triangle in Java with numbers starting from the right
import java.util.Scanner;
public class Pyramid {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
// loop
for (int i=1; i <= 6; i++) {
// space
for(int j=1; j <= 6-i; j++)
System.out.print(" ");
// numbers
for(int k= 1; k <= i; k++)
System.out.print(k);
// new line
System.out.println();
}
}
}
Upvotes: 0
Views: 1260
Reputation: 1
import java.util.Scanner;
public class Pyramid {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int lines = scanner.nextInt();
for (int i = 0; i <= lines; i++) {
//space
int spaceNum = lines - I;
for (int j = 0; j < spaceNum; j++) {
System.out.print(" ");
}
//numbers
int numbers = lines - spaceNum;
for (int j = numbers; j > 0; j--) {
System.out.print(" " + j);
}
System.out.println();
}
}
}
Upvotes: 0
Reputation: 40034
Here is one way. It uses String.repeat()
to pad with leading spaces.
int rows = 6;
for (int i = 1; i <= rows; i++) {
System.out.print(" ".repeat(rows-i));
for (int k = i; k > 0; k--) {
System.out.print(k+ " ");
}
System.out.println();
}
prints
1
2 1
3 2 1
4 3 2 1
5 4 3 2 1
6 5 4 3 2 1
If you don't want to use String.repeat()
then use a loop.
Upvotes: 1
Reputation: 1308
start k=i
then decrement it till k>=1
.
for(int k= i; k >=1 ; k--)
System.out.print(k+" ");
output
1
2 1
3 2 1
4 3 2 1
5 4 3 2 1
6 5 4 3 2 1
Upvotes: 0
Reputation: 167
Well the only thing you have to do is change order like you are first adding space and then number instead add number and then space. code -
import java.util.Scanner;
public class Pyramid {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
// loop
for (int i=1; i <= 6; i++) {
// numbers
for(int k= 1; k <= i; k++)
System.out.print(k);
// space
for(int j=1; j <= 6-i; j++)
System.out.print(" ");
// new line
System.out.println();
}
}
}
Now we get the result -
Upvotes: 0