Problems Associated with Printing Pascal’s Triangle Using For Loop in Java

You may have learnt how to print a Pascal’s Triangle using Java when you took your first or second progamming course in college; you may probably have learnt that there are more than 10 ways to do it; you may also understand that For Loop is the best way to do it. Here is the coding:

 

package yanghuiSanjiao;

 

import java.util.Scanner;

 

class Yanghui{

int m;

int a[][] ;

 

public static void yh(int m){

 

int a[][] = new int[m][m];

 

for (int x=0;x<m;x++){

 

for(int y=0;y<=x;y++){

 

if(x==y || y == 0){

 

a[x][y]=1;

 

}

else {

 

a[x][y] = a[x-1][y-1]+a[x-1][y];

 

}

System.out.print(a[x][y]+”\t”);

}

System.out.println(” “);

}

 

}

 

 

}

 

public class Ynaghuisanjiaolianxi_fengzhuang {

 

public static void main(String[] args){

 

Scanner sc = new Scanner(System.in);

System.out.println(“Please set the number of lines in the Pascal’s Triangle”);

 

int m = sc.nextInt();

Yanghui.yh(m);

 

}

 

}

 

Test showed that for this code, the Pascal’s Triangle it printed out is like this:

 

Neat and beautiful – isn’t it?

 

But how about we try to do something more? As I looked through all the testbooks available in either computer science or java programming, all of them chose For Loop. However, you may also have probably heard that While Loop, a feature that’s quite similar to For Loop yet also varies from it in functinalities, can convert from For Loop almost perfectly.

So why don’t we print this Triangle using While Loop?

Let’s test it – fortunately, because of the similarity in their structures, a little revision on the original code can make it While-wise.

Code:

 

package yanghuiSanjiao;

 

import java.util.Scanner;

 

class Yanghui{

int m;

int a[][] ;

 

public static void yh(int m){

 

int a[][] = new int[m][m];

int x=0;

int y=0;

while (x<m){

 

while(y<=x){

 

if(x==y || y == 0){

 

a[x][y]=1;

 

}

else {

 

a[x][y] = a[x-1][y-1]+a[x-1][y];

 

}

System.out.print(a[x][y]+”\t”);

x++;

}

System.out.println(” “);

y++;

}

 

}

 

 

}

 

public class Ynaghuisanjiaolianxi_fengzhuang {

 

public static void main(String[] args){

 

Scanner sc = new Scanner(System.in);

System.out.println(“Please set the number of lines in the Pascal’s Triangle”);

 

int m = sc.nextInt();

Yanghui.yh(m);

 

}

 

}

It looks perfect right?

But guess what does it print? I suppose that you must have figured out that the way I speak implied something wrong.

There must be something wrong with it – right?

 

 




Sites DOT MIISThe Middlebury Institute site network.