C program to print mirrored half diamond star pattern

Write a C program to print the mirrored half diamond star(*) pattern using for loop. How to print mirrored half diamond star pattern structure using for loop in C programming. The pattern with 5 columns should look like:
    *
   **
  ***
 ****
*****
 ****
  ***
   **
    *
If you are looking for reverse of this pattern find it here how to print half diamond star pattern.

Required knowledge:

Basic C programming, For loop

Logic:

Here to print this pattern I am going to bisect this pattern to make the task easy. The first upper half look likes:
    *
   **
  ***
 ****
*****
And the lower half look likes:
 ****
  ***
   **
    *
Now, if you have done with previous patterns you will find that the first half is the mirrored right triangle star pattern and the second half is the inverted mirrored right triangle star pattern. Hence, in-order to get the final pattern we need to write the codes of both the pattern one by one.

Program:

/**
 * C program to print mirrored half diamond star pattern
 */

#include <stdio.h>

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

    //Reads number of columns to be printed from user
    printf("Enter value of n : ");
    scanf("%d", &n);

    //Prints the upper half part of the pattern
    for(i=1; i<=n; i++)
    {
        for(j=i; j<n; j++)
        {
            printf(" ");
        }
        for(j=1; j<=i; j++)
        {
            printf("*");
        }
        printf("\n");
    }
    
    //Prints the lower half part of the pattern
    for(i=n; i>=1; i--)
    {
        for(j=i; j<=n; j++)
        {
            printf(" ");
        }
        for(j=1; j<i; j++)
        {
            printf("*");
        }
        printf("\n");
    }

    return 0;
} 


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


Screenshot:

C program to print mirrored half diamond star pattern

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