C program to print hollow diamond star pattern

Write a C program to print hollow diamond star (*) pattern series of n rows using for loop. How to print hollow diamond star pattern structure using for loop in C programming. The pattern should look like:
**********
****  ****
***    ***
**      **
*        *
*        *
**      **
***    ***
****  ****
**********

Required knowledge:

Basic C programming, For loop
Before continuing to this pattern you must know how to print diamond star pattern.

Logic:

The pattern seems to be one of the complex pattern to think. To make it easier bisect it in two halves where the upper half looks like:
**********
****  ****
***    ***
**      **
*        *
and lower half looks like:
*        *
**      **
***    ***
****  ****
**********
Now consider the upper pattern here trailing stars are simple inverted right triangle pattern that can be easily printed and each row contains total 2*rownumber - 2 spaces and the leading stars are will be also printed same as trailing stars.

Now moving on to the second half if you look the the trailing and leading stars you will find that both of them are simple right triangle star patterns and total number of spaces per row is 2*rownumber - 2.

Program:

/**
 * C program to print hollow diamond star pattern
 */

#include <stdio.h>

int main()
{
    int i, j, n;

    printf("Enter value of n : ");
    scanf("%d", &n);

    //Loop for printing upper half part of the pattern
    for(i=1; i<=n; i++)
    {
        for(j=i; j<=n; j++)
        {
            printf("*");
        }

        for(j=1; j<=(2*i-2); j++)
        {
            printf(" ");
        }

        for(j=i; j<=n; j++)
        {
            printf("*");
        }

        printf("\n");
    }

    //Loop for printing lower half part of the pattern
    for(i=1; i<=n; i++)
    {
        for(j=1; j<=i; j++)
        {
            printf("*");
        }

        for(j=(2*i-2); j<(2*n-2); j++)
        {
            printf(" ");
        }

        for(j=1; j<=i; j++)
        {
            printf("*");
        }

        printf("\n");
    }

    return 0;
}


Output
X
_
Enter value of n : 5
**********
****  ****
***    ***
**      **
*        *
*        *
**      **
***    ***
****  ****
**********


Screenshot:

Hollow diamond star pattern in C

Happy coding ;)


Any doubt or suggestion write here. I will try my best to help. Before posting your code you must escape it to view. To format your source code and use format highlighting, post your source code inside
< code >< pre > -- Your source code -- < /pre >< /code > (Remove spaces from pre and code tags).

No comments:

Post a Comment