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
Program to print number pattern in C
Numerical patterns in C programming involve printing sequences of numbers arranged in specific shapes or structures. These patterns follow mathematical rules and are excellent for practicing nested loops and logical thinking.
Syntax
for(i = start; condition; increment/decrement) {
for(j = start; condition; increment/decrement) {
printf("format", value);
}
printf("<br>");
}
Example 1: Triangular Number Pattern
This pattern displays numbers in a triangular format where each row contains specific values based on a mathematical formula −
#include <stdio.h>
int main() {
int i, j, k;
printf("Triangular Number Pattern:<br><br>");
for(i = 1; i <= 5; i++) {
k = i;
for(j = 1; j <= i; j++) {
printf("%d ", k);
k += 5 - j;
}
printf("<br>");
}
return 0;
}
Triangular Number Pattern: 1 2 6 3 7 10 4 8 11 13 5 9 12 14 15
Example 2: Diamond Number Pattern
This creates a diamond shape with numbers, expanding from 1 to the maximum row and then contracting back −
#include <stdio.h>
int main() {
int i, j, k;
printf("Diamond Number Pattern:<br><br>");
/* Upper half of diamond */
for(i = 1; i <= 5; i++) {
/* Print leading spaces */
for(j = i; j < 5; j++) {
printf(" ");
}
/* Print numbers */
for(k = 1; k < (i * 2); k++) {
printf("%d ", k);
}
printf("<br>");
}
/* Lower half of diamond */
for(i = 4; i >= 1; i--) {
/* Print leading spaces */
for(j = 5; j > i; j--) {
printf(" ");
}
/* Print numbers */
for(k = 1; k < (i * 2); k++) {
printf("%d ", k);
}
printf("<br>");
}
return 0;
}
Diamond Number Pattern:
1
1 2 3
1 2 3 4 5
1 2 3 4 5 6 7
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7
1 2 3 4 5
1 2 3
1
How It Works
-
Pattern 1: Uses variable
kinitialized to row numberi, then increments by(5-j)for each position. - Pattern 2: Creates diamond by printing spaces followed by consecutive numbers, with rows expanding then contracting.
- Both patterns use nested loops where outer loop controls rows and inner loops handle spacing and number printing.
Key Points
- Nested loops are essential for creating 2D patterns in C.
- Mathematical formulas determine the relationship between row position and displayed values.
- Proper spacing using loops creates visual alignment in patterns.
Conclusion
Number patterns in C demonstrate the power of nested loops and mathematical logic. These examples show how to create both simple triangular and complex diamond patterns using systematic approaches.
Advertisements
