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. Logic to print half diamond star pattern series in C program.

Example

Input

Input rows: 5

Output

Required knowledge

Basic C programming, For loop

Read more - Program to print mirrored half diamond star pattern

Logic to print half diamond star pattern

On first glance the pattern may look as a complex one to print. However, 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.

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 need to combine code of both the program one by one to get the final pattern.

Program to print half diamond star pattern

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

#include <stdio.h>

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

    // Input number of columns from user
    printf("Enter value of n : ");
    scanf("%d", &n);
   
    // Print upper half part of the pattern
    for(i=1; i<=n; i++)
    {
        for(j=1; j<=i; j++)
        {
            printf("*");
        }
        printf("\n");
    }

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

    return 0;
}

Program to print half diamond star pattern

This logic was submitted by one of our Codeforwin reader Sankar Majumder. It uses two loops instead of four as above program.

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

#include<stdio.h>

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

    // Input number of columns from user
    printf("Enter number of columns:");
    scanf("%d",&n);

    columns=1;

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

        if(i < n)
        {
            /* Increment number of columns per row for upper part */
            columns++;
        }
        else
        {
            /* Decrement number of columns per row for lower part */
            columns--;
        }

        printf("\n");
    }

    return 0;
}

Output

Enter number of columns: 5
*
**
***
****
*****
****
***
**
*
Happy coding ;)

Write your doubts or suggestion. I will try my best to help. You must escape source code before commenting. To format your source code paste your source code inside
<pre><code> ----Your Source Code---- </code></pre>