Loop Assignment 21 — Print an X-Shaped Star Pattern Using Nested For Loops
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program: Print an X-Shaped Star Pattern Using Nested For Loops — Printing Both Diagonals

📑 On this page:
  • How the X-Star Pattern Works
  • The Three Steps of Printing the Pattern
  • Complete C Program
  • Program Output
  • Step-by-Step Explanation
  • Frequently Asked Questions
📚 In this program, you will learn:
  • How to print an X-shaped star pattern using nested for loops
  • How to identify the left diagonal using i == j
  • How to identify the right diagonal using i + j == rows - 1
  • How to print spaces in all other positions
  • Why an odd number of rows creates a better X shape
  • How nested loops represent a square matrix

How the X-Star Pattern Works

An X-shaped star pattern is created by printing stars on two diagonals of a square. The left diagonal moves from the top-left corner to the bottom-right corner, while the right diagonal moves from the top-right corner to the bottom-left corner.

The program uses two nested loops. The outer loop controls the rows, and the inner loop controls the columns. Together, they visit every position in a square of size rows × rows.

A star is printed when the current position lies on either diagonal. Otherwise, a space is printed. After completing one row, the program moves to the next line.

💡 In one line: Print * when i == j or i + j == rows - 1; otherwise print a space.

Diagram showing an X-shaped star pattern created using nested for loops in C

The Three Steps of Printing the Pattern

Step Loop operation Effect
1. Visit each rowfor (i = 1; i <= rows; i++)Controls the current row of the pattern
2. Visit each columnfor (j = 1; j <= rows; j++)Controls the current column in the row
3. Print star or spaceif (i == j || i + j == rows + 1)Prints stars on both diagonals and spaces elsewhere

When loops start from 1, the left diagonal condition is i == j. The right diagonal condition is i + j == rows + 1. If loops start from 0, the right diagonal condition becomes i + j == rows - 1.

For an X-shaped pattern, it is better to use an odd number of rows such as 5, 7, or 9. With an odd number of rows, both diagonals meet exactly at the center position.

Complete C Program

Program: print an X-shaped star pattern using nested for loops

#include <stdio.h>

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

    printf("Enter an odd number of rows: ");
    if (scanf("%d", &rows) != 1 || rows <= 0 || rows % 2 == 0) {
        printf("Invalid input. Please enter a positive odd number.\n");
        return 1;
    }

    for (i = 1; i <= rows; i++) {
        for (j = 1; j <= rows; j++) {
            if (i == j || i + j == rows + 1) {
                printf("*");
            }
            else {
                printf(" ");
            }
        }
        printf("\n");
    }

    return 0;
}
                                    

Program Output

Enter an odd number of rows: 5

*   *
 * * 
  *  
 * * 
*   *
                                

A second run, with 7 rows:

Enter an odd number of rows: 7

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

The stars appear on the left and right diagonals, while spaces appear in all other positions. The two diagonals meet at the center, forming the X shape.

Step-by-Step Explanation

Let us understand how the program prints an X-shaped pattern for 5 rows.

1. The outer loop controls rows

The outer loop for (i = 1; i <= rows; i++) runs from row 1 to row 5. Each iteration prints one complete row of the pattern.

2. The inner loop controls columns

The inner loop for (j = 1; j <= rows; j++) runs from column 1 to column 5. Together, the two loops visit all 25 positions in a 5 × 5 square.

3. Left diagonal condition

The condition i == j is true when the row number and column number are the same. These positions form the left diagonal: (1,1), (2,2), (3,3), (4,4), and (5,5).

4. Right diagonal condition

The condition i + j == rows + 1 is true when the row and column indexes add up to 6. These positions form the right diagonal: (1,5), (2,4), (3,3), (4,2), and (5,1).

5. Center position

The center position (3,3) satisfies both diagonal conditions. Therefore, it prints only one star, which forms the meeting point of the X shape.

6. Printing spaces

If a position is not on either diagonal, the program prints a space. These spaces create the empty areas between the two diagonal lines.

7. Example trace for row 1

  • Position (1,1): i == j is true, so print *.
  • Position (1,2): neither condition is true, so print a space.
  • Position (1,3): neither condition is true, so print a space.
  • Position (1,4): neither condition is true, so print a space.
  • Position (1,5): i + j == 6 is true, so print *.
  • Row 1 output: * *.

8. Example trace for row 3

  • Position (3,1): i + j == 6 is true, so print *.
  • Position (3,2): neither condition is true, so print a space.
  • Position (3,3): both conditions are true, so print *.
  • Position (3,4): neither condition is true, so print a space.
  • Position (3,5): i == j is true, so print *.
  • Row 3 output: * *.

9. Why odd rows are preferred

With an odd number of rows, the two diagonals intersect at one exact center cell. With an even number of rows, the diagonals do not meet at a single center position, so the X shape looks less balanced.

10. Complexity summary

Time complexity is O(n2), because the program visits every position in an n × n square. Space complexity is O(1), because the program uses only loop variables and does not store the pattern in an array.

🎯 Remember this: To print an X pattern, print a star when i == j or i + j == rows + 1. Print a space for every other position.

Frequently Asked Questions

1. Why does i == j print the left diagonal?

When the row number and column number are equal, the position lies on the left diagonal. For example, (1,1), (2,2), and (3,3) all satisfy i == j.

2. Why does i + j == rows + 1 print the right diagonal?

When loops start from 1, the right diagonal positions always add up to rows + 1. For a 5-row pattern, the right diagonal positions are (1,5), (2,4), (3,3), (4,2), and (5,1).

3. Why should the number of rows be odd?

An odd number of rows gives the pattern a single center position where both diagonals meet. This makes the X shape symmetrical and visually balanced.

4. Can this program print an X pattern with even rows?

Yes, but the diagonals will not meet at one exact center cell. The program can still print an X-like shape, though it may look less symmetrical.

5. How can I print the pattern using 0-based indexing?

Start both loops from 0 and use i == j for the left diagonal and i + j == rows - 1 for the right diagonal. The output will be the same.

6. What is the time complexity of this program?

The time complexity is O(n2), because the program visits every position in an n × n square. Space complexity is O(1), since no additional array is used.

💡 Tip: After implementing this program, try printing a hollow square, a plus sign, or a diamond pattern. All these patterns use the same idea of checking row and column positions inside nested loops.

📖 Related Tutorials

  • 20. Print Floyd's Triangle Using Nested For Loops
  • 22. Print a Plus-Sign Star Pattern Using Nested For Loops
  • 9. Print the Pattern of a Pyramid Using a For Loop
  • 13. Print the Pattern of a Diamond Using a For Loop
  • All Loop Assignments in C

Previous Topic: -->> 20. Write a program in C to print Floyd's triangle using nested for loops.   ||   Next Topic: -->> 22. Write a program in C to print a plus-sign star pattern using nested for loops.


C Language

  • Home
  • Why C Language
  • History of C Language
  • Applications of C Language
  • Introduction To C
    • What is Program?
    • Structure of C Program
    • Working Of C Program
    • CHARACTER SET
    • VARIABLES AND IDENTIFIERS
    • BUILT-IN DATA TYPES
    • OPERATORS AND EXPRESSIONS
    • CONSTANTS AND LITERALS
    • SIMPLE ASSIGNMENT STATEMENT
    • BASIC INPUT/OUTPUT STATEMENT
    • SIMPLE 'C' PROGRAMS
    • Assignments
  • Operators in C Programming
    • Arithmetic Operators
    • Assignment Operators
    • Increment and Decrement Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Other Operators
    • Assignments
  • CONDITIONAL STATEMENTS
    • DECISION MAKING WITHIN A PROGRAM
    • CONDITIONS
    • IF STATEMENT
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • SWITCH CASE
    • Assignments
  • LOOPS STATEMENTS
    • Introduction to Loops
    • GO TO Statement
    • Do while Loop
    • While Loop
    • Nested While Loop
    • Difference Between While and Do while
    • Difference Between Goto and loop
    • while loop assignments
    • C FOR Loop
    • C For loop examples
    • Nested for loop
    • Nested for loop examples
    • Infinite while Loops
    • Infinite for Loops
    • Continue in Loops
    • break in Loops
    • difference while do..while & for
    • Assignments
  • Arrays
    • One Dimensional Array
    • Declaring 1D Arrays
    • Initilization of 1D arrays
    • Accessing element of one 1D Array
    • Read and Display 1D Arrays
    • Two Dimensional Arrays
    • Declare 2D Arrays
    • Read and Display 2D Arrays
    • Assignments/Examples
  • Functions
    • Introduction
    • Need For User-Defined Function
    • Multiple Function Program
    • Modular Programming
    • Elements Of User Defined Function
    • Function Definition
    • Function Declaration
    • Types of functions
    • Nesting of Function
    • Recursion
    • Passing Array To Functions
    • Scope,Visibility and Lifetime of Variables
    • Assignments
  • Structure
    • Introduction
    • Array vs Structure
    • Defining Structure
    • Declaring Structure Variables
    • Type Defined Structure
    • Accessing Structure Members
    • Structure Initilization
    • Copying & Comparing Structure Variables
    • Array of Structure
    • Arrays Within Structure
    • Structures Within Structures
    • Structures and Functions
    • Structure Examples/Assignments
  • Union
    • Define Union
    • Create and use Union
    • Difference Between Structure and Union
    • Union Examples
    • Union FAQ
  • Pointers
    • What Are Pointers In C?
    • How Do We Use Pointers In C?
    • Declaration Of A Pointer
    • The Initialization Of A Pointer
    • Syntax Of Pointer Initialization
    • Use Of Pointers In C
    • The Pointer To An Array
    • The Pointer To A Function
    • The Pointer To A Structure
    • Types Of Pointers
    • The Null Pointer
    • The Void Pointer
    • The Wild Pointer
    • The Near Pointer
    • The Huge Pointer
    • The far Pointer
    • dangling pointer
    • Accessing Pointers- Indirectly And Directly
    • Pros Of Using Pointers In C
    • Cons Of Pointers In C
    • Applications Of Pointers In C
    • The & Address Of Operator In C
    • How To Read The Complex Pointers In C?
    • Practice Problems On Pointers
  • File Processiong
    • File Handling In C
    • Types Of Files In C
    • Operations Done In File Handling
    • File Examples
    • Binary Files
    • count words,lines in a file
    • Copy files
    • Update File
    • count vowels in a file
  • Preprocessor
    • Macro substitution division
    • File Inclusion
    • Conditional Compilation
    • Other directives
    • Examples
  • Dynamic Memory Allocation
    • malloc
    • calloc
    • free
    • realloc
    • Examples
  • Storage Classes
  • Graphics
  • Frequently Asked Interview Questions (FAQ)
    • Introduction To C FAQ
    • Operators FAQ
    • Conditional Statements FAQ
    • Loops FAQ
    • Arrays FAQ
    • Function FAQ
    • Structure FAQ
    • Pointers FAQ
    • Files FAQ
    • Storage classes FAQ
    • Dynamic Memory FAQ
  • Programs/Assignments
    • Introduction To C
    • Operators
    • Conditional Statements
    • Loops
    • Arrays
    • Function
    • Structure
    • Pointers
    • Files
    • Storage classes
    • Dynamic Memory
  • Case Studies
  • Multiple Choice Questions
    • Introduction To C MCQ
    • Operators MCQ
    • Conditional Statements MCQ
    • Loops MCQ
    • Arrays MCQ
    • Function MCQ
    • Structure MCQ
    • Pointers MCQ
    • Files MCQ
    • Storage classes MCQ
    • Dynamic Memory MCQ
    • More MCQ

Get in touch

  • tech2dsm@gmail.com

© Sankalan Data Tech. All rights reserved.