I need to write a Java-Code which prints the pascal's triangle. This is what I did until now.
import java.util.Scanner;
class Pascal {
static int bnk (int n, int k) {
if (k==0 || k==n) {
return 1;
} // B(n,k) Berechnung für Standardwert = 1;
else {
int x = (bnk(n-1, k-1) + bnk(n-1, k));
return x;
} // Berechnung aller sonstigen B(n,k)-Werte.
} // Berechnung von B(n,k)
public static void main (String [] args) {
Scanner sc = new Scanner(System.in);
System.out.println("How many rows?: ");
int r = sc.nextInt();
sc.close();
for (int n=0; n<r; n++) {
for (int j=0; j<(r-n); j++) {
System.out.print(" ");
} // Setzt Anzahl Leerzeichen vor erster Zahl
for (int k=0; k<=n; k++) {
int b = bnk(n,k);
System.out.print(b+" ");
} // Berechnet in jeder Reihe alle Elemente
System.out.println();
} // Berechnet Reihe nach Reihe
} // main
} // class Pascal
The first method calculates the values needed in the triangle. The second one prints the triangle row after row by printing (r-n) blanks. n stands for the current row and r is the total count of rows. So the left side of the triangle gets printed in the right way but the problem is, when the values in the triangle are getting too high, the triangle gets out of shape on the right side. I hope what i described was understandable. Could you help me find a way to properly format the triangle?
The current output looks like this:
5 rows: https://gyazo.com/d9a536d3ac92c155707ebb2e4ee7745b


So you could format with
"\t"but instead of using 1, use 2. Then you would be able to space the numbers every 1 space or every 2 spaces, allowing the first (top) one to be in between the second 2, and repeat.