C Program to Display Pascal’s Triangle Using Loops

C Program

C Program to Display Pascal’s Triangle Using Loops

Example 


#include<stdio.h>

int main()

{

    int  row,coef=1,space,i,j;

    printf("enter the number");

    scanf("%d",&row);

    for (i=0;i<row;i++)

    {
    for(space=1;space<=row -i;space++)

    printf(" ");

    for(j=0;j<=i;j++)

    {

    if(j==0||i==0)

    coef =1;

    else

    coef=coef * (i-j+1)/j;

printf("%4d",coef);

    }

    printf("\n");

    }

return 0;

}


C Program to Display Pascal’s Triangle Using Loops

Explain Program

Step :1

#include <stdio.h>

  •  standard input/output library for printf() and scanf() function

Step :2

int main()

  • Starting point of the program.

Step :3

Variable Declarations

int row, coef = 1, space, i, j;

  • row: Number of rows to print (user input).
  • coef: Coefficient in Pascal’s Triangle, initialized to 1. It holds the binomial coefficient.
  • space: Used to align the triangle by printing leading spaces.
  • i: Outer loop counter (represents the current row).
  • j: Inner loop counter (represents the position in the row).

Step :4

Input Prompt

printf("enter the number");

scanf("%d", &row);

  •  rows of Pascal's Triangle they want to display

Step :5

Outer Loop: Iterates through rows

for (i = 0; i < row; i++)

  • i  from 0 to row - 1 (0-based index).
  • Each iteration corresponds to one row of Pascal’s Triangle.

Step :6

Printing Leading Spaces

for (space = 1; space <= row - i; space++)

    printf(" ");

  • Aligns the triangle by printing spaces before numbers.
  • As i increases, fewer spaces are printed.

Makes the triangle centered

Step :7

Inner Loop: Calculates and Prints Coefficients

for (j = 0; j <= i; j++)

  • Print  value  the current row (row i has i+1 value).

Step :8

if (j == 0 || i == 0)

    coef = 1;

else

    coef = coef * (i - j + 1) / j;

  • This is an efficient iterative formula to calculate binomial coefficients without using factorials:

Step :9

printf("%4d", coef);

  • %4d ensures that each number takes at least 4 spaces, which helps align the triangle neatly.

Step :10

printf("\n");

  •  starts the next one.
return 0


C Program to Display Pascal’s Triangle Using Loops

 Program Output :- 



Related Post :-


C program number pattern

Comments

Popular posts from this blog

how to add background image in html.

HTML pre tag

How to insert image in html

Html anchor tag

Inline css in html