C program to print X star pattern

Write a C program to print X star pattern series using loop. How to print the X star pattern series using for loop in C programming. Logic to print X using stars in C program.

Example:
Input N: 5
Output:

Required knowledge:

Basic C programming, If else, Loop

Logic to print X star pattern

Logic to print the X star pattern can really be complex and confusing if you haven't gone through two previous star pattern programs.
C program to print hollow pyramid star pattern.
C program to print hollow inverted pyramid star pattern.

If you bisect the pattern horizontally you will get two pattern.

X star pattern is a combination of both of these patterns. Where the first one is similar to the hollow inverted pyramid and second one to hollow pyramid star pattern. Hence if you haven't gone through these two posts I recommend you to go through them before continuing. As I won't be getting in detail about these two patterns here.

Program to print X star pattern

/**
 * C program to print X star pattern series
 */

#include <stdio.h>

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

    printf("Enter N: ");
    scanf("%d", &N);

    // Print first upper hollow inverted pyramid
    for(i=N; i>=1; i--)
    {
        //Prints trailing spaces
        for(j=i; j<N; j++)
        {
            printf(" ");
        }

        //Prints upper hollow triangular part
        for(j=1; j<=(2*i-1); j++)
        {
            if(j==1 || j==(2*i-1))
            {
                printf("*");
            }
            else
            {
                printf(" ");
            }
        }

        printf("\n");
    }

    // Prints the lower half hollow pyramid 
    for(i=2; i<=N; i++)
    {
        //Prints trailing spaces
        for(j=i; j<N; j++)
        {
            printf(" ");
        }

        //Prints lower hollow triangular part
        for(j=1; j<=(2*i-1); j++)
        {
            if(j==1 || j==(2*i-1))
            {
                printf("*");
            }
            else
            {
                printf(" ");
            }
        }

        printf("\n");
    }

    return 0;
}


Before you move on. You might love to check the similar number pattern program


Output
Enter N: 5
*       *
 *     *
  *   *
   * *
    *
   * *
  *   *
 *     *
*       *


Snapshot

X 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