Introduction
A half pyramid pattern with numbers is a simple triangular arrangement where the numbers increase in each row. This exercise helps in understanding the use of nested loops and controlling output using numbers in a half-pyramid shape.
Problem Statement
Create a C program that:
- Accepts the number of rows for the pyramid.
- Prints a half-pyramid pattern with numbers.
Example:
- Input:
rows = 5
- Output:
1 1 2 1 2 3 1 2 3 4 1 2 3 4 5
Solution Steps
- Input the Number of Rows: The user defines the number of rows for the half pyramid.
- Use Nested Loops: The outer loop handles the rows, and the inner loop handles printing the numbers.
- Display the Half-Pyramid Pattern: Print numbers in increasing order for each row.
C Program
#include <stdio.h>
int main() {
int i, j, rows;
// Step 1: Accept the number of rows for the pyramid
printf("Enter the number of rows: ");
scanf("%d", &rows);
// Step 2: Outer loop for the rows
for (i = 1; i <= rows; i++) {
// Step 3: Inner loop to print numbers
for (j = 1; j <= i; j++) {
printf("%d ", j);
}
// Move to the next line after each row
printf("\n");
}
return 0;
}
Explanation
Step 1: Input Number of Rows
- The program begins by asking the user to input the number of rows for the half pyramid.
Step 2: Outer Loop for Rows
- The outer loop controls how many rows are printed. It runs from
1
torows
.
Step 3: Inner Loop for Numbers
- The inner loop prints the numbers in increasing order, starting from
1
and going up to the current row number (i
).
Output Example
For rows = 5
, the output will be:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
For rows = 4
, the output will be:
1
1 2
1 2 3
1 2 3 4
Conclusion
This C program prints a half pyramid pattern using numbers. The program uses nested loops to print increasing numbers in each row, forming a half pyramid shape. This exercise helps in practicing loop control and formatting output in C programming.
Comments
Post a Comment
Leave Comment