C Program to Print a Solid Rectangle Pattern

1. Introduction

A solid rectangle pattern is one of the simplest patterns to create in C programming. It involves printing a series of characters (usually asterisks) to form a rectangle. This type of pattern is a great exercise for understanding nested loops in C.

2. Program Steps

1. Ask the user to input the number of rows and columns for the rectangle.

2. Use a nested loop where the outer loop represents the rows and the inner loop represents the columns.

3. Print an asterisk for each position in the rectangle.

3. Code Program

#include <stdio.h>

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

    // Prompting for user input
    printf("Enter the number of rows: ");
    scanf("%d", &rows);
    printf("Enter the number of columns: ");
    scanf("%d", &columns);

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

    return 0;
}

Output:

Enter the number of rows: 4
Enter the number of columns: 5
*****
*****
*****
*****

Explanation:

1. The program starts by including the stdio.h header file, which is necessary for input and output operations.

2. In the main function, four integer variables rows, columns, i, and j are declared. rows and columns will store the user input for the dimensions of the rectangle, while i and j are used as loop counters.

3. The user is prompted to enter the number of rows and columns for the rectangle, and these values are read from the standard input using scanf.

4. A nested loop structure is used to print the rectangle pattern. The outer loop (i) iterates for each row, and the inner loop (j) iterates for each column in a row.

5. Inside the inner loop, an asterisk (*) is printed for each column of the current row. This loop continues until all columns for the current row are printed.

6. After printing all columns of a row, the printf("\n") statement is executed to move to the next line, starting the process for the next row.

7. This process repeats until all rows have been printed, resulting in a solid rectangle of asterisks.

8. The program ends with return 0;, signaling successful execution.


Comments