C (programming language)

C program to print hollow right triangle number pattern

Understanding the Problem

  • Goal: Write a C program that prints a hollow right triangle pattern of numbers, with numbers only along the edges and spaces inside.
  • Key Concepts:
    • Loops: for loops for controlled iterations.
    • Conditional statements: if statements for decision-making.
    • Formatting output: printf for printing numbers and spaces.

Step-by-Step Guide

1. Header Inclusion

C

#include <stdio.h>
  • Explanation: Includes the standard input/output library for functions like printf.

2. Main Function

C

int main() {
    // Code statements here
    return 0;
}

3. Variable Declaration

C

int rows;
  • Explanation: Stores the number of rows in the triangle.

4. Get User Input

C

printf("Enter the number of rows: ");
scanf("%d", &rows);

5. Outer Loop for Rows

C

for (int i = 1; i <= rows; i++) {
    // Code for printing each row
}
  • Explanation: Iterates through each row of the triangle.

6. Inner Loop for Columns

C

for (int j = 1; j <= rows; j++) {
    // Code to print numbers or spaces based on conditions
}
  • Explanation: Iterates through each column within a row.

7. Printing Numbers and Spaces

C

for (int j = 1; j <= rows; j++) {
    if (j == 1 || j == i || i == rows) {
        printf("%d ", j);  // Print numbers on edges
    } else {
        printf("  ");      // Print spaces inside
    }
}
printf("\n");  // Move to the next line after each row
  • Explanation:
    • j == 1 || j == i || i == rows: Checks for edge conditions to print numbers.
    • printf("%d ", j): Prints the number and a space.
    • printf(" "): Prints two spaces for the hollow interior.
    • printf("\n"): Moves to the next line after each row.

8. Complete Code

C

#include <stdio.h>

int main() {
    int rows;

    printf("Enter the number of rows: ");
    scanf("%d", &rows);

    for (int i = 1; i <= rows; i++) {
        for (int j = 1; j <= rows; j++) {
            if (j == 1 || j == i || i == rows) {
                printf("%d ", j);
            } else {
                printf("  ");
            }
        }
        printf("\n");
    }

    return 0;
}

9. Executing the Program

  1. Save the code as a .c file (e.g., hollow_triangle.c).
  2. Compile using a C compiler (e.g., gcc hollow_triangle.c -o hollow_triangle).
  3. Run the executable (e.g., ./hollow_triangle).

Example Output

Enter the number of rows: 5

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

CodeForHunger

Learn coding the easy way. Find programming guides, examples and solutions with explanations.

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button