C program to print plus star pattern

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

Example:
Input N: 5


Required knowledge

Basic C programming, If else, Loop

Logic to print plus star pattern

Before you write or think about logic of the pattern. Take a close look about the pattern and identify some noticeable things about it. Here are some.
  1. The pattern consists of N * 2 - 1 rows (where N is the value enter by user).
  2. When you look to the center horizontal plus line i.e. +++++++++ this line. It also consists of N * 2 - 1 columns.
  3. For every other row, single plus symbol gets printed after N - 1 blank spaces, for this case it is 4.
Based on the above observation we can easily code down the solution.

Program to print plus star pattern series

/**
 * C program to print the plus star pattern series
 */

#include <stdio.h>

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

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

    // Run an outer loop from 1 to N*2-1
    for(i=1; i<=(N * 2 - 1); i++)
    {
        // For the center horizontal plus
        if(i == N)
        {
            for(j=1; j<=(N * 2 - 1); j++)
            {
                printf("+");
            }
        }
        else
        {
            // For spaces before single plus sign
            for(j=1; j<=N-1; j++)
            {
                printf(" ");
            }
            printf("+");
        }

        printf("\n");
    }

    return 0;
}


Output
Enter N: 5
    +
    +
    +
    +
+++++++++
    +
    +
    +
    +


Snapshot

Plus 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