C program to print half diamond star pattern

In this article, I will show you, How to write a C program to print half diamond star patterns. How to print half diamond star pattern in C programming. Here, one thing is important to know that the columns of the half diamond.

Logic to C program to print half diamond star pattern:

  • Enter the column value for the half diamond.
  • Here I have used two loops one is the outer loop to change the line and the second is inner loops to print star.
  • Create a variable col and initialized with 1.
  • The outer loop iterates column times and prints a newline after completing the inner loop. It also increments and decrements the col variable according to columns (a variable that contains columns of half diamond).
  • Inner loop print the star 1 to the col (current column count).

Logic to C program to print half diamond star pattern:

 

#include <stdio.h>

int main()
{
    int x = 0,y = 0;
    unsigned int columns = 0;
    unsigned int col = 0;
    
    printf("Enter the number of columns = ");
    scanf("%u",&columns);

    for(x=0; x < (columns*2) ; ++x)
    {
        // Print spaces
        for(y=0; y < col; ++y)
        {
            printf("*");
        }
        (x<columns)?(++col):(--col);
        
        // Print new line
        printf("\n");
    }
    return 0;
}

 

Output:

print half diamond star pattern

 

Code Analysis:

It asks the user to enter the columns for the half diamond.

printf("Enter the number of columns = ");
scanf("%u",&columns);

 

Inner loop print star 1 to (col-1)  times.

// Print star
for(y=0; y < col; ++y)
{
    printf("*");
}

 

The outer loop iterates 0 to (2* columns). It prints the new line and calculates the value of col.

for(x=0; x < (columns*2) ; ++x)
{
    // Print star
    for(y=0; y < col; ++y)
    {
        printf("*");
    }
    (x<columns)?(++col):(--col);
    
    // Print new line
    printf("\n");
}

 

Recommended Post:



Leave a Reply

Your email address will not be published. Required fields are marked *