Introduction
An alternating star (*
) and space pattern is a simple yet interesting pattern where stars and spaces alternate in each row. This exercise helps in practicing how to control loops and conditional statements to print patterns in C programming.
Problem Statement
Create a C program that:
- Accepts the number of rows and columns.
- Prints a pattern where stars and spaces alternate in each row.
Example:
- Input:
rows = 5, columns = 5
- Output:
* * * * * * * * * * * * * * * * * * * * * * *
Solution Steps
- Input the Number of Rows and Columns: The user specifies the number of rows and columns for the pattern.
- Use Nested Loops: The outer loop controls the rows, and the inner loop controls printing the stars and spaces alternately in each row.
- Display the Alternating Pattern: Stars and spaces alternate across each row, and rows also alternate between starting with a star or a space.
C Program
#include <stdio.h>
int main() {
int i, j, rows, columns;
// Step 1: Accept the number of rows and columns
printf("Enter the number of rows: ");
scanf("%d", &rows);
printf("Enter the number of columns: ");
scanf("%d", &columns);
// Step 2: Outer loop for rows
for (i = 1; i <= rows; i++) {
// Step 3: Inner loop for columns
for (j = 1; j <= columns; j++) {
// Step 4: Print star or space based on the sum of i and j
if ((i + j) % 2 == 0) {
printf("*");
} else {
printf(" ");
}
}
// Move to the next line after each row
printf("\n");
}
return 0;
}
Explanation
Step 1: Input Number of Rows and Columns
- The program starts by asking the user to input the number of rows and columns for the alternating star and space pattern.
Step 2: Outer Loop for Rows
- The outer loop controls how many rows are printed. It runs from
1
torows
.
Step 3: Inner Loop for Columns
- The inner loop controls the number of columns printed in each row.
Step 4: Conditional Printing
- The condition
(i + j) % 2 == 0
is used to alternate between printing a star (*
) and a space. If the sum of the row indexi
and the column indexj
is even, a star is printed; if odd, a space is printed.
Output Example
For rows = 5
and columns = 5
, the output will be:
* * * * *
* * * *
* * * * *
* * * *
* * * * *
For rows = 6
and columns = 6
, the output will be:
* * * * * *
* * * * *
* * * * * *
* * * * *
* * * * * *
* * * * *
Conclusion
This C program prints an alternating star and space pattern using nested loops and conditional logic. The program alternates stars and spaces across the rows and columns, with each row alternating between starting with a star or a space. This exercise is useful for practicing loop control and conditional statements in C programming.
Comments
Post a Comment
Leave Comment