How to print Pascal’s triangle in C programming | Pascal Pyramid

Dear Learner, Today I will teach you how to make pascal’s triangle using C programming. I hope all of you now know about the pascal triangle. In the pascal triangle, it starts with 1 and ends with 1.

As we print this triangle using programming knowledge, So we have to think of this triangle as a programmer. Look at the picture at top of this article.

Pascal’s Triangle concept in C programming

In this picture, you will see there is 5 column of this triangle. And the value of this triangle is printed after 4 spaces. In the second row, the value is printed after 3 spaces, and in the third-row value is printed after 2 spaces. And at the last row, there is space before value.

Basic Concept:

  • At first, we have to take the value from the user for the number of rows;
  • If our value is 7 then we print 6 spaces.
  • After spaces, we print Pascal triangle Value.
  • For printing value, we use an equation.

Pascal’s Triangle Code in C Programming

#include<stdio.h>
int main(){
    
     int row, col, k, n, value;
     printf("Enter number of Row:");
     scanf("%d", &n);
      for(row=1; row<=n; row++){


        for(col=1; col<=n-row; col++){

            printf(" ");
        }
        value=1;
        for(k=1; k<=row; k++){
            printf("%d ", value);
            value=value*(row-k)/k;

        }
        printf("\n");
      }
     
     return 0;
}

The output of Pascal’s Triangle Code:

Code Explanation:

In our code, we take 5 variables for printing column, Row, and value. At first, we take input from users, How many rows does he want? And we stored the rows amount in variable n. For printing columns and rows, we have to use nested for loop. The first loop will be for the row, and the second, the loop will be for the column.

So we start first for loop and this for loop will end after matching the variable n. Inside the row, for loop, we start the second for loop and this for loop will end when matching n-row. Inside the column loop, we print the spaces.

Now we again run a for loop inside the row for loop. This loop is used for printing the value of the Triangle. Before the loop, we initialize the value variable using 1. Inside the 3rd for loop, we print the value variable, and in the next line, we set a new value in the value variable.

At the end of the first loop, we print a new line.

I hope you understand this simple program. So stay tuned for the next program.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *