The assignment is to create Pascal\'s Triangle without using arrays. I have the method that produces the values for the triangle below. The method accepts an integer for the
public static long pascalTriangle(int r, int k)
{
if(r == 1 || k <= 1 || k >= r) return 1L;
return pascalTriangle(r-1, k-1) + pascalTriangle(r-1, k);
}
This method allows you to find the kth value of rth row.
import java.util.*;
class Mine
{
public static void main(String ar[])
{
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
for(int i=1;i<n;i++)
{
int size=1;
for(int j=1;j<=i;j++)
{
int a[]=new int[size];
int d[]=new int[size];
for(int k=1;k<=size;k++)
{
a[1]=1;
a[size]=1;
for(int p=1;p<=size;p++)
{
d[p]=a[p];
}
if(size>=3)
{
for(int m=2;m<size;m++)
{
a[m]=d[m]+d[m-1];
}
}
}
for(int y=0;y<size;y++)
{
System.out.print(a[y]);
}
System.out.println(" ");
}
++size;
}
}
}
public static void main(String[] args)
{
int a, num;
for (int i = 0; i <= 4; i++)
{
num = 1;
a = i + 1;
for(int j=4;j>0;j--)
{
if(j>i)
System.out.print(" ");
}
for (int j = 0; j <= i; j++)
{
if (j > 0)
num = num * (a - j) / j;
System.out.print(num + " ");
}
System.out.println();
}
}
Code perfectly prints pascal triangle
You can try this code in java. It's simple :)
public class PascalTriangle {
public static void main(String[] args) {
int rows = 10;
for(int i =0;i<rows;i++) {
int number = 1;
System.out.format("%"+(rows-i)*2+"s","");
for(int j=0;j<=i;j++) {
System.out.format("%4d",number);
number = number * (i - j) / (j + 1);
}
System.out.println();
}
}
}
In each row you will need to print:
n
spacesm
numbersn
spacesYour job is to figure out n
(which will be zero in the last line) and m
based on row number
.
[This is more like a comment but I needed more formatting options than comments provide]
This is a good start, where it's homework, I'll leave the rest to you:
int maxRows = 6;
int r, num;
for (int i = 0; i <= maxRows; i++) {
num = 1;
r = i + 1;
//pre-spacing
for (int j = maxRows - i; j > 0; j--) {
System.out.print(" ");
}
for (int col = 0; col <= i; col++) {
if (col > 0) {
num = num * (r - col) / col;
}
System.out.print(num + " ");
}
System.out.println();
}