Reputation: 19
I want to create a program to print a pattern as shown below,
**********
**** ****
*** ***
** **
* *
I've tried creating this pattern, but it's not printing the star in the middle of the first line. This is the code.
int main()
{
int i,j,k,l;
char c='*';
for(i=1;i<=5;i++)
{
for(j=5;j>=i;j--)
{
printf("%c",c);
}
for(k=1;k<=i;k++)
{
printf(" ");
}
for(l=5;l>=i;l--)
{
printf("%c",c);
}
printf("\n");
}
getch();
return 0;
}
This program prints the pattern shown below.
***** *****
**** ****
*** ***
** **
* *
So, what are your suggestions ?
Upvotes: 1
Views: 131
Reputation: 5872
try this,
#include <stdio.h>
#include <string.h>
int main()
{
int i,j,k,l;
char c='*';
for(i=1;i<=5;i++)
{
for(j=5;j>=i;j--)
{
printf("%c",c);
}
for(k=1;k<i;k++)
{
printf(" ");
}
for(l=5;l>=i;l--)
{
printf("%c",c);
}
printf("\n");
}
getch();
return 0;
}
output:
**********
**** ****
*** ***
** **
* *
this code also display same output :) if anyone can try this if want :)
#include <stdio.h>
#include <string.h>
int main()
{
int i,j,k=0;
for(i=5;i>=1;i--)
{
for(j=1;j<=i;j++)
{
printf("*");
}
for(j=1;j<=k;j++)
{
printf(" ");
}
k = k+2;
for(j=1;j<=i;j++)
{
printf("*");
}
printf("\n");
}
getch();
return 0;
}
Upvotes: 0
Reputation: 2528
The precision %.precision
field can be used to print a specific number of characters and the asterisk allows a variable to be used as the precision.
#include <stdio.h>
int main ( void)
{
char stars[10] = "*********";
char spaces[10] = " ";
int i = 0;
for ( i = 0; i < 5; i++) {
printf ( "%.*s%.*s%.*s\n", 5 - i, stars, i * 2, spaces, 5 - i, stars);
}
return 0;
}
Upvotes: 1
Reputation: 8464
To avoid the redundant space just change:
for(k=1;k<=i;k++)
to:
for(k=1;k<i;k++)
Upvotes: 1
Reputation: 2790
You only need to remove one space:
for(k=1;k<i;k++) // changing the <= to <
Upvotes: 0
Reputation: 6405
The center loop should be for(k=1;k<i;k++)
(with a <
instead of <=
).
Otherwise, each line has an extra space in the middle.
Upvotes: 1