Hi Viewers, I am going to write a simple C program to draw a Rectangle shape based on user input. I am going to use the ASCII characters to print the Rectangle.
Let’s see the code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
#include <stdio.h> void drawRectangle(int width, int height) { int i, j; for (i = 0; i < height; i++) { for (j = 0; j < width; j++) { if (i == 0 || i == height - 1 || j == 0 || j == width - 1) { printf("*"); } else { printf(" "); } } printf("\n"); } } int main() { int width, height; printf("Enter the width of the rectangle: "); scanf("%d", &width); printf("Enter the height of the rectangle: "); scanf("%d", &height); drawRectangle(width, height); return 0; } |
In the above program, the drawRectangle
function takes the width
and height
of the rectangle as parameters. It uses nested loops to iterate through each row and column of the rectangle and prints either an asterisk (*) for the boundary or a space for the interior.
In the main
function, the user is prompted to enter the width and height of the rectangle, which are then passed to the drawRectangle
function. The function is called with the provided dimensions, and the rectangle is drawn on the console.
Output:
1 2 3 4 5 6 7 8 9 10 11 |
Enter the width of the rectangle: 10 Enter the height of the rectangle: 5 ********** * * * * * * ********** -------------------------------- Process exited after 2.548 seconds with return value 0 Press any key to continue . . . |
This C program is beneficial for College / School kids to learn the C language. I hope this helped you the same.