I'm currently working on a project to display Pascal's Triangle and the binomials up to a certain row that the user inputs.
I have the triangle done, but I'm having a bit of trouble getting the binomials to work.
This is what the output should look like for the binomials:
(x + y)^0 = 1
(x + y)^1 = x + y
(x + y)^2 = x^2 + 2xy + y^2
(x + y)^3 = x^3 + 3x^2y + 3xy^2 + y^3
(x + y)^4 = x^4 + 6x^2y^2 + 4xy^3 + y^4
(x + y)^5 = x^5 + 5x^4y + 10x^3y^2 + 10x^2y63 + 5xy^4 + y^5
Here is my code. As you can see Pascal's Triangle outputs right. The binomials...not so much.
using System;
public class Project3
{
public static void Main()
{
int rows = 0;
Console.Write("Enter an integer bound: ");
rows = Convert.ToInt32(Console.ReadLine());
//Calculate row (i)
for (int i = 0; i < rows; i++)
{
//Calculate Column (j)
for (int j = 0; j <= 2 * rows - i * 2; j++)
{
Console.Write(" ");
}
for (int j = 0; j <= i; j++)
{
//Calculate coefficent of row and column
int entry = factorial(i) / (factorial(j) * factorial(i - j));
Console.Write(entry);
if (entry < 10)
{
Console.Write(" ");
}
else
{
Console.Write(" ");
}
}
Console.WriteLine("");
}
//Polynomials
//Calculate row (i)
string x = "";
string y = "";
for (int i = 0; i < rows; i++)
{
//Calculate Column (j)
int xexpo = i;
int yexpo = 0;
for (int j = 0; j <= 2 * rows - i * 2; j++)
{
//Calculate coefficent of row and column
int entry = factorial(i) / (factorial(j) * factorial(i - j));
Console.WriteLine("(x + y)^" + i + "=" + "x" + "^" + xexpo + " + " + "y^" + yexpo + entry);
}
}
}
//Calculate n (factorial)
public static int factorial(int n)
{
int retval = 1;
for (int i = 1; i <= n; i++)
{
retval = retval * i;
}
return retval;
}
}
I know this will be done similarly to how I coded the triangle. The issue is the way its outputting. Our teacher said that we should start by copying and pasting the code used to get the triangle and removing the code that adds spaces.
The first line should be 1. Also, when an exponent is 1, the exponent won't be printed at all. (I know this can be accomplished with if statements.)
Any ideas to help get my on the right track?