Placement Prep

Program to Print Pascal's Triangle in C, Python, and Java

Step-by-step guide to printing Pascal's triangle in C, Python, and Java, with row construction logic, O(n²) complexity, and placement interview context.

By FACE Prep Team 6 min read
pascal-triangle coding-questions dynamic-programming placement-prep c-programming python-programming algorithms

Pascal’s triangle is a triangular array of binomial coefficients that shows up in placement coding rounds at TCS, Infosys, and Cognizant more often than its simple construction rule would suggest.

It’s a favourite placement problem because it tests three skills at once: nested loop control, index arithmetic, and translating a clean mathematical rule into working code. No library import required.

What Pascal’s Triangle Is

Each row holds the binomial coefficients for that row index. Row 0 has one element: 1. Row r has r+1 elements, and the value at row r, column c equals C(r,c), the number of ways to choose c items from r.

The construction rule is two lines:

  • Every edge element (first and last in each row) is 1.
  • Every interior element equals the sum of the two elements directly above it.

The first seven rows, verified from the addition rule:

RowValues
01
11   1
21   2   1
31   3   3   1
41   4   6   4   1
51   5   10   10   5   1
61   6   15   20   15   6   1

Spot-check row 4: edges are 1; interior positions give 1+3=4, 3+3=6, 3+1=4. The row reads 1, 4, 6, 4, 1. Correct.

There is also a direct formula: the value at row r, column c is C(r,c) = r factorial divided by (c factorial times (r minus c) factorial). For row 5, column 2: C(5,2) = 5! / (2! * 3!) = 120 / (2 * 6) = 10. This matches the table. The formula is more useful for computing a specific value than for printing the entire triangle row by row, which is what placement questions ask.

Building Each Row — the Addition Rule

A useful mental model: pad every row with a 0 on each side, then sum adjacent pairs to get the next row.

Working example for row 2 producing row 3:

  • Row 2 padded: 0, 1, 2, 1, 0
  • Adjacent sums: (0+1), (1+2), (2+1), (1+0) — which gives 1, 3, 3, 1 (row 3). ✓

This zero-padding model is why most 2D-array implementations set the first and last element of each row to 1 before running the inner loop. The boundary condition is simply the padded 0 adding to the edge 1.

The same model extends naturally to row 6. Pad row 5 (1, 5, 10, 10, 5, 1) with zeros: 0, 1, 5, 10, 10, 5, 1, 0. Adjacent sums: (0+1), (1+5), (5+10), (10+10), (10+5), (5+1), (1+0) = 1, 6, 15, 20, 15, 6, 1. That is row 6, which matches the table.

Programs to Print Pascal’s Triangle

Three standard implementations are shown below. All produce the same output for the same input.

C — nCr incremental method

This approach uses the recurrence C(r,c) = C(r, c-1) * (r - c + 1) / c to update the current coefficient without storing a separate row array.

#include <stdio.h>

int main() {
    int n, i, j, coeff;
    printf("Enter number of rows: ");
    scanf("%d", &n);

    for (i = 0; i < n; i++) {
        coeff = 1;
        for (j = 0; j <= i; j++) {
            printf("%d ", coeff);
            coeff = coeff * (i - j) / (j + 1);
        }
        printf("\n");
    }
    return 0;
}

Auxiliary space: O(1). The triangle is printed one value at a time. The integer division in coeff * (i - j) / (j + 1) works correctly because the numerator is always divisible by the denominator at each step. This divisibility is a guaranteed property of binomial coefficients.

Python — 2D list

def pascal_triangle(n):
    triangle = []
    for i in range(n):
        row = [1] * (i + 1)
        for j in range(1, i):
            row[j] = triangle[i - 1][j - 1] + triangle[i - 1][j]
        triangle.append(row)
    return triangle

n = int(input("Enter number of rows: "))
for row in pascal_triangle(n):
    print(" ".join(map(str, row)))

Space: O(n²). The full triangle is stored as a list of lists. The inner loop skips index 0 and index i because those positions are already 1 from the [1] * (i + 1) initialisation.

Java — 2D array

import java.util.Scanner;

public class PascalTriangle {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int[][] t = new int[n][];

        for (int i = 0; i < n; i++) {
            t[i] = new int[i + 1];
            t[i][0] = 1;
            t[i][i] = 1;
            for (int j = 1; j < i; j++) {
                t[i][j] = t[i - 1][j - 1] + t[i - 1][j];
            }
        }

        for (int[] row : t) {
            for (int val : row) {
                System.out.print(val + " ");
            }
            System.out.println();
        }
    }
}

TCS NQT and most Cognizant hiring platforms accept C, C++, Java, and Python. Pick the language you’re most fluent in for pattern-printing problems.

Formatting: centering the triangle

The programs above print each row left-aligned. Placement questions sometimes ask for centered output. The standard approach is to print leading spaces before each row. For n total rows, row i needs (n - i - 1) spaces prepended.

In Python, add one line before the row print:

print(" " * (n - i - 1) + " ".join(map(str, row)))

This produces the classic triangular shape with the apex centred above the base.

For a broader set of pattern-printing and array problems, the C coding questions in placement rounds article covers the question types that appear alongside Pascal’s triangle in the same round.

Time and Space Complexity

ApproachTimeAuxiliary space
2D array (Python / Java)O(n²)O(n²)
nCr incremental (C above)O(n²)O(1)
Two-row rolling bufferO(n²)O(n)

The O(n²) lower bound is unavoidable. A triangle with n rows has n(n+1)/2 values, which is O(n²). The difference between implementations is purely in auxiliary space. For placement interviews, knowing the O(1)-space variant exists is a useful differentiator. Most candidates stop at the 2D-array solution; an interviewer who asks “how would you reduce memory usage?” is testing whether you know the nCr recurrence.

The two-row rolling buffer sits between the two extremes: keep only the previous row in memory, compute the current row from it, then overwrite. O(n) space and easier to reason about than the incremental formula.

The GeeksforGeeks Pascal’s Triangle article covers additional variants, including the O(n) per-row formula method, for further reading.

Where Pascal’s Triangle Appears in Placement Tests

Pattern-printing questions (pyramids, diamonds, Floyd’s triangle, Pascal’s triangle) appear in the first coding section of most volume-hire placement rounds. Pascal’s triangle is the hardest of the standard pattern group for three reasons:

  • Edge-case handling: the first and last element of each row must always equal 1. A loop that does not set boundary values explicitly will print 0 at the edges.
  • Index correctness: the nested loop bounds must be right, or the triangle prints the wrong shape. Off-by-one errors are the most common failure.
  • Extension questions: interviewers can follow up with “now compute nCr without a 2D array,” a test of whether you understand the incremental formula above.

Index-arithmetic number pattern questions share the same loop-structure skills and are worth drilling in the same session.

The combinatorics connection runs deeper than the code. Row r of Pascal’s triangle holds the coefficients of the binomial expansion (a + b)^r. If a placement aptitude round asks how many ways to choose 2 items from 5, the answer (10) sits at row 5, column 2. That is C(5,2) from the triangle. Recognising the link between a printed row and a combinatorics formula is the kind of depth that coding-type aptitude questions in competitive rounds sometimes reward.

Pascal’s triangle is also connected to several well-known number sequences. The first diagonal (all 1s) gives natural numbers offset by one. The second diagonal gives the natural numbers 1, 2, 3, 4… Row sums double: row 0 sums to 1, row 1 to 2, row 2 to 4, row 3 to 8, and so on. Each row sum equals 2 raised to the row index. These patterns come up in interview follow-up questions and are worth knowing as quick mental checks that your output is correct.

Pascal’s triangle is built from one rule applied n² times: each cell inherits from its two parents. That pattern (simple local rules composing into rich global structure) is also how transformer layers build context from tokens. If you want hands-on experience probing how large language models handle recursive and combinatorial patterns, TinkerLLM at ₹299 is a low-cost starting point where you can run those experiments without setting up a research environment.

Primary sources

Frequently asked questions

What is Pascal's triangle?

Pascal's triangle is a triangular array of binomial coefficients. Row r, column c holds C(r,c), the number of ways to choose c items from r. The edges are always 1, and every interior cell is the sum of the two cells directly above it.

How does each row of Pascal's triangle get calculated?

Each new row is produced by padding the previous row with a 0 on each side, then summing adjacent pairs. Row edges are always 1; interior values are the sum of the two neighbours above.

What is the time complexity of printing Pascal's triangle?

O(n²) for n rows, since you compute n*(n+1)/2 values in total. Space is O(n²) if you store the full triangle, or O(1) extra if you use the nCr incremental formula and only print each row.

How do you print Pascal's triangle in Python?

Build a 2D list where each row starts as all-1s, then fill interior cells with triangle[i-1][j-1] + triangle[i-1][j]. Print each row with a space-joined string using map(str, row).

Does Pascal's triangle appear in TCS NQT or placement coding rounds?

Pattern-printing questions including Pascal's triangle appear regularly in placement coding rounds. The question tests nested loop control, index arithmetic, and the ability to express a mathematical rule as code, all in one problem.

What is the difference between Floyd's triangle and Pascal's triangle?

Floyd's triangle fills rows with consecutive integers starting from 1, with no mathematical relationship between adjacent cells. Pascal's triangle fills rows with binomial coefficients where each cell equals the sum of its two parents.

Build AI projects

A self-paced playground for building with LLMs.

TinkerLLM is FACE Prep's sister property. A guided environment for shipping real LLM applications, the kind of project that earns a paragraph on your resume, not a line.

Try TinkerLLM (₹299 launch)
Free AI Roadmap PDF