C Program to Print a Cross (X) Pattern

1. Introduction

Printing patterns in C is a great way to practice loops and conditionals. In this tutorial, we will learn how to print a cross (X) pattern. This pattern consists of stars (*) that form the shape of an X, and it demonstrates an interesting use of logic within nested loops to manage space and character printing.

2. Program Steps

1. Ask the user to enter the size of the cross pattern. The size will determine both the height and the width of the pattern.

2. Use nested loops to iterate through each row and column, printing a star (*) at positions where a star should appear to form the cross pattern.

3. Use conditional statements within the loops to determine whether a star or a space should be printed at a given position.

3. Code Program

#include <stdio.h>

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

    // Prompting user input
    printf("Enter the size of the cross: ");
    scanf("%d", &size);

    for(i = 1; i <= size; i++) {
        for(j = 1; j <= size; j++) {
            // Printing stars at diagonals
            if(j == i || j == (size - i + 1)) {
                printf("*");
            } else {
                printf(" ");
            }
        }
        printf("\n");
    }

    return 0;
}

Output:

Enter the size of the cross: 5
*   *
 * *
  *
 * *
*   *

Explanation:

1. The program starts with the inclusion of the stdio.h header file, which is required for input/output operations.

2. The main function declares three integer variables: size, for storing the size of the cross, and i and j, for loop control.

3. The user is prompted to enter the size of the cross, which is then read and stored in the size variable.

4. A nested loop structure is used to iterate over each row (i) and each column (j) within that row. The loops range from 1 to size.

5. Inside the inner loop, a conditional statement checks if the current position is on one of the two diagonals of the square (where j == i or j == (size - i + 1)). If so, a star (*) is printed.

6. If the current position is not on a diagonal, a space ( ) is printed instead. This logic creates the cross pattern.

7. After all columns in a row have been processed, a newline character (\n) is printed to move to the next row.

8. The process repeats until the pattern is complete. The program then ends with return 0;, indicating successful execution.


Comments