C Program to Print a Plus (+) Pattern

1. Introduction

Printing patterns is a fundamental exercise in learning C programming, enhancing understanding of nested loops and conditionals. This tutorial will demonstrate how to print a plus (+) pattern, which involves strategically placing characters to form the shape of a plus sign. This pattern is an excellent example of using basic programming constructs to achieve visually interesting results.

2. Program Steps

1. Determine the size of the plus pattern, which will affect both its height and width.

2. Use nested loops to iterate over each row and column of the pattern.

3. Within the loops, use conditional statements to print a star (*) in positions that form the vertical and horizontal lines of the plus sign.

4. Ensure that the middle row and the middle column are filled with stars, while other positions are left blank.

3. Code Program

#include <stdio.h>

int main() {
    int size, i, j, mid;

    // User input for the size of the plus pattern
    printf("Enter the size of the plus pattern: ");
    scanf("%d", &size);

    mid = size / 2 + 1; // Calculate the middle position

    for(i = 1; i <= size; i++) {
        for(j = 1; j <= size; j++) {
            // Print stars for the middle row and middle column
            if(i == mid || j == mid) {
                printf("*");
            } else {
                printf(" ");
            }
        }
        printf("\n");
    }

    return 0;
}

Output:

Enter the size of the plus pattern: 5
  *
  *
*****
  *
  *

Explanation:

1. The program includes stdio.h for standard input and output operations.

2. The main function initializes variables size for the overall dimensions of the pattern, i and j for loop control, and mid to calculate the middle position of the pattern.

3. The user is prompted to input the size of the plus pattern. This size determines the height and width of the pattern.

4. The middle position is calculated by dividing the size by 2 and adding 1, ensuring it works for both odd and even sizes.

5. A nested loop structure iterates over each row (i) and column (j), within the dimensions of the pattern.

6. Conditional statements inside the loops check if the current row or column is the middle of the pattern (i == mid || j == mid). If so, a star (*) is printed to form the vertical and horizontal lines of the plus sign.

7. Spaces are printed in all other positions, maintaining the clarity of the plus sign shape.

8. After completing each row, a newline character (\n) is printed to start a new row.

9. The program concludes with return 0;, indicating successful execution.


Comments