Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

Pascal Triangle Program in C

For the programmers that are learning any programming language in the starting days, they will do some of the patterns-related problems. The same is the case with C language programmers who will have come across the pascal triangle problem because the Pascal triangle program in c is one of the standard pattern problems. While moving further in this article we will learn all about the pascal triangle program in c, followed by various methods to implement it.

What is Pascal Triangle?

The pascal triangle is referred to as a mathematical concept that is named after the famous french mathematician Blaise Pascal. The Pascal Triangle is a triangular collection of numbers that displays the coefficients of an extended binomial expression. The numbers in Pascal’s triangle pattern are designed so that each number will be the product of the closest two numbers in the triangle’s upper row and that the number at each row’s ends will be 1.

It is a triangular array of binomial coefficients that is frequently used in algebraic, combinatorial, and probability theory issues. Typically, the Pascal triangle is used to determine things like probability binomial expansion factors and coin toss results.

How to Write Pascal Triangle Program in C?

The triangle shown above is an example of a pascal triangle as you can see at all the extreme ends of the rows we have 1 and for the rest of the elements it is the sum of the two closest elements to it in the upper row. The row is numbered from 0 and all the rows contain n+1 elements in total where n represents the number of rows. The leftmost element of any row is the 1st element.
As the pascal triangle is a special representation of binomial coefficients and it contains the 1 on all the extreme edges of every row. We have various methods to write a pascal program in c.

Approach 1 of writing a Pascal Program in C: Brute Force

In this method we will use two loops to calculate the binomial coefficients by using combination formulas and factorial to print the pascal program in c.

Algorithm
Now we will discuss the algorithm of the above-mentioned approach of writing a pascal program in c.

  • Take the input from the user of the number of rows required in the pascal triangle.
  • Run the outer loop from 0 to n.
  • Run the inner loop from 0 to the outer loop.
  • Now for every pair of values of the inner loop and outer loop we will find the corresponding binomial coefficient.
  • To find the binomial coefficients we first need to find the combination and factorial.
  • Now for every point add the value of two points closest to it in the above row.
  • Repeat this operation and you will get your pascal triangle.

Code Implementation

#include <stdio.h>

int fact(int n) //function to calculate factorial of a number
{
  int a;

  for (a = 1; n > 1; n--)
    a *= n;

  return a;
}

int combination(int n, int r)
{
  return fact(n) / (fact(n - r) * fact(r)); }

int main()
{
  int rows;
  int i, j;

  printf("Enter Number of Rows: ");
  scanf("%d", &rows);

  for (i = 0; i <= rows; i++)
  {
    for (j = 0; j <= rows - i; j++)
      printf("  ");

    for (j = 0; j <= i; j++)
      printf(" %3d", combination(i, j));

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

Input

Enter Number of Rows: 4

Output

           1   1
         1   2   1
       1   3   3   1
     1   4   6   4   1

Explanation of the above code
In the above code we have written the pascal triangle program in c using the brute force.

Time Complexity
The time complexity of the above approach is O(n^3). As we are using the nested loops and also finding the binomial coefficient with them.

Space Complexity
We are not using any additional space hence the space complexity is O(1).

Approach 2 of Pascal Triangle Program in C: Optimized Approach

Now we will discuss the optimal approach. Here we will use a two-dimensional array. That will store the details of the previous rows.

Algorithm
Now we will discuss the algorithm for the optimized approach.

  • We will create a 2d array.
  • We will travel in the 2d array.
  • In the 2d array we will initialize the extreme ends with 1.
  • We will add the value of the two elements of the above row which are closest to the current element.

Dry Run
Now we will see a dry run of the above approach.

  • Step1: The 0th row will look like this:

  • Step 2: Now add the value of the above elements to get the first row which will look like this:

  • Step 3: The second row will contain (2+1=3 ) elements and will look like below

  • Step 4: The 3rd row will contain 4 elements and the elements will look like this.

Code Implementation

#include<stdio.h>

void pascalTriangle(int n) {
int arr[n][n]; 
  
for (int j = 0; j < n; j++) {
    for (int i = 0; i <= j; i++) {
    if (j == i || i == 0)
        arr[j][i] = 1;
    
    else 
        arr[j][i] = arr[j-1][i-1] + arr[j-1][i];
        printf("%3d ", arr[j][i]);
    }
    printf("\n");
    }
}
int main() {
int rows;
    printf("Enter the number of rows: ");
    scanf("%d",&rows);
    pascalTriangle(rows); 
    return 0;
}

Input

Enter the number of rows:  6

Output

 1   1 
 1   2   1 
 1   3   3   1 
 1   4   6   4   1 
 1   5  10  10   5   1

Explanation of the above code
In the above approach we have seen an optimized version of the first approach. We are not calculating the binomial coefficient. We are just using two loops and adding the corresponding elements.

Time Complexity
The time complexity of the above approach is O(N^2). As we are using only two nested loops.

Space Complexity
The space complexity of the above approach is O(N^2). As we are using the extra 2d array.

Approach 3 of Pascal Program in C: Space Optimized

Now we do not use any extra space so it will save the extra space complexity that we are using in the above approach.

Algorithm
Now we will discuss the space-optimized approach of the pascal triangle program in c.

  • First we will take the input from the user.
  • Now we will travel from 1 to n, n is the number of rows.
  • For each row we will run an internal loop.
  • Before the loop we will initialize both the extreme ends of the row by 1.
  • Now we will use the internal loop to calculate the value of the middle elements.
  • And after the calculator of each element the updated value will help us to calculate the further values.

Code Implementation

#include <stdio.h>

void pascalTriangle(int n) {
    for (int j = 1; j <= n; j++) {
        int B = 1; 
        for (int i = 1; i <= j; i++) {
            printf("%d ", B); 
            B = B * (j - i) / i; 
        }
        printf("\n");
    }
}
int main() {
    int nRows;
    printf("Enter number of rows: ");
    scanf("%d", &nRows);
    pascalTriangle(nRows);
    return 0;
}

Input

Enter number of rows: 6

Output

1 1 
1 2 1 
1 3 3 1 
1 4 6 4 1 
1 5 10 10 5 1

Explanation of the above code
In the above approach we have just used some formulas to write the pascal triangle program in c. We are not using any additional space.

Time Complexity
The time complexity of the above approach is O(N^2). As we are using two nested loops.

Space Complexity
The space complexity of the above approach is O(1). We are not using any extra space.

Uses of Pascal Triangle in C

Pascal triangle is a mathematical concept that has wide applications in various fields. Some of them are given below:

  • The pascal triangle is used to calculate the binomial coefficients. And these coefficients are used in probability theory, statistics, etc.
  • It is used to calculate the Fibonacci numbers. As we can use the diagonal elements to find the Fibonacci sequence.
  • It is also used to generate random numbers but with uniform distribution.
  • It is also used to calculate probabilities in statistical experiments.

Conclusion
In this article, we discussed how to write a Pascal Triangle program in the C programming language. We provided a dry run of the program and explained each part of the code in detail. We also provided examples of the program output for different numbers of rows. The Pascal Triangle is an interesting mathematical concept that has many applications in various fields, and writing a program to generate it is a great exercise for learning nested loops and mathematical formulas.

Frequently Asked Questions

Here are some of the frequently asked questions about the pascal triangle program in c.

1. What are nested loops?
Nested loops are loops that are nested inside each other. They are used to perform a set of actions repeatedly for a certain number of times.

2. What is the purpose of the first inner loop in a Pascal Triangle program?
The purpose of the first inner loop is to print the spaces before each row of the triangle to align the numbers correctly.

3. How do you handle the special cases where the coefficient is 1 in a Pascal Triangle program?
You handle the special cases where the coefficient is 1 by using an if statement.

4. What is the purpose of the newline character in a Pascal Triangle program?
The purpose of the newline character is to move to the next line after each row of the triangle is printed.

5. What are some common errors in a Pascal Triangle program?
Some common errors in a Pascal Triangle program include syntax errors, logical errors, and runtime errors.

Leave a Reply

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