C program to print half diamond star pattern

Write a C program to print the half diamond star(*) pattern series using for loop. How to print 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 mirrored half diamond star pattern.

Required knowledge:

Basic C programming, For loop

Logic:

On first glance the pattern may look as a complex one to print. But if you look carefully you will find that the pattern can be divided into two parts to make our task easy. Let's us divide the pattern in two halves - the first upper half look likes:
*
**
***
****
*****
and the second half should look like:
****
***
**
*
If you have done previous stars patterns you will find that first pattern is the simple right triangle star pattern(with n rows) and second is the inverted right triangle star pattern(with n-1 rows). Now, we just need to write codes of both the program one by one to get the final pattern.

Program:

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

#include <stdio.h>

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

    //Reads number of columns 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=1; j<=i; j++)
        {
            printf("*");
        }
        printf("\n");
    }

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

    return 0;
} 


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


Screenshot:

C program to print 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).

1 comment: