I'm trying to print a half pyramid with numbers and stars together and the output must be like this:
1 1 1 1 1 1 1
2 * * * * 2
3 * * * 3
4 * * 4
5 * 5
6 6
7
Here is the code that I've done so far:
public class numberplsustar {
public static void main(String[] args) {
int rows = 7, i, j, num;
for (i = rows; i >= 1; i--) {
for (j = 1; j <= i; ++j) {
if (i >= 3 && i <= 6) {
System.out.print("* ");
} else
System.out.print(i + " ");
}
System.out.println();
}
}
}
And this is the output:
7 7 7 7 7 7 7
* * * * * *
* * * * *
* * * *
* * *
2 2
1
The problem is you don't check for the first character and the last character to print the values. Also start printing from rows: 7.
You should start printing from 1 (j=1), than increment the value on each time j++.
You should check for which value to be printed on each step:
(i == rows || i == 2 || temp == 1) ? j : "*"
prints j (number) :
i == rows : for the first row (1 1 1 1 1 1 1)
i == 2 : for the row before the last one (6 6)
temp == 1 : for the numbers at the end of rows
otherwise prints *
Try this:
public static void main(String[] args) {
int rows = 7;
for (int i = rows, j = 1; i > 0; i--, j++) {
System.out.print(j);
for (int temp = i - 1; temp > 0; temp--) {
System.out.print(" " + ((i == rows || i == 2 || temp == 1) ? j : "*"));
}
System.out.print("\n");
}
}
Output:
1 1 1 1 1 1 1
2 * * * * 2
3 * * * 3
4 * * 4
5 * 5
6 6
7
PS: In Java the first letter of class names should be capitalized according to naming conventions.
just print every characterindividualy and if its on the outline you print the number
public class piramid {
public static void main(String[] args) {
int n = 7;
for (int i=1; i<n; i++) {
for (int x=n; x>i; x--) {
if (i == 1 || x == n || x==i+1) {
System.out.print(i);
}
else {
System.out.print("*");
}
System.out.print(" ");
}
System.out.println("");
}
}
}
this code outputs this
1 1 1 1 1 1
2 * * * 2
3 * * 3
4 * 4
5 5
6
in response to your comment:
this would work:
public class piramid {
public static void main(String[] args) {
int n = 7;
for (int i=1; i<n; i++) {
for (int x=0; x<i; x++) {
if (i == n-1 || x == 0|| x == i-1) {
System.out.print(i);
}
else {
System.out.print("*");
}
System.out.print(" ");
}
System.out.println("");
}
}
}
and the output is
1
2 2
3 * 3
4 * * 4
5 * * * 5
6 6 6 6 6 6
Solution
Check if i == 1(first) row -> print i
Check if j is at the edge j==i || j == range -> print i
else print "*"
public static void main(String[] args) {
int range = 7;
for(int i = 1; i <= range; i++){
for(int j = range; j >= i ; j--){
if(i == 1){
System.out.print(i);
}else if(j == range || j == i){
System.out.print(i);
}else{
System.out.print("*");
}
}
System.out.println();
}
}
Outsputs
1 1 1 1 1 1 1
2 * * * * 2
3 * * * 3
4 * * 4
5 * 5
6 6
7
To print a triangle in some corner of a 2d array, you can use two nested for loops (or streams) and two nested conditional statements (or ternary operators). Your code might look something like this:
int m = 7;
IntStream.range(0, m)
.mapToObj(i -> IntStream.range(0, m)
// 'i' - row, 'j' - column
.mapToObj(j ->
// triangle corner:
// upper left: 'i + j < m'
// lower right: 'i + j >= m - 1'
// lower left: 'i >= j'
// upper right: 'i <= j'
i + j >= m - 1 ?
// triangle boundaries:
// top: 'i == 0'
// bottom: 'i == m - 1'
// left: 'j == 0'
// right: 'j == m - 1'
// primary diagonal: 'i == j'
// secondary diagonal: 'i + j == m - 1'
i == m - 1 || j == m - 1 || i + j == m - 1 ?
// row number
(i + 1) + " "
// otherwise asterisk
: "* "
// otherwise whitespace
: " ")
// collect into one line
.collect(Collectors.joining()).stripTrailing())
// print line by line
.forEach(System.out::println);
Output:
1
2 2
3 * 3
4 * * 4
5 * * * 5
6 * * * * 6
7 7 7 7 7 7 7
int m = 7;
for (int i = 0; i < m; i++) {
String row = "";
for (int j = 0; j < m; j++) {
if (i <= j) {
if (i == 0 || j == m - 1 || i == j) {
row += (i + 1) + " ";
} else {
row += "* ";
}
} else {
row += " ";
}
}
System.out.println(row.stripTrailing());
}
Output:
1 1 1 1 1 1 1
2 * * * * 2
3 * * * 3
4 * * 4
5 * 5
6 6
7
Related
I am writing some code that creates a incrementing number right angle triangle that looks something like this:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4 5 6
I am unsure on how to make my code output a triangle to that shape as my code outputs the same thing except inverted.
This is the code I have:
public class Main {
public static void main(String[] args) {
int rows = 6;
for (int i = 1; i <= rows; ++i) {
for (int j = 1; j <= i; ++j) {
System.out.print(j + " ");
}
System.out.println();
}
}
}
My speculation is that instead of incrementing some of the values I would decrement them however the code would run infinite garbage values and not what I wanted.
It is needed to print some spaces before printing the numbers in each row, and the number of spaces should be decreasing depending on the row:
int rows = 6;
for (int i = 1; i <= rows; ++i) {
for (int j = rows - i; j >= 1; j--) {
System.out.print(" ");
}
for (int j = 1; j <= i; ++j) {
System.out.print(j + " ");
}
System.out.println();
}
This prefix may be build using String::join + Collections::nCopies:
System.out.print(String.join("", Collections.nCopies(rows - i, " ")));
Or since Java 11, this prefix may be replaced using String::repeat:
System.out.print(" ".repeat(rows - i));
Instead of two nested for loops, you can use a single while loop with two incrementing variables. The number of iterations stays the same.
int n = 7, i = 0, j = 0;
while (i < n) {
// element
if (i + j >= n - 1) {
// print an element
System.out.print(i + j + 2 - n);
} else {
// print a whitespace
System.out.print(" ");
}
// suffix
if (j < n - 1) {
// print a delimiter
System.out.print(" ");
j++;
} else {
// print a new line
System.out.println();
j = 0;
i++;
}
}
Output:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4 5 6
1 2 3 4 5 6 7
See also: Optimized Bubble Sort
Your approach is almost correct - use two nested for loops, all that remains is to add one if else statement and calculate the sum of coordinates i and j.
Try it online!
public static void main(String[] args) {
int n = 6;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
System.out.print(" ");
int sum = i + j;
if (sum > n)
System.out.print(sum - n);
else
System.out.print(" ");
}
System.out.println();
}
}
Output:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4 5 6
See also: Printing a squares triangle. How to mirror numbers?
You can print an inverted triangle using two nested for-loops as follows:
// the number of rows and the
// number of elements in each row
int n = 6;
// iterating over rows with elements
for (int i = 0; i < n; i++) {
// iterating over elements in a row
for (int j = 0; j < n; j++) {
// element
if (i + j >= n - 1) {
// print an element
System.out.print(i + j + 2 - n);
} else {
// print a whitespace
System.out.print(" ");
}
// suffix
if (j < n - 1) {
// print a delimiter
System.out.print(" ");
} else {
// print a new line
System.out.println();
}
}
}
Output:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4 5 6
See also: How to draw a staircase with Java?
You have to print spaces before printing the numbers to make the triangle look inverted, the number of spaces depends on the amount of numbers you skip which are rows-i, so you can loop from i to rows and print space in each iteration.
int rows = 6;
for (int i = 1; i <= rows; ++i) {
for (int j = i; j < rows; j++) {
System.out.print(" ");
}
for (int j = 1; j <= i; ++j) {
System.out.print(j + " ");
}
System.out.println();
}
Output:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4 5 6
You can use the property that for the row containing i as the greatest number of the row the number of the spaces can be calculated as 2*(rows-i). You can rewrite your program like below:
public class Main {
public static void main(String[] args) {
int rows = 6;
for (int i = 1; i <= rows; ++i) {
for (int nspaces = 0; nspaces < 2 * (rows - i); ++nspaces) {
System.out.print(" ");
}
for (int j = i; j > 0; --j) {
System.out.print(j + " ");
}
System.out.println();
}
}
}
Output:
1
2 1
3 2 1
4 3 2 1
5 4 3 2 1
6 5 4 3 2 1
i cant print this pattern :
1 2 3 4 *
1 0 0 * 5
1 0 * 0 5
1 * 0 0 5
* 2 3 4 5
i tried to print but only on row :
public class Pattern {
public static void main(String[] args) {
for(int j=1;j<=5;j++)
{
if(j>4) {
System.out.print("*");
}
else {
System.out.print(j);
}
}
}
}
Let's try to consider the logic of this output:
You have an NxN matrix, with rows and columns numbered 1..N.
If you're on the secondary diagonal (i.e. row+column=N+1), print a *
Else, if you're on the borders (i.e., either the row or the column is 1 or N), print the column number
Else, print a 0
Now, you just need to convert this logic to Java:
int size = 5;
for (int i = 1; i <= size; ++i) {
for (int j = 1; j <= size; ++j) {
char ch;
if (i + j == size + 1) {
ch = '*';
} else if (i == 1 || i == size || j == 1 || j == size) {
ch = (char) ('0' + j);
} else {
ch = '0';
}
System.out.print(ch + " ");
}
System.out.println();
}
I did this below but I didn't get it right,
int i = 1;
while(i <= 6){
for(int j = 1;j <= 6-i;j++){
System.out.print(" ");
}
for(int m = 1; m <= i; m++){
System.out.print(m + " ");
}
i++;
System.out.println();
}
I got this instead :
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4 5 6
But I need guide on how to get this below,
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
while(i <= 6){
for(int j = 1; j <= 6 - i; j++){
System.out.print(" ");
}
for(int m = i-1; m > 1; m--){
System.out.print(m + " ");
}
for(int m = 1; m < i; m++){
System.out.print(m + " ");
}
i++;
System.out.println();
}
This should work for you, i just added / edited this part:
for(int m = i-1; m > 1; m--){
System.out.print(m + " ");
}
for(int m = 1; m < i; m++){
System.out.print(m + " ");
}
To let it count down again, and let it count up afterwards
This should do the trick, but it's important to understand what is going on:
public class Main {
public static void main(String[] args) {
for (int i = 0; i <= 6; i++) {
printRow(6, i);
}
}
public static void printRow(int highestValue, int rowValue) {
for (int i = 0; i < (highestValue - rowValue); i++) {
System.out.print(" ");
}
for (int i = rowValue; i >= 1; i--) {
System.out.print(i + " ");
}
for (int i = 2; i <= rowValue; i++) {
System.out.print(i + " ");
}
System.out.println();
}
}
The first loop pads the left side of the pyramid, as you have already done. The second loop counts down from the value of the row to 1, which is the center of the pyramid. The third loop counts back up from 2 to the value of the row. Note that for the first row, 2 will not be printed, because i = 2 is greater than rowValue, which is 1, so the loop is skipped.
Running this results in the following:
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
Note that a row starting with 6 is printed since I used the bounds you provided. If this is not what should be done (from your example output), I will leave that up to you on how to fix this. Pay attention to the name of the arguments in the printRow method to see why there is an extra row printed.
There you have my solution, little smarty solution with using absolute value, with notes why is what where
public static void printPyramid(int rows) {
// row counter
for (int i = 1; i <= rows; i++) {
// padding- size = rows - i
for (int j = 1; j <= rows - i; j++) {
// 2 spaces - char + space
System.out.print(" ");
}
// print numbers
for (int j = -i; j <= i; j++) {
// we want only once 1, and skip print zero
if (j == 0 || j == 1) {
continue;
}
// print absolute value
System.out.print(Math.abs(j) + " ");
}
// new row- println same as print("\n");
System.out.println();
}
}
With 6 rows, 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
Let's break this down into parts. First we need to figure out how to output a single level of the pyramid. Let's start without padding. For the first level it's just "1", for every other level it's the level above it surrounded by the "number" of that level (and the spaces).
private static String buildLevel(int num) {
if (num == 1) return "1";
return Integer.toString(num) + " " + buildLevel(num -1) + " " + Integer.toString(num);
}
We then need to be able to add the padding, so let's create a method that pads to a certain length.
private static String pad(String stringToPad, int padTo) {
return String.join("", Collections.nCopies(padTo - stringToPad.length(), " ")) + stringToPad;
}
Putting this together we can create a method to build a pyramid by looping over the needed levels and concatenating the levels together.
private static String buildPyramid(int height) {
int expectedLength = height * 2 + 1;
String out = "";
for (int i = 1; i <= height; i++) {
out += pad(buildLevel(i), expectedLength) + "\n";
expectedLength += 2;
}
return out;
}
The length of the first line is the height * 2 + 1, derived by counting. (This includes two spaces at the beginning of each line, which is in your examples). Each subsequent line should be 2 longer than the one above it.
Call it like this to produce your example
public static void main(String[] args) {
System.out.println(buildPyramid(5));
}
Outputs:
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
For completeness, here is all the code in one block.
private static String buildLevel(int num) {
if (num == 1) return "1";
return Integer.toString(num) + " " + buildLevel(num -1) + " " + Integer.toString(num);
}
private static String pad(String stringToPad, int padTo) {
return String.join("", Collections.nCopies(padTo - stringToPad.length(), " ")) + stringToPad;
}
private static String buildPyramid(int height) {
int expectedLength = height * 2 + 1;
String out = "";
for (int i = 1; i <= height; i++) {
out += pad(buildLevel(i), expectedLength) + "\n";
expectedLength += 2;
}
return out;
}
public static void main(String[] args) {
System.out.println(buildPyramid(6));
}
I need to draw a numeric diamond, for example with a height of 9:
1
222
33333
4444444
555555555
4444444
33333
222
1
I wrote the code and I managed to get the same diamond, but with stars. I want it with these numbers. How can I do that? Here is what I have done so far:
for (int i = 1; i < 10; i += 2) {
for (int j = 0; j < 9 - i / 2; j++)
System.out.print(" ");
for (int j = 0; j < i; j++)
System.out.print("a");
System.out.print("\n");
}
for (int i = 7; i > 0; i -= 2) {
for (int j = 0; j < 9 - i / 2; j++)
System.out.print(" ");
for (int j = 0; j < i; j++)
System.out.print("b");
System.out.print("\n");
}
Regarding your code:
System.out.print("\n"); should be replaced by System.out.println().
You should a dynamic height instead of hard-coding 9.
It prints the correct pattern, only what is printed is wrong: instead of printing "a" and "b", you should print the index of the loop and see what you can get from there. This is #Tsung-Ting Kuo solution.
You can do it with fewer loops and a more understandable in my view. Consider the following algorithm:
For each row of the pattern (so the row goes from 0 to height excluded)
For each column of the pattern (so the column goes from 0 to height excluded)
We need to print a space when we are in the upper-right, upper-left, lower-right or lower-left of the diagram.
Upper-left: This is when the column is less than height/2-row-1
Lower-left: This is when the column is less than row-height/2
Factoring these two expressions in a single one, this is when the column is less than height/2 - min where min = Math.min(row+1, height-row).
Upper-right: This is when the column is greater than height/2+row+1
Lower-right: This is when the column is greater than height/2+height-row
Factoring these two expressions in a single one, this is when the column is greater than height/2 + min where min = Math.min(row+1, height-row).
Otherwise, we need to print Math.min(row+1, height-row).
Turning into code:
public static void main(String[] args) {
int height = 9;
for (int row = 0; row < height; row++) {
for (int column = 0; column < height; column++) {
int min = Math.min(row+1, height-row);
if (column <= height / 2 - min || column >= height / 2 + min) {
System.out.print(" ");
} else {
System.out.print(min);
}
}
System.out.println();
}
}
Sample output:
1
222
33333
4444444
555555555
4444444
33333
222
1
java-11
Using String#repeat introduced as part of Java-11, you can do it using a single loop.
public class Main {
public static void main(String[] args) {
final int MID_ROW_NUM = 5;
for (int i = 1 - MID_ROW_NUM; i < MID_ROW_NUM; i++) {
int x = Math.abs(i);
System.out.println(" ".repeat(x) + String.valueOf(MID_ROW_NUM - x).repeat((MID_ROW_NUM - x) * 2 - 1));
}
}
}
Output:
1
222
33333
4444444
555555555
4444444
33333
222
1
You can print a variant of the diamond simply by increasing the amount of space by one character:
public class Main {
public static void main(String[] args) {
final int MID_ROW_NUM = 5;
for (int i = 1 - MID_ROW_NUM; i < MID_ROW_NUM; i++) {
int x = Math.abs(i);
System.out.println(" ".repeat(x) + ((MID_ROW_NUM - x) + " ").repeat((MID_ROW_NUM - x) * 2 - 1));
}
}
}
Output:
1
2 2 2
3 3 3 3 3
4 4 4 4 4 4 4
5 5 5 5 5 5 5 5 5
4 4 4 4 4 4 4
3 3 3 3 3
2 2 2
1
Please try the following code (I have tested it), only change two print:
public static void main(String[] args) throws Exception {
for (int i = 1; i < 10; i += 2) {
for (int j = 0; j < 9 - i / 2; j++)
System.out.print(" ");
for (int j = 0; j < i; j++)
System.out.print(i/2+1); // Change here
System.out.print("\n");
}
for (int i = 7; i > 0; i -= 2) {
for (int j = 0; j < 9 - i / 2; j++)
System.out.print(" ");
for (int j = 0; j < i; j++)
System.out.print(i/2+1); // Change here
System.out.print("\n");
}
}
Output:
1
222
33333
4444444
555555555
4444444
33333
222
1
You can draw a numeric rhombus using IntStream as follows:
int m = 5;
int n = 5;
String[][] arr = IntStream
.rangeClosed(-m, m)
.map(Math::abs)
.mapToObj(i -> IntStream
.rangeClosed(-n, n)
.map(Math::abs)
.mapToObj(j -> i + j > Math.max(m, n) ? " " : "" + (m - i))
.toArray(String[]::new))
.toArray(String[][]::new);
// formatted output
Arrays.stream(arr).map(row -> String.join(" ", row)).forEach(System.out::println);
0
1 1 1
2 2 2 2 2
3 3 3 3 3 3 3
4 4 4 4 4 4 4 4 4
5 5 5 5 5 5 5 5 5 5 5
4 4 4 4 4 4 4 4 4
3 3 3 3 3 3 3
2 2 2 2 2
1 1 1
0
See also: Filling a 2d array with numbers in a rhombus form • Print this diamond
I made a Java program that prints out a pascal triangle, however I can't figure out how to correctly position it.
Program 1
public class Triangle {
public static void main() {
System.out.println("\nTriangle: ");
int row = 11;
long[][] triangle = new long[row][row];
triangle[1][1] = 1;
System.out.print(triangle[1][1] + "\n");
for (int i = 2; i < row; i++) {
for (int n = 1; n < row; n++) {
triangle[i][n] = triangle[i-1][n-1] + triangle[i-1][n];
if (triangle[i][n] > 0) {
System.out.print(triangle[i][n] + " ");
}
}
System.out.println();
}
}
}
Output:
1
1 1
1 2 1
1 3 3 1
Program 2
public class Triangle {
public static void main() {
System.out.println("\nTriangle: ");
int row = 11;
long[][] triangle = new long[row][row];
int x = 1;
while (x < row - 1) {
System.out.print(" ");
x++;
}
triangle[1][1] = 1;
System.out.print(triangle[1][1] + "\n");
for (int i = 2; i < row; i++) {
x = i;
while (x < row - 1) {
System.out.print(" ");
x++;
}
for (int n = 1; n < row; n++) {
triangle[i][n] = triangle[i-1][n-1] + triangle[i-1][n];
if (triangle[i][n] > 0) {
System.out.print(triangle[i][n] + " ");
}
}
System.out.println();
}
}
}
Output:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1 //(Notice this line is incorrectly positioned)
When the triangle approaches multiple digit numbers, it starts to break down and makes it ugly. Can someone explain how I can display a normal triangle instead of this ugly one?
Dynamic Pascal Triangle generator is here:
import java.io.IOException;
import java.util.Scanner;
public class Main {
static double fact(int n) {
double result = 1;
for (double i = 1; i <= n; i++)
result *= i;
return result;
}
static double combine(int n, int r) {
return ((fact(n)) / (fact(n - r) * fact(r)));
}
static void pascalTriangle(int n) {
int n2 = n;
for (int i = 0; i < n; i++) {
for (int space = 8 * (n2 - 1); space >= 0; space--) {
System.out.printf(" ");
}
for (int j = 0; j <= i; j++) {
System.out.printf("%14.0f", combine(i, j));
System.out.printf(" ");
}
System.out.println();
n2--;
}
}
public static void main(String[] args)
throws IOException, InterruptedException {
#SuppressWarnings("resource")
Scanner sc = new Scanner(System.in);
System.out.print("Enter Number of Lines(n): ");
int n = sc.nextInt();
pascalTriangle(n);
System.out.println("Press any key to exit! ");
sc.nextByte();
}
}
Try this ...
Results:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
import java.util.*;
public class HelloWorld {
static int binCoeff(int n, int k) {
int res = 1;
if (k > n - k)
k = n - k;
for (int i = 0; i < k; ++i) {
res *= (n - i);
res /= (i + 1);
}
return res;
}
static void pascalTriangle(int lines) {
for (int i = 0; i < lines; i++) {
for (int j = 0; j <= i; j++)
System.out.print(HelloWorld.binCoeff(i, j) + " ");
System.out.println();
}
}
public static void main(String[] args) {
System.out.println("Results: ");
HelloWorld.pascalTriangle(8);
}
}
/**
* #author Ranjith
*/
public class JavaApplication2 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
int i;
int x;
int n = 15; //number of rows
String newLine = System.getProperty("line.separator");
for (i = 0; i < n; i++) { //loop to adjust spacing
x = i;
while (x < n - 1) {
System.out.print(" ");
x++;
}
fib(i); //fibonacci function is called
System.out.print(newLine);
}
}
public static void fib(int num) { //fibonacci function
int[] febo = new int[100];
febo[0] = 0;
febo[1] = 1;
for (int i = 2; i < num; i++) {
febo[i] = febo[i - 1] + febo[i - 2];
}
for (int i = 0; i < num; i++) {
System.out.print(febo[i] + " ");
}
}
}
Output:
0
0 1
0 1 1
0 1 1 2
0 1 1 2 3
0 1 1 2 3 5
0 1 1 2 3 5 8
0 1 1 2 3 5 8 13
0 1 1 2 3 5 8 13 21
0 1 1 2 3 5 8 13 21 34
0 1 1 2 3 5 8 13 21 34 55
0 1 1 2 3 5 8 13 21 34 55 89
0 1 1 2 3 5 8 13 21 34 55 89 144
0 1 1 2 3 5 8 13 21 34 55 89 144 233
You can represent such a triangle as a 2d array, where the elements of the first row and column are equal to one, and all other elements are the sum of the previous element in the row and column.
arr[i][j] = arr[i][j-1] + arr[i-1][j];
Then you can position it in the upper left corner as follows:
1 1 1 1 1 1 1 1 1
1 2 3 4 5 6 7 8
1 3 6 10 15 21 28
1 4 10 20 35 56
1 5 15 35 70
1 6 21 56
1 7 28
1 8
1
Try it online!
public static void main(String[] args) {
int n = 9;
// an array of 'n' rows
int[][] arr = new int[n][];
// iterate over the rows of the array
for (int i = 0; i < n; i++) {
// a row of 'n-i' elements
arr[i] = new int[n - i];
// iterate over the elements of the row
for (int j = 0; j < n - i; j++) {
if (i == 0 || j == 0) {
// elements of the first row
// and column are equal to one
arr[i][j] = 1;
} else {
// all other elements are the sum of the
// previous element in the row and column
arr[i][j] = arr[i][j - 1] + arr[i - 1][j];
}
}
}
// formatted output
for (int[] row : arr) {
for (int el : row) {
// formatting as a number with a trailing space
System.out.printf("%2d ", el); // two-digit number
// System.out.printf("%3d ", el); // three-digit number
// System.out.printf("%4d ", el); // four-digit number
}
System.out.println();
}
}
See also:
• Pascal's triangle 2d array - formatting printed output
• Print Pascal's Triangle
class pascal {
static void main(int n) {
int a[][] = new int[n][n + 1];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
a[i][j] = 0;
}
}
a[0][1] = 1;
int k = 5;
int p = 0;
for (int i = 1; i < n; i++) {
for (int j = 1; j < n + 1; j++) {
a[i][j] = a[i - 1][j] + a[i - 1][j - 1];
}
}
for (int i = 0; i < a.length; i++) {
for (p = n + -i; p > 0; p--) {
System.out.print(" ");
}
for (int j = 0; j < a[i].length; j++) {
if (a[i][j] != 0) {
System.out.print(a[i][j] + " ");
} else {
System.out.print(" ");
}
}
System.out.println();
}
}
}