Printing Pascal Triangle using java.
Printing Pascal Triangle using java.
Hi,
I got an assignment on coding, it asked me to write a code that will print out pascal triangle in this format:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
I have been stuck on this question for days now, literally. The closest I can get is this:
1
1 1
1 2 1
1 3 1
1 4 1
1 5 1
which is not what I wanted at all.
This is my code :
int PreviousRow = 1;
int CurrentRow = 0;
for (int rows = 0; rows <= 5; rows++)
{
//storing the sum of the number above
CurrentRow = PreviousRow + rows;
for (int space = 6; space > 0; space–)
{
System.out.println(“”);
}
for (int col1 = 1 ; col1 < 2; col1++)
{ //keep printing 1 on each rows
System.out.print(1);
}
for (int col2 = 0; col2 < 1; col2++)
{
if (rows == 0)
{
System.out.println();
}
/*
* reason why i subtract 1 off because
* when rows + PreviousRow it adds up to 2 which
* in the first row I want it to be 1 1
*/
else if (rows >=1 && rows < 2)
{
System.out.print(CurrentRow -1 );
}
/*
* when the row in 2 or more I want it to print
* the two in the middle. but when the row is 2 and it
* adds up with PreviousRow(which is one) it will become
* 3
*/
else if (rows >= 2)
{
System.out.print(CurrentRow – 1);
System.out.print(1);;
}
}
I know this looks horrible, and that’s why I need someone to help me get through this.
"You need a similar assignment done from scratch? Our qualified writers will help you with a guaranteed AI-free & plagiarism-free A+ quality paper, Confidentiality, Timely delivery & Livechat/phone Support.
Discount Code: CIPD30
Click ORDER NOW..


