C (programming language)
C program to print half right side of pyramid number pattern
Understanding the Problem
- Goal: Write a C program that prints a half right-side pyramid pattern of numbers, starting from 1 and incrementing in each row.
- Key Concepts:
- Loops:
for
loops for controlled iterations. - Indentation: Aligning numbers for visual pattern.
- Formatting output:
printf
for printing numbers and spaces.
- Loops:
Step-by-Step Guide
1. Header Inclusion
C
#include <stdio.h>
- Explanation: Include the standard input/output library for functions like
printf
.
2. Main Function
C
int main() {
// Code statements here
return 0;
}
3. Get User Input
C
int rows;
printf("Enter the number of rows: ");
scanf("%d", &rows);
4. Outer Loop for Rows
C
for (int i = 1; i <= rows; i++) {
// Code for printing each row
}
5. Inner Loop for Columns
C
for (int j = 1; j <= i; j++) {
printf("%d ", j); // Print the number
}
printf("\n"); // Move to the next line after each row
6. Indentation for Pattern
C
// Indentation for aligning numbers to the right
for (int j = 1; j <= rows - i; j++) {
printf(" "); // Print two spaces for indentation
}
7. 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 - i; j++) {
printf(" ");
}
for (int j = 1; j <= i; j++) {
printf("%d ", j);
}
printf("\n");
}
return 0;
}
8. Executing the Program
- Save the code as a
.c
file (e.g.,half_pyramid.c
). - Compile using a C compiler (e.g.,
gcc half_pyramid.c -o half_pyramid
). - Run the executable (e.g.,
./half_pyramid
).
Example Output
Enter the number of rows: 5 1 1 2 1 2 3 1 2 3 4 1 2 3 4 5