# 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. 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; }``

Output 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.

Explanation • 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

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

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