Skip to main content

Programming

Pascal's Triangle in C++ and Java

·

Solving Pascal's Triangle in C++ and Java

Pascal's Triangle is one of the first non-trivial algorithms most CS students encounter. The output looks like a number pyramid: each row has one more element than the row before, the edges are always 1, and every interior value is the sum of the two elements directly above it. This post walks through a complete implementation in both C++ and Java, tackling the two distinct challenges separately: printing the pyramid shape, then computing the correct values.

The sample output for a 5-row triangle looks like this:

Pascal's Triangle sample output showing 5 rows of numbers arranged in pyramid form

There are 2 challenges to solve. First: print numbers in a full pyramid shape with correct spacing. Second: compute the value for each position using the combinatorics formula. Each challenge builds on the previous step.

For Java, install the latest JDK from https://www.oracle.com/java/technologies/downloads/.

For C++, DevC++ or Visual Studio both work. Download DevC++ from https://sourceforge.net/projects/orwelldevcpp/.

Challenge 1: Print the Pyramid Shape

Step 1: Project setup

Declare the required libraries and entry point. This step produces an empty program that compiles and runs without errors.

C++ (save as *.cpp):

#include <iostream>

using namespace std;

int main()
{

}

Java (save as Main.java, then compile with javac Main.java and run with java Main):

public class Main
{
    public static void main(String[] args) {
    }
}

Output: empty screen, no compilation errors.

Step 2: Outer loop for row count

Add a main for loop that iterates N times, where N is the height of the triangle. Start with N = 5.

C++

#include <iostream>

using namespace std;

int main()
{
    int N = 5;

    for(int i = 0; i < N; i++)
    {
    }
}

Java

public class Main
{
    public static void main(String[] args) {

        int N = 5;

        for(int i = 0; i < N; i++)
        {
        }
    }
}

Step 3: Inner loop for leading spaces

Add an inner for loop to print the leading tabs before each row. The loop runs N - i times so the tab count decreases by one with each row, pulling the numbers toward the center.

C++

#include <iostream>

using namespace std;

int main()
{
    int N = 5;

    for(int i = 0; i < N; i++)
    {
        for(int j = 0; j < N - i; j++)
        {
            cout << "\t";
        }
    }
}

The Java equivalent uses System.out.print() instead of cout:

Java

public class Main
{
    public static void main(String[] args) {

        int N = 5;

        for(int i = 0; i < N; i++)
        {
            for(int j = 0; j < N - i; j++)
            {
                System.out.print("\t");
            }
        }
    }
}

Step 4: Confirm spacing with a placeholder character

Print X after the leading tabs to verify the indentation is correct before dealing with real values.

C++

#include <iostream>

using namespace std;

int main()
{
    int N = 5;

    for(int i = 0; i < N; i++)
    {
        for(int j = 0; j < N - i; j++)
        {
            cout << "\t";
        }

        cout << "X";

        cout << endl;
    }
}

Java

public class Main
{
    public static void main(String[] args) {

        int N = 5;

        for(int i = 0; i < N; i++)
        {
            for(int j = 0; j < N - i; j++)
            {
                System.out.print("\t");
            }

            System.out.print("X");
            System.out.println();
        }
    }
}

Console output showing a right-aligned column of X characters confirming pyramid indentation

Step 5: Duplicate the character across each row

Print i + 1 copies of X per row (the loop counter starts at 0, so add 1 to get the correct count). Two tab characters separate adjacent placeholders so the columns align with the spacing in the previous row.

C++

#include <iostream>

using namespace std;

int main()
{
    int N = 5;

    for(int i = 0; i < N; i++)
    {
        for(int j = 0; j < N - i; j++)
        {
            cout << "\t";
        }

        for(int j = 0; j < (i + 1); j++)
        {
            cout << "X" << "\t\t";
        }

        cout << endl << endl;
    }
}

Java

public class Main
{
    public static void main(String[] args) {

        int N = 5;

        for(int i = 0; i < N; i++)
        {
            for(int j = 0; j < N - i; j++)
            {
                System.out.print("\t");
            }

            for(int j = 0; j < (i + 1); j++)
            {
                System.out.print("X");
                System.out.print("\t\t");
            }

            System.out.println();
            System.out.println();
        }
    }
}

Two tab characters per element keep the adjacent positions of the next row between the current positions, not directly below them. Two newlines improve the visual pyramid shape.

Console output showing a correctly spaced X pyramid with 5 rows and increasing width

The pyramid shape is now correct. Challenge 1 is done.

Challenge 2: Compute the Triangle Values

Step 1: Replace the placeholder with an integer variable

Declare an integer value initialized to 1 and print it instead of X. Every position prints 1 for now.

C++

#include <iostream>

using namespace std;

int main()
{
    int N = 5;

    for(int i = 0; i < N; i++)
    {
        for(int j = 0; j < N - i; j++)
        {
            cout << "\t";
        }

        int value = 1;

        for(int j = 0; j < (i + 1); j++)
        {
            cout << value << "\t\t";
        }

        cout << endl << endl;
    }
}

Java

public class Main
{
    public static void main(String[] args) {

        int N = 5;

        for(int i = 0; i < N; i++)
        {
            for(int j = 0; j < N - i; j++)
            {
                System.out.print("\t");
            }

            int value = 1;

            for(int j = 0; j < (i + 1); j++)
            {
                System.out.print(value);
                System.out.print("\t\t");
            }

            System.out.println();
            System.out.println();
        }
    }
}

Step 2: Add the factorial helper using combinations

Each value in Pascal's Triangle equals nCr = n! / (r! * (n - r)!), where n is the row index and r is the column index. Both permutation and combination formulas depend on factorial.

Permutation: nPr = n! / (n - r)!

Combination: nCr = n! / (r! * (n - r)!)

The factorial function calls itself recursively, reducing the argument by 1 on each call until it reaches 1.

C++

#include <iostream>

using namespace std;

int factorial(int n)
{
    if(n <= 1)
        return 1;

    return n * factorial(n - 1);
}

Java

public class Main
{
    public static int factorial(int n) {
        if(n <= 1)
            return 1;

        return n * factorial(n - 1);
    }
}

Step 3: Apply the combination formula to each position

Use factorial(i) / (factorial(j) * factorial(i - j)) inside the inner loop, where i is the row and j is the column. This replaces the constant 1 with the correct Pascal's Triangle value.

C++ (complete program):

#include <iostream>

using namespace std;

int factorial(int n)
{
    if(n <= 1)
        return 1;

    return n * factorial(n - 1);
}

int main()
{
    int N = 5;

    for(int i = 0; i < N; i++)
    {
        for(int j = 0; j < N - i; j++)
        {
            cout << "\t";
        }

        int value = 1;

        for(int j = 0; j < (i + 1); j++)
        {
            value = factorial(i) / (factorial(j) * factorial(i - j));
            cout << value << "\t\t";
        }

        cout << endl << endl;
    }
}

Java (complete program):

public class Main
{
    public static int factorial(int n) {
        if(n <= 1)
            return 1;

        return n * factorial(n - 1);
    }

    public static void main(String[] args) {

        int N = 5;

        for(int i = 0; i < N; i++)
        {
            for(int j = 0; j < N - i; j++)
            {
                System.out.print("\t");
            }

            int value = 1;

            for(int j = 0; j < (i + 1); j++)
            {
                value = factorial(i) / (factorial(j) * factorial(i - j));
                System.out.print(value);
                System.out.print("\t\t");
            }

            System.out.println();
            System.out.println();
        }
    }
}

The output for N = 5:

Final Pascal's Triangle output showing correct numeric values in a 5-row pyramid

The value N is hard-coded to 5 here. Change it to any positive integer or read it from user input to get a different height.

Output for N = 8:

Pascal's Triangle output with N=8 showing 8 rows of correct combinatorial values

Time Complexity

The time complexity is O(N^2). The outer loop runs N times. The inner loop that computes and prints values runs at most N times per outer iteration. The factorial function runs in O(N) per call, but since it is called a constant number of times per inner loop iteration, the dominant term remains O(N^2) for typical values of N used in this pattern.

For related algorithm implementations, see Sorting Algorithms in Java: Step-by-Step and Recursion in Java.

If you need working code submitted for a C++ programming assignment or a Java assignment, the team at GeeksProgramming handles both languages and delivers tested, commented code. Pricing starts at $29 with 50% upfront and 50% after you verify it runs.

Share: X / Twitter LinkedIn

Related articles

  • Case Study

    Autograder Fixed in Under 24 Hours: 100/100

    How our networking expert diagnosed a broken distance vector routing submission, fixed the output formatting bug, and delivered a 100/100 autograder score before the deadline.

    Sep 2, 2025

  • Programming

    Can You Get Caught Using Someone Else's Code?

    Yes, you can get caught. MOSS, JPlag, and Codequiry detect copied code even after renaming variables or restructuring. Here is what actually happens if you are.

    Jul 17, 2025

  • Programming

    30+ Websites Every Programming Student Needs

    The best forums, coding platforms, IDEs, debugging tools, and algorithm resources for programming students in 2026, organized by what each one actually does.

    Apr 6, 2025

← All articles

Stuck on a programming assignment?

Get expert help in Java, C++, Python, JavaScript, SQL, and more. We deliver working code with a clear walkthrough so you can understand and defend it.