Code:
# include <stdio.h>
//This is a function to provide the spacing for the triangle
void spaces(void)
{
printf(" ");
}
//This is a function to calculate the factorial of n
int factorial(int n)
{
int x;
int y=1;
for(x=1; x<=n; x++)
{
y=y*x;
}
return y;
}
//This function calculates ncr - the number in each place of the triangle
//It uses the previous factorial function to do so
int choose(int n, int r)
{
int x;
x=(factorial(n))/((factorial(n))*(factorial(n-r)));
return x;
}
//This function calculates ncr - the number in each place of the triangle
//It uses the previous factorial function to do so
int choose(int n, int r)
{
int x;
x=(factorial(n))/((factorial(n))*(factorial(n-r)));
return x;
}
//This function prints the triangle
//It uses the spaces and choose functions to do so
void triangle(int n)
{
int row;
int col;
int x;
int y=n-1;
//This statement decides where to put spaces and numbers depending on the input and using the choose function
for(row=1; row<=n; row++)
{
for(col=0; col<row; col++)
{
if(col==0)
{
for(x=y; x>0; x--)
{
printf(" ");
}
y--;
}
}
printf("%d", choose(row - 1, col));
//This statement chooses how much space to print depending on the number of digits in the surrounding numbers
if(((choose(row-1, col)/10)!=0)&&(choose(row-1, col)/100==0))
{
printf(" ");
}
else if(((choose(row-1, col)/10)!=0)&&(choose(row-1, col)/100!=0))
{
printf(" ");
}
else
{
spaces ();
}
}
printf("\n");
}
//This is the main function of the program
//It asks and scans for the number of rows in the program
int main (void)
{
printf("What is the number of rows in Pascal's triangle? ");
int rows;
scanf("%d", &rows);
//This ensures the program is repeated while rows is greater than or equal to 0
while (rows>=0)
{
//This statement makes the triangle function run when rows is greater than 0
if(rows!=0)
{
triangle (rows);
}
printf("What is the number of rows in Pascal's triangle? ");
scanf("%d", &rows);
}
return 0;
}