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 stars in Diamond pattern using C language?
In C programming, printing a diamond pattern with stars is a common pattern printing problem that helps understand nested loops and spacing logic. A diamond pattern consists of an upper triangular half followed by a lower triangular half.
Syntax
// Upper half pattern
for (j = 1; j <= rows; j++) {
for (i = 1; i <= rows-j; i++) // Print spaces
printf(" ");
for (i = 1; i <= 2*j-1; i++) // Print stars
printf("*");
printf("<br>");
}
// Lower half pattern
for (j = 1; j <= rows-1; j++) {
for (i = 1; i <= j; i++) // Print spaces
printf(" ");
for (i = 1; i <= 2*(rows-j)-1; i++) // Print stars
printf("*");
printf("<br>");
}
Understanding the Logic
The diamond pattern is created in two parts −
- Upper Half: Stars increase from 1 to maximum (2*rows-1), with decreasing leading spaces
- Lower Half: Stars decrease from maximum-2 to 1, with increasing leading spaces
Example: Complete Diamond Pattern
#include <stdio.h>
int main() {
int rows = 5, i, j;
printf("Diamond pattern with %d rows:<br><br>", rows);
// Upper half of diamond
for (j = 1; j <= rows; j++) {
for (i = 1; i <= rows-j; i++)
printf(" ");
for (i = 1; i <= 2*j-1; i++)
printf("*");
printf("<br>");
}
// Lower half of diamond
for (j = 1; j <= rows-1; j++) {
for (i = 1; i <= j; i++)
printf(" ");
for (i = 1; i <= 2*(rows-j)-1; i++)
printf("*");
printf("<br>");
}
return 0;
}
Diamond pattern with 5 rows:
*
***
*****
*******
*********
*******
*****
***
*
Pattern Analysis
| Row | Spaces | Stars | Formula |
|---|---|---|---|
| 1 | 4 | 1 | spaces = rows-j, stars = 2*j-1 |
| 2 | 3 | 3 | spaces = 5-2=3, stars = 2*2-1=3 |
| 3 | 2 | 5 | spaces = 5-3=2, stars = 2*3-1=5 |
| 4 | 1 | 7 | spaces = 5-4=1, stars = 2*4-1=7 |
| 5 | 0 | 9 | spaces = 5-5=0, stars = 2*5-1=9 |
Key Points
- The maximum width of the diamond is 2*rows-1 stars
- Upper half uses formula: spaces = rows-j, stars = 2*j-1
- Lower half uses formula: spaces = j, stars = 2*(rows-j)-1
- Total lines printed = 2*rows-1
Conclusion
The diamond pattern demonstrates effective use of nested loops and mathematical formulas for spacing and star count. Understanding this pattern helps in solving more complex pattern printing problems in C programming.
Advertisements
