C program to Print Pascals Triangle

One of the most interesting Number Patterns is Pascal’s Triangle. To build the triangle, start with «1» at the top, then continue placing numbers below it in a triangular pattern. Each number is the numbers directly above it added together.

Pascals Triangle in C

Ex: 2+1=3 stored below

#include <stdio.h> int main() {   int rows, val=1, i, j;   printf("Enter number of rows: ");   scanf("\%d",&rows);   for(i=0; i<rows; i++)   {       for(j=1; j<=rows-i;j++)           printf("  "); //for appearance of a triangle 2 spaces        for(j=0; j <= i; j++)       {           if (i==0 || j==0) //start and end of a row will print 1               val = 1;           else               val = val*(i-j+1)/j;                          printf("   \%d", val); //print the triangle with 3 spaces       }       printf(""); //new row   } return 0; }


Pascals triangle in c

Variable ‘rows’ keeps count of how many rows we have to display and Variable ‘val’ consists of value of each digit in the Pascal triangle.


Pascals Triangle in C

  • We use nested for loop with two counter variable, ‘i’ and ‘j’. The 2 nested loops inside the parent loop ‘i’ use the same variable ‘j’ as the second loop is initializing its value to ‘1’ so we need not waste extra memory.
  • for(i=0; i<rows; i++) is for the row
  • for(j=0; j <= i; j++) is for the columns
  • When ‘j=0’ or ‘i=0’ we assign ‘val=1’, as you can observe from the above figure
  • The logic for the values is “ val=val*(i-j+1)/j ” which we have condensed the factorial logic to take advantage of the memory function of Computers
  • Before the end of parent loop we printf(“”) for printing from the next row

Thank you for reading.

Tweet your queries and feedback to @PsychoCodes or leave a message on our Facebook page. You can also comment your questions below.

Also, don’t forget to subscribe to our Newsletter.

If you like this article, then please share it and help us grow.

C program to generate all combinations of N-Bit Binary String
10 July 2018

Data Autosave System using PHP, MySQL and AJAX
06 July 2018

Macros in C with examples C Tutorials
30 January 2018

Armstrong Number program in C and C++
29 January 2018

Creating a Fixed Header Navigation Bar with on scroll effect
28 January 2018

C program to find Modular Multiplicative Inverse of two Relatively Prime Numbers
25 January 2018

Понравилась статья? Поделиться с друзьями:
Добавить комментарий