C Program to Print Zig-Zag Star Pattern

Introduction

A Zig-Zag star pattern consists of stars (*) arranged in a zig-zag format. This pattern can be constructed using nested loops by controlling when to print stars and spaces. It helps in understanding how to use conditional statements and loops to control output format in C programming.

Problem Statement

Create a C program that:

  • Accepts the number of rows for the zig-zag pattern.
  • Prints a zig-zag star pattern.

Example:

  • Input: rows = 5
  • Output:
        *       *
      *   *   *   *
    *       *       *
    

Solution Steps

  1. Input the Number of Rows: The size determines the number of rows in the zig-zag pattern.
  2. Use Nested Loops: The outer loop will handle the rows, and the inner loop will handle printing stars and spaces.
  3. Conditionally Print Stars: The stars are printed based on their positions to form the zig-zag pattern.

C Program

#include <stdio.h>

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

    // Step 1: Accept the number of rows for the zig-zag pattern
    printf("Enter the number of rows: ");
    scanf("%d", &rows);

    // Step 2: Outer loop for rows
    for (i = 1; i <= rows; i++) {
        // Step 3: Inner loop for columns
        for (j = 1; j <= 2 * rows; j++) {
            // Step 4: Conditionally print stars to create the zig-zag pattern
            if ((i + j) % 4 == 0 || (i == 2 && j % 4 == 0)) {
                printf("*");
            } else {
                printf(" ");
            }
        }
        // Move to the next line after each row
        printf("\n");
    }

    return 0;
}

Explanation

Step 1: Input Number of Rows

  • The program starts by asking the user to input the number of rows for the zig-zag pattern.

Step 2: Outer Loop for Rows

  • The outer loop controls the number of rows to be printed. It runs from 1 to rows.

Step 3: Inner Loop for Columns

  • The inner loop controls how many columns are printed in each row. The number of columns printed is approximately 2 * rows to allow room for the zig-zag pattern.

Step 4: Conditional Star Printing

  • The condition (i + j) % 4 == 0 ensures that stars are printed in a zig-zag pattern. The secondary condition (i == 2 && j % 4 == 0) adjusts the middle row to align the stars properly.

Output Example

For rows = 5, the output will be:

    *       *
  *   *   *   *
*       *       *

For rows = 7, the output will be:

      *       *       *
    *   *   *   *   *   *
  *       *       *       *

Conclusion

This C program prints a zig-zag star pattern using nested loops and conditional statements. The program aligns the stars in a zig-zag format by determining which positions to print stars and which to leave as spaces. This exercise is useful for learning how to control output format and create complex patterns in C programming.

Comments