Program to print hollow diamond star pattern using c
Question:
Write a c program to print hollow diamond pattern using the stars.
Logic:
- Get the length as an input from the user.
- Then print the corresponding spaces.
- And print the star only in the borders.
Program:
#include<stdio.h> void main() { int i,j,n; clrscr(); printf("enter the length:"); scanf("%d",&n); for(i=0;i<n;i++) //prints the first half of the pattern { for(j=i;j<n-1;j++) //prints the spaces { printf(" "); } for(j=0;j<=2*i;j++) //2*i can gives total columns to print { if(j==0||j==2*i) //it prints the first and last coulumn { printf("*"); } else //prints intermediate spaces { printf(" "); } } printf("\n"); } for(i=n-1;i>=1;i--) //prints the second half { for(j=i;j<n;j++) //at same it prints spaces { printf(" "); } for(j=1;j<2*i;j++) { if(j==1||j==2*i-1) //it prints the boundaries as * { printf("*"); } else { printf(" "); } } printf("\n"); } getch(); }
Alternative
#include<stdio.h> int main() { int size,i,k,temp,temp1=-3; printf("Enter the size:"); scanf("%d",&size); for(i=0;i<(2*size)-1;i++) { temp=size-i-1; if(i>=size) { temp*=-1; temp1-=2; } else temp1+=2; for(k=0;k<temp;k++) printf(" "); printf("*"); for(k=0;k<temp1;k++) printf(" "); if(i!=0&&i!=(2*size)-2) printf("*"); printf("\n"); } return 0; }