Dushyant vishwakarma
Dushyant vishwakarma

Reputation: 19

How can I print this pattern?

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

Answers (5)

Sachith Wickramaarachchi
Sachith Wickramaarachchi

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

xing
xing

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

Ohad Eytan
Ohad Eytan

Reputation: 8464

To avoid the redundant space just change:

for(k=1;k<=i;k++)

to:

for(k=1;k<i;k++)

Upvotes: 1

granmirupa
granmirupa

Reputation: 2790

You only need to remove one space:

    for(k=1;k<i;k++) // changing the <= to <

Upvotes: 0

Aganju
Aganju

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

Related Questions