Program to print hollow diamond star pattern using c

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:

[code lang=”c”]
#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();
}
[/code]

 

Alternative

[code lang=”c”]
#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;
}
[/code]

 

Vignesh

A Computer Science graduate who likes to make things simpler. When he’s not working, you can find him surfing the web, learning facts, tricks and life hacks. He also enjoys movies in his leisure time.

Leave a Reply

Your email address will not be published. Required fields are marked *