C Program
C Program to print Hollow Diamond Star Pattern
Example :-
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i,j,rows;
printf("Enter the number \n");
scanf("%d",&rows);
for(i=1; i<=rows; i++){
for(j=rows; j>i; j--){
printf(" ");
}
printf("*");
for(j=1; j<(i-1)*2; j++){
printf(" ");
}
if(i==1){
printf("\n");
}
else{
printf("*\n");
}
}
for(i=rows-1; i>=1; i--){
for(j=rows; j>i; j--){
printf(" ");
}
printf("*");
for(j=1; j<(i-1)*2; j++){
printf(" ");
}
if(i==1){
printf("\n");
}
else{
printf("*\n");
}
}
return 0;
}
C Program to Display a Hollow Diamond Shape with Star
Explain Program
Step :1
Header and main function
#include <stdio.h>
#include <stdlib.h>
{
int i, j, rows;
- #include
<stdio.h>: - use printf() , scanf() for input/output.
- #include <stdlib.h>: -use
- int i, j, rows; :-- Loop variables i & j, and rows is the number of rows input by the user
Step :2
User Input
printf("Enter the number \n");
scanf("%d", &rows);
- enter how many rows the upper half of the diamond
- rows
= 5, diamond will have 2 * rows - 1 = 9 lines total.
Step :3
Top Half of the Hollow Diamond
for(i = 1; i <= rows; i++) {
for (j = rows; j
> i; j--) {
printf("
");
}
printf ("
");
}
printf("\n");
} else {
printf ("*\n");
}
}
How it work:
- i represent to the current row number
- First inner loop (for (j = rows; j > i; j--))
- Print spaces to align the star to the center.
- printf("*"); Print the first star the line.
- Second inner loops (for (j = 1; j < (i - 1) *2; j++ ))
- Prints the hollow spaces between two stars.
- On line 1: no space.
- On line 2: 1 space.
- On line 3: 3 spaces.
- Final if:
- first line (i == 1), only one * is printed (no second star).
- From line 2 onwards, two *s are printed with space in between.
Step :4
Bottom Half of the Hollow Diamond
for(i = rows - 1; i >= 1; i--) {
for(j = rows; j
> i; j--) {
printf("
");
}
printf("
");
}
printf("\n");
} else {
printf("*\n");
}
}
How it work:
- This is a mirror of the top half but in reverse.
- i from rows - 1 down to 1 to avoid repeating the middle line.
- Same logic applies:
- Print leading spaces.
- Print one *.
- Print hollow middle spaces if needed.
- Print second * if not the last line.
Step :5
Program Exit
return 0;
}
successful program execution.
No comments:
Post a Comment