Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to print the numbers in different formats using C program?
In C programming, we can print numbers and symbols in different patterns like pyramids and triangles using nested loops. The outer loop controls the rows while inner loops handle spacing and pattern generation.
Syntax
for(int i = 1; i <= rows; i++) {
// Outer loop for rows
for(int j = 1; j <= columns; j++) {
// Inner loop for columns/pattern
printf("pattern");
}
printf("
");
}
Example 1: Star Pyramid Pattern
This program creates a pyramid using stars with proper spacing −
#include <stdio.h>
int main() {
int n;
printf("Enter number of lines: ");
scanf("%d", &n);
printf("
");
// Loop for each row
for(int i = 1; i <= n; i++) {
// Print leading spaces
for(int space = 0; space <= n - i; space++) {
printf(" ");
}
// Print stars
for(int j = 1; j <= i * 2 - 1; j++) {
printf("*");
}
printf("
");
}
return 0;
}
Enter number of lines: 5
*
***
*****
*******
*********
Example 2: Number Right Triangle
This program displays numbers in a right-angled triangle pattern −
#include <stdio.h>
int main() {
int i, j, rows;
printf("Input number of rows: ");
scanf("%d", &rows);
for(i = 1; i <= rows; i++) {
for(j = 1; j <= i; j++) {
printf("%d ", j);
}
printf("
");
}
return 0;
}
Input 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
Example 3: Inverted Number Triangle
This program creates an inverted triangle pattern with numbers −
#include <stdio.h>
int main() {
int i, j, rows;
printf("Input number of rows: ");
scanf("%d", &rows);
for(i = rows; i >= 1; i--) {
for(j = 1; j <= i; j++) {
printf("%d ", j);
}
printf("
");
}
return 0;
}
Input number of rows: 5 1 2 3 4 5 1 2 3 4 1 2 3 1 2 1
Key Points
- Use nested loops where outer loop controls rows and inner loops control columns and spacing.
- For pyramids, calculate spaces as
(total_rows - current_row)and stars as(2 * current_row - 1). - Always use proper spacing and formatting for clear pattern display.
Conclusion
Number and symbol patterns in C are created using nested for loops. The key is understanding how to control spacing, repetition, and formatting to achieve the desired visual output.
Advertisements
