C program to print pascal triangle

Write a C program to print pascal triangle up to n rows using for loop.
Pascal triangle

Required knowledge:

Basic C programming, For loop, Functions

Pascal Triangle

Pascal triangle is a triangular number pattern named after famous mathematician Blaise Pascal.

For example Pascal triangle with 5 rows.
    1
   1 1
  1 2 1
 1 3 3 1
1 4 6 4 1

Logic:

Simple formula for getting any term of the Pascal triangle.

Where n is row number and k is term of that row.
Read more interesting facts about Pascal triangle.

Program:

/**
 * C program to print Pascal triangle up to n rows
 */

#include <stdio.h>

long fact(int n);

int main()
{
    int n, k, num, i;
    long term;

    printf("Enter number of rows : ");
    scanf("%d", &num);

    for(n=0; n<=num; n++)
    {
        //Prints 2 spaces
        for(i=n; i<=num; i++)
            printf("%2c", ' ');

        for(k=0; k<=n; k++)
        {
            term = fact(n)/( fact(k) * fact(n-k));
            printf("%4ld", term);
        }

        printf("\n");
    }

    return 0;
}

//Function to calculate factorial
long fact(int n)
{
    long factorial = 1;
    while(n>=1)
    {
        factorial *= n;
        n--;
    }

    return factorial;
} 
Output:
Pascal triangle in C

Happy coding ;)


Any doubt or suggestion write here. I will try my best to help. Before posting your code you must escape it to view. To format your source code and use format highlighting, post your source code inside
< code >< pre > -- Your source code -- < /pre >< /code > (Remove spaces from pre and code tags).

2 comments:

  1. What, exactly, is this bit of code doing?

    //Prints spaces
    for(i=n; i<=num; i++)
    printf("%*c", 2,' ',' ');

    ReplyDelete
    Replies
    1. Hello Student, the line actually prints two blank spaces. I have made the code little easy to be understood.

      You can also replace the line with
      printf("  ");
      OR
      printf(" %c", ' ');
      OR
      printf("%2c", ' ');

      Delete