Loop Assignment 19 — Print Pascal's Triangle Using Nested For Loops
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program: Print Pascal's Triangle Using Nested For Loops — Binomial Coefficient Pattern

📑 On this page:
  • How Pascal's Triangle Works
  • The Three Steps of Printing the Triangle
  • Complete C Program
  • Program Output
  • Step-by-Step Explanation
  • Frequently Asked Questions
📚 In this program, you will learn:
  • How to print Pascal's triangle using nested for loops
  • How to calculate binomial coefficients using C(n, r)
  • How to print leading spaces to shape the triangle
  • How to calculate factorial using a loop
  • How to avoid using arrays for this pattern
  • Why Pascal's triangle is useful in combinations and algebra

How Pascal's Triangle Works

Pascal's triangle is a triangular arrangement of numbers in which each number is the sum of the two numbers directly above it. The first and last number in every row is always 1.

Each number in Pascal's triangle represents a binomial coefficient. The value at row n and position r is calculated using the formula \(C(n, r) = \frac{n!}{r!(n-r)!}\).

To print the triangle, the program uses nested for loops. The outer loop controls the rows, the first inner loop prints spaces for alignment, and the second inner loop calculates and prints the numbers in each row.

💡 In one line: Print spaces for alignment, calculate each value using the binomial coefficient formula, and display every row using nested for loops.

Diagram showing Pascal's triangle printed using nested for loops in C

The Three Steps of Printing the Triangle

Step Loop operation Effect
1. Print spacesfor (space = 1; space <= rows - i; space++)Creates the triangular shape by shifting each row to the right
2. Calculate coefficientsC(n, r) = n! / (r! * (n-r)!)Generates the numbers for the current row
3. Print the rowfor (r = 0; r <= i; r++)Displays all binomial coefficients in the current row

The first few rows of Pascal's triangle are:

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

In row 4, the middle value 6 is obtained by adding the two numbers above it: 3 + 3 = 6. This addition property is the main idea behind Pascal's triangle.

Complete C Program

Program: print Pascal's triangle using nested for loops

#include <stdio.h>

/* Function to calculate factorial */
long factorial(int number) {
    long result = 1;
    int i;

    for (i = 1; i <= number; i++) {
        result = result * i;
    }

    return result;
}

/* Function to calculate binomial coefficient C(n, r) */
long binomial_coefficient(int n, int r) {
    return factorial(n) / (factorial(r) * factorial(n - r));
}

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

    printf("Enter the number of rows: ");
    if (scanf("%d", &rows) != 1 || rows <= 0) {
        printf("Invalid input. Please enter a positive integer.\n");
        return 1;
    }

    for (i = 0; i < rows; i++) {
        /* Print leading spaces */
        for (space = 1; space <= rows - i; space++) {
            printf("  ");
        }

        /* Print binomial coefficients */
        for (j = 0; j <= i; j++) {
            printf("%4ld ", binomial_coefficient(i, j));
        }

        printf("\n");
    }

    return 0;
}
                                    

Program Output

Enter the number of rows: 5

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

A second run, with 7 rows:

Enter the number of rows: 7

                 1 
               1    1 
             1    2    1 
           1    3    3    1 
         1    4    6    4    1 
       1    5   10   10    5    1 
     1    6   15   20   15    6    1 
                                

The program prints the required number of rows. Each row begins and ends with 1, and every middle value is the sum of the two values above it.

Step-by-Step Explanation

Let us understand how the program prints Pascal's triangle for 5 rows.

1. The factorial function

factorial(int number) calculates the factorial of a number using a for loop. For example, factorial(4) returns \(4 \times 3 \times 2 \times 1 = 24\).

2. The binomial coefficient function

binomial_coefficient(n, r) calculates \(C(n, r)\) using the formula \(n! / (r! \times (n-r)!)\). This formula gives the value at row n and position r in Pascal's triangle.

3. Outer loop for rows

The outer loop for (i = 0; i < rows; i++) controls the rows. When i = 0, the program prints the first row. When i = 4, it prints the fifth row.

4. Inner loop for spaces

The first inner loop prints spaces before the numbers. The number of spaces decreases as the row number increases, which creates the triangular shape.

5. Inner loop for numbers

The second inner loop prints values from position 0 to position i. For row 4, it prints five values: 1, 4, 6, 4, and 1.

6. Example calculation for row 4

  • C(4, 0) = 1
  • C(4, 1) = 4
  • C(4, 2) = 6
  • C(4, 3) = 4
  • C(4, 4) = 1

Therefore, row 4 is printed as 1 4 6 4 1.

7. Why nested loops are needed

One loop is needed to move through the rows, another loop is needed to print spaces, and another loop is needed to print the values in each row. This is why the program uses nested for loops.

8. Why the first and last values are 1

In the formula \(C(n, r)\), when r = 0 or r = n, the result is always 1. Therefore, every row of Pascal's triangle starts and ends with 1.

9. Importance of Pascal's triangle

Pascal's triangle is used in algebra, probability, and combinatorics. Its values represent the number of ways to choose r items from n items, also written as nCr.

10. Complexity summary

The time complexity is high because the program calculates factorials repeatedly for every binomial coefficient. For n rows, the factorial-based approach takes approximately O(n3) time in the worst case. Space complexity is O(1) because no array is used to store the triangle.

🎯 Remember this: Pascal's triangle is made of binomial coefficients. Use \(C(n, r) = \frac{n!}{r!(n-r)!}\), print spaces for alignment, and use nested for loops to display each row.

Frequently Asked Questions

1. What is Pascal's triangle?

Pascal's triangle is a triangular arrangement of numbers where each number is the sum of the two numbers directly above it. Every row begins and ends with 1.

2. Why are binomial coefficients used?

Each value in Pascal's triangle is a binomial coefficient. The value at row n and position r is \(C(n, r)\), which represents the number of ways to choose r items from n items.

3. Why are nested for loops required?

Nested loops are required because the program must handle rows, spaces, and values. The outer loop controls rows, while the inner loops print spaces and calculate the numbers for each row.

4. Can Pascal's triangle be printed without factorial?

Yes. A more efficient method uses the relationship \(C(n, r+1) = C(n, r) \times (n-r) / (r+1)\). This avoids calculating factorials repeatedly.

5. Why does each row start and end with 1?

In the binomial coefficient formula, \(C(n, 0)\) and \(C(n, n)\) are always 1. Therefore, the first and last numbers of every row are 1.

6. What is the time complexity of this program?

The factorial-based version has approximately O(n3) time complexity because factorials are recalculated for every coefficient. Space complexity is O(1) because the program does not store the triangle in an array.

💡 Tip: After implementing this program, try printing Pascal's triangle without using the factorial function. Use the previous coefficient to calculate the next coefficient in the same row.

📖 Related Tutorials

  • 18. Convert a Hexadecimal String to Decimal Using a For Loop
  • 20. Print Floyd's Triangle Using Nested For Loops
  • 9. Print the Pattern of a Pyramid Using a For Loop
  • 13. Print the Pattern of a Diamond Using a For Loop
  • All Loop Assignments in C

Previous Topic: -->> 18. Write a program in C to convert a hexadecimal string to decimal using a for loop.   ||   Next Topic: -->> 20. Write a program in C to print Floyd's triangle using nested for loops.


C Language

  • Home
  • Why C Language
  • History of C Language
  • Applications of C Language
  • Introduction To C
    • What is Program?
    • Structure of C Program
    • Working Of C Program
    • CHARACTER SET
    • VARIABLES AND IDENTIFIERS
    • BUILT-IN DATA TYPES
    • OPERATORS AND EXPRESSIONS
    • CONSTANTS AND LITERALS
    • SIMPLE ASSIGNMENT STATEMENT
    • BASIC INPUT/OUTPUT STATEMENT
    • SIMPLE 'C' PROGRAMS
    • Assignments
  • Operators in C Programming
    • Arithmetic Operators
    • Assignment Operators
    • Increment and Decrement Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Other Operators
    • Assignments
  • CONDITIONAL STATEMENTS
    • DECISION MAKING WITHIN A PROGRAM
    • CONDITIONS
    • IF STATEMENT
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • SWITCH CASE
    • Assignments
  • LOOPS STATEMENTS
    • Introduction to Loops
    • GO TO Statement
    • Do while Loop
    • While Loop
    • Nested While Loop
    • Difference Between While and Do while
    • Difference Between Goto and loop
    • while loop assignments
    • C FOR Loop
    • C For loop examples
    • Nested for loop
    • Nested for loop examples
    • Infinite while Loops
    • Infinite for Loops
    • Continue in Loops
    • break in Loops
    • difference while do..while & for
    • Assignments
  • Arrays
    • One Dimensional Array
    • Declaring 1D Arrays
    • Initilization of 1D arrays
    • Accessing element of one 1D Array
    • Read and Display 1D Arrays
    • Two Dimensional Arrays
    • Declare 2D Arrays
    • Read and Display 2D Arrays
    • Assignments/Examples
  • Functions
    • Introduction
    • Need For User-Defined Function
    • Multiple Function Program
    • Modular Programming
    • Elements Of User Defined Function
    • Function Definition
    • Function Declaration
    • Types of functions
    • Nesting of Function
    • Recursion
    • Passing Array To Functions
    • Scope,Visibility and Lifetime of Variables
    • Assignments
  • Structure
    • Introduction
    • Array vs Structure
    • Defining Structure
    • Declaring Structure Variables
    • Type Defined Structure
    • Accessing Structure Members
    • Structure Initilization
    • Copying & Comparing Structure Variables
    • Array of Structure
    • Arrays Within Structure
    • Structures Within Structures
    • Structures and Functions
    • Structure Examples/Assignments
  • Union
    • Define Union
    • Create and use Union
    • Difference Between Structure and Union
    • Union Examples
    • Union FAQ
  • Pointers
    • What Are Pointers In C?
    • How Do We Use Pointers In C?
    • Declaration Of A Pointer
    • The Initialization Of A Pointer
    • Syntax Of Pointer Initialization
    • Use Of Pointers In C
    • The Pointer To An Array
    • The Pointer To A Function
    • The Pointer To A Structure
    • Types Of Pointers
    • The Null Pointer
    • The Void Pointer
    • The Wild Pointer
    • The Near Pointer
    • The Huge Pointer
    • The far Pointer
    • dangling pointer
    • Accessing Pointers- Indirectly And Directly
    • Pros Of Using Pointers In C
    • Cons Of Pointers In C
    • Applications Of Pointers In C
    • The & Address Of Operator In C
    • How To Read The Complex Pointers In C?
    • Practice Problems On Pointers
  • File Processiong
    • File Handling In C
    • Types Of Files In C
    • Operations Done In File Handling
    • File Examples
    • Binary Files
    • count words,lines in a file
    • Copy files
    • Update File
    • count vowels in a file
  • Preprocessor
    • Macro substitution division
    • File Inclusion
    • Conditional Compilation
    • Other directives
    • Examples
  • Dynamic Memory Allocation
    • malloc
    • calloc
    • free
    • realloc
    • Examples
  • Storage Classes
  • Graphics
  • Frequently Asked Interview Questions (FAQ)
    • Introduction To C FAQ
    • Operators FAQ
    • Conditional Statements FAQ
    • Loops FAQ
    • Arrays FAQ
    • Function FAQ
    • Structure FAQ
    • Pointers FAQ
    • Files FAQ
    • Storage classes FAQ
    • Dynamic Memory FAQ
  • Programs/Assignments
    • Introduction To C
    • Operators
    • Conditional Statements
    • Loops
    • Arrays
    • Function
    • Structure
    • Pointers
    • Files
    • Storage classes
    • Dynamic Memory
  • Case Studies
  • Multiple Choice Questions
    • Introduction To C MCQ
    • Operators MCQ
    • Conditional Statements MCQ
    • Loops MCQ
    • Arrays MCQ
    • Function MCQ
    • Structure MCQ
    • Pointers MCQ
    • Files MCQ
    • Storage classes MCQ
    • Dynamic Memory MCQ
    • More MCQ

Get in touch

  • tech2dsm@gmail.com

© Sankalan Data Tech. All rights reserved.