Placement Prep

Palindrome Pyramid Pattern Using Numbers: C, Python, Java

Step-by-step code and loop trace for the palindrome number pyramid in C, C++, Python, and Java, with centered and half-pyramid variants.

By FACE Prep Team 8 min read
pattern-programs number-patterns python c-programming java coding-interview placement-prep

The palindrome number pyramid prints each row as its own palindrome: row i counts up from 1 to i, then mirrors back from i-1 to 1 using two inner loops.

For n=5, the centered output looks like this:

        1
      1 2 1
    1 2 3 2 1
  1 2 3 4 3 2 1
1 2 3 4 5 4 3 2 1

Read any row forwards or backwards and you get the same sequence. That palindromic property follows directly from the ascending-then-descending loop structure that builds each row.

Understanding the Palindrome Number Pyramid

Two standard variants appear in placement coding tests and programming practice problems.

The half pyramid is left-aligned. There are no leading spaces, and the output begins at the far left of the screen:

1
1 2 1
1 2 3 2 1
1 2 3 4 3 2 1
1 2 3 4 5 4 3 2 1

The centered pyramid adds leading spaces before each row, so every row is centered above the widest row at the bottom:

        1
      1 2 1
    1 2 3 2 1
  1 2 3 4 3 2 1
1 2 3 4 5 4 3 2 1

Both variants use the same row-building logic. The difference is that the centered version runs a third loop to print leading spaces before each row’s numbers.

Row structure for one iteration

For row i in an n-row pyramid, the logic runs in three phases:

  • Phase 1 (centered only): print 2*(n-i) space characters as left padding.
  • Phase 2 — ascending: j runs from 1 to i inclusive; print j followed by a space.
  • Phase 3 — descending: j runs from i-1 down to 1 inclusive; print j followed by a space.

Row 1 is a special case worth noting. Phase 3’s starting value is i-1 = 0, which is already below the stopping condition of 1. The descending loop never executes. Row 1 prints only “1” regardless of n.

The “palindrome” property holds for every row. For row i, the full sequence is 1 2 3 ... i ... 3 2 1. Any sequence of the form a b c ... x ... c b a is a palindrome by definition. The loop structure guarantees symmetry: Phase 2 builds the left half up to the peak, Phase 3 builds the mirror of that same half on the way down.

How Each Row Is Built: The Loop Formula

Deriving the leading-space count

For the centered pyramid with n rows, the widest row is row n. That row contains 2n-1 numbers (counting up to n and back down, with n appearing once). Each number is printed followed by a space, giving 2*(2n-1) output characters. Ignoring the trailing space, the visible width of row n is 4n-3 characters.

Row i follows the same logic; its visible width is 4i-3 characters. The extra width at the bottom compared to row i is (4n - 3) - (4i - 3) = 4*(n - i). To center row i under row n, that gap splits evenly: leading spaces = 2*(n-i).

This formula is derivable rather than memorizable. If you forget it during an exam, start from first principles: the bottom row sets the width, every row above it is narrower by 2 on each side.

Loop trace for n=4

Row (i)Leading spaces 2*(4-i)Ascending j: 1 to iDescending j: i-1 to 1Output line
12*(4-1) = 61(loop empty) 1
22*(4-2) = 41, 21 1 2 1
32*(4-3) = 21, 2, 32, 1 1 2 3 2 1
42*(4-4) = 01, 2, 3, 43, 2, 11 2 3 4 3 2 1

Visual output for n=4 (trailing spaces are invisible in a terminal):

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

Row 2 check: 4 leading spaces, ascending prints “1 2 ” (j from 1 to 2), descending prints “1 ” (j = 1 down to 1). Combined: ” 1 2 1 ”, as expected.

Loop trace for n=5

Row (i)Leading spaces 2*(5-i)Output line
12*(5-1) = 8 1
22*(5-2) = 6 1 2 1
32*(5-3) = 4 1 2 3 2 1
42*(5-4) = 2 1 2 3 4 3 2 1
52*(5-5) = 01 2 3 4 5 4 3 2 1

Visual output for n=5:

        1
      1 2 1
    1 2 3 2 1
  1 2 3 4 3 2 1
1 2 3 4 5 4 3 2 1

Row 5 check: zero leading spaces, ascending j from 1 to 5 prints “1 2 3 4 5 ”, descending j from 4 down to 1 prints “4 3 2 1 ”. Combined: “1 2 3 4 5 4 3 2 1 ”, as expected.

Edge case: n=1

One row only. i=1, leading spaces = 2*(1-1) = 0, ascending loop prints “1 ”, descending loop is empty. Output is a single “1”. The formula holds for this edge case without a special branch.

Programs in C, C++, Python, and Java

The programs below print the centered pyramid. The outer loop runs n times; for each row, three inner constructs handle spaces, ascending numbers, and descending numbers in that order.

C

#include <stdio.h>

int main() {
    int n, i, j;
    printf("Enter number of rows: ");
    scanf("%d", &n);
    for (i = 1; i <= n; i++) {
        for (j = 1; j <= 2 * (n - i); j++)
            printf(" ");
        for (j = 1; j <= i; j++)
            printf("%d ", j);
        for (j = i - 1; j >= 1; j--)
            printf("%d ", j);
        printf("\n");
    }
    return 0;
}

C++

#include <iostream>
using namespace std;

int main() {
    int n;
    cin >> n;
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= 2 * (n - i); j++)
            cout << " ";
        for (int j = 1; j <= i; j++)
            cout << j << " ";
        for (int j = i - 1; j >= 1; j--)
            cout << j << " ";
        cout << "\n";
    }
    return 0;
}

Python 3

n = int(input("Enter number of rows: "))
for i in range(1, n + 1):
    print(' ' * 2 * (n - i), end='')
    for j in range(1, i + 1):
        print(j, end=' ')
    for j in range(i - 1, 0, -1):
        print(j, end=' ')
    print()

The descending loop uses range(i - 1, 0, -1). When i = 1, that becomes range(0, 0, -1), which is an empty sequence. The Python range() function returns empty whenever the start already satisfies the stop condition for the given step direction. Row 1 therefore prints only “1” without needing a separate conditional.

Java

import java.util.Scanner;

public class PalindromePyramid {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= 2 * (n - i); j++)
                System.out.print(" ");
            for (int j = 1; j <= i; j++)
                System.out.print(j + " ");
            for (int j = i - 1; j >= 1; j--)
                System.out.print(j + " ");
            System.out.println();
        }
    }
}

All four implementations produce identical output. The three-loop structure is the same in every language; only the syntax changes. For n=5, every version prints the 5-row centered pyramid verified in the trace section above.

The Half Pyramid Variant

The half pyramid drops Phase 1 entirely. No leading spaces are printed; each row starts at the left margin. The row-building logic stays the same: ascending from 1 to i, descending from i-1 back to 1.

Python implementation:

n = int(input("Enter number of rows: "))
for i in range(1, n + 1):
    for j in range(1, i + 1):
        print(j, end=' ')
    for j in range(i - 1, 0, -1):
        print(j, end=' ')
    print()

Output for n=5:

1 
1 2 1 
1 2 3 2 1 
1 2 3 4 3 2 1 
1 2 3 4 5 4 3 2 1 

The half pyramid is the simpler form to code under time pressure because there are no alignment calculations. Converting the half pyramid to the centered form requires only adding the space loop before the ascending numbers; that is exactly the derivation in the previous section. If you can code the half pyramid cleanly, the centered variant follows from the 2*(n-i) formula.

A useful self-check when coding either variant: trace row 1 and row n mentally before submitting. Row 1 should print only “1”. Row n should print “1 2 … n … 2 1” with zero leading spaces in either form. If both edge cases pass the trace, the middle rows almost always follow.

For more variations including right-aligned and inverted pyramids, GeeksforGeeks covers the full family of pyramid pattern programs in Python.

Pattern Programs in Placement Coding Tests

Pattern printing problems appear in the programming sections of campus recruitment assessments for Indian engineering students, particularly at Tier-2 and Tier-3 colleges where the test batteries typically include one or two pattern questions alongside standard data-structures problems.

The palindrome pyramid is a common harder variant because it demands a mirrored descending loop on top of the basic ascending one. A student who has only drilled right-aligned number triangles will stall here. The question tests three things: awareness that a row-reset is needed (unlike Floyd’s triangle), correct loop bounds for the descending leg, and the space formula for the centered form.

Off-by-one errors are the most frequent failure point. The ascending loop condition j <= i is straightforward; the descending loop starting at j = i-1 (not j = i) is where candidates lose a mark. The edge case where i = 1 causes the descending loop to be empty is worth tracing explicitly before submitting.

For students preparing for IT jobs for freshers, pattern programs fall in the programming and problem-solving section. The palindrome pyramid and related patterns are achievable in under ten minutes once the loop structure is clear, but that clarity requires having traced through the loops once, not just having read the output.

The coding section of the Texas Instruments interview process tests similar loop-control skills, particularly the ability to reason about two counters operating over the same bounded range. The indexed-loop thinking that makes the palindrome pyramid solvable transfers directly to that category of problem.

The same nested-loop reasoning that builds this pyramid: tracking two counters, iterating over a bounded sequence, mirroring output, is the structural intuition behind sequence-processing in LLM applications. TinkerLLM is where to apply that loop-indexed thinking to building LLM-powered tools rather than printing pyramids; the entry point is ₹299.

Primary sources

Frequently asked questions

What is a palindrome pyramid pattern in programming?

A palindrome pyramid is a number pattern where each row forms a palindromic sequence. Row i prints numbers 1 to i then i-1 back to 1, and the rows are centered to form a triangle.

How many loops are needed for the palindrome number pyramid?

Three loops per row: a leading-space loop for centering, an ascending loop counting 1 to i, and a descending loop counting i-1 back to 1. An outer loop runs n times for the row count.

What is the leading space formula for the centered palindrome pyramid?

Leading spaces = 2*(n-i), where n is total rows and i is the current row (1-indexed). For n=4 row 1: 6 spaces; row 2: 4 spaces; row 3: 2 spaces; row 4: 0 spaces.

Does the palindrome pyramid appear in campus placement coding tests?

Pattern programs appear in the coding rounds of campus assessments. The palindrome pyramid tests nested-loop control and off-by-one awareness, both standard skills for IT fresher coding screens.

How is the palindrome pyramid different from Floyd's triangle?

Floyd's triangle increments a running counter continuously across all rows; the palindrome pyramid resets to 1 at the start of each row and mirrors the ascending count back down.

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