Google News
logo
C Program to print Number Triangle
Like alphabet triangle, we can write the c program to print the number triangle. In the following example of C program to print a number triangle :
Program :
#include <stdio.h>

int main() {
    int rows;

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

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

    return 0;
}
Output :
Enter the number of rows: 6
1 
1 2 
1 2 3 
1 2 3 4 
1 2 3 4 5 
1 2 3 4 5 6 
Explanation :

* We start by declaring a variable rows to store the number of rows in the triangle.

* We ask the user to enter the number of rows using printf and scanf.

* We use two nested for loops to print the triangle. The outer loop controls the number of rows in the triangle, and the inner loop controls the number of numbers to be printed in each row.

* Inside the inner loop, we print the current number using printf and then increment current to print the next number in the next iteration of the loop.

* After the inner loop, we print a newline character using printf to move to the next row of the triangle.

* After the outer loop, we return 0 to indicate successful execution of the program.

Note : This program assumes that the input rows variable is a positive integer. If the input is negative or zero, the program may produce unexpected results.