Cover Image for Number Triangle in C
81 views

Number Triangle in C

A number triangle is a pattern where numbers are arranged in a triangular shape. Each row contains a sequence of numbers, often increasing by one in each row. Here’s an example of how to create a number triangle in C:

C
#include <stdio.h>

int main() {
    int rows, i, j, number = 1;

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

    for (i = 1; i <= rows; i++) {
        // Print spaces before the numbers
        for (j = 1; j <= rows - i; j++) {
            printf("  ");
        }

        // Print numbers in the current row
        for (j = 1; j <= i; j++) {
            printf("%2d", number);
            number++;
        }

        // Move to the next line for the next row
        printf("\n");
    }

    return 0;
}

In this program:

  • We prompt the user to enter the number of rows for the triangle.
  • We use nested loops to print the numbers in the triangular pattern.
  • The outer loop (i) iterates through the rows.
  • The first inner loop (j) prints spaces before the numbers to align them in a triangular shape.
  • The second inner loop (j) prints the numbers in the current row.
  • The number variable keeps track of the current number to be printed, and it increases by one in each iteration.

Compile and run the program, and it will generate a number triangle based on the user’s input. The numbers will be displayed in a triangular pattern, with each row having one more number than the previous row.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS