The solid square is one of the most fundamental patterns in C programming
What You Will Learn
In this tutorial, we will walk through the implementation of a C program that prints a solid square of a given size. You will learn how to structure nested loops to create a uniform 2D grid of characters
Prerequisites:
A basic understanding of the
printffunction. Familiarity with
forloops in C.
Final Output:
If we choose a square size of 5, the output will appear as follows:
*****
*****
*****
*****
*****
Deconstructing the Pattern: The Logic
1. The Visual Representation
A solid square is a grid where the number of rows equals the number of columns
Rows: 5 (determined by the outer loop)
. Columns: 5 (determined by the inner loop)
.
2. Problem Statement
The objective is to print a specific symbol (such as *) in a grid format where both the height and the width are defined by a single input variable, n.
3. Pattern Analysis & Logic
Identifying the Rows: We use an outer loop to control the vertical height of the square, running from i = 1 to n.
Identifying the Columns: We use an inner loop to print the symbol horizontally in each row, running from j = 1 to n.
Algorithm:
Initialize the size $n$
. Start an outer loop for the rows
. Inside, start an inner loop for the columns
. Print the symbol inside the inner loop
. Print a newline character after the inner loop finishes to move to the next row
.
The Code Implementation
int main() {
int n = 5; // Size of the square
// Outer loop for the number of rows
for (int i = 1; i <= n; i++) {
// Inner loop for the number of columns
for (int j = 1; j <= n; j++) {
printf("*"); // Print the star symbol
}
// Move to the next line after each row
printf("\n");
}
return 0;
}
Explanation:
#include <stdio.h>: This line includes the standard library required for input and output operations. int n = 5;: We define the size of our square; you can change this value to adjust the grid size. for (int i = 1; i <= n; i++): The outer loop manages the rows; it ensures the code executes the print logic exactly $n$ times. printf("\n");: This statement is critical; it ensures that each row of stars begins on a new line, preventing the output from printing as a single long string.
Sample Output and Analysis
User Input:
The code is set for n = 5.
Program Output:
*****
*****
*****
*****
*****
Output Analysis:
The outer loop runs 5 times, and for every iteration, the inner loop also runs 5 times to print five stars, effectively creating a 5 \times 5 square
Complexity Analysis
Time Complexity: O(n^2), as the nested loops perform operations for each row and column
. Space Complexity: O(1), as the program uses a constant amount of memory regardless of the input size
.
Conclusion
You have successfully implemented a solid square pattern using nested loops. This simple yet powerful structure is the basis for all grid-based pattern programming
For all Pattern Programs list click here:
…till the next post, bye-bye & take care
No comments:
Post a Comment