C++ Program to Draw Rectangle Using For Loop

In this post, we will learn to code the C++ Program to Draw Rectangle Using For Loop. Let’s understand about for loops and “How to Draw Rectangle Using For Loop”

In this Program, we will take the width and height of the Rectangle from the user as an input and then Display the Rectangle.

Let’s see the C++ Program to Draw Rectangle Using For Loop.

C++ Program to Draw Rectangle Using For Loop

    #include <iostream>
    using namespace std;
     
    void draw_rectangle(int height, int width){
     
    	for(int i=0; i<height; i++){
    		for(int j=0; j<width; j++){
    			cout << "* ";
    		}
    		cout << endl;
    	}
     
    }
     
    int main() {
     
    	int height, width;
    	cout << "Enter the Height of rectangle: \n";
    	cin >> height;
    	
    	cout << "Enter the Width of rectangle: \n";
    	cin >> width;
    	
    	draw_rectangle(height,width);
     
    	return 0;
    }

Output

Enter the Height of rectangle: 5

Enter the Width of rectangle: 6

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

How Does This Program Work ?

    	int height, width;
    	cout << "Enter the Height of rectangle: \n";
    	cin >> height;
    	
    	cout << "Enter the Width of rectangle: \n";
    	cin >> width;

In this program, we have declared the height and width variable of int datatype. Then, we have taken the input of the Height and width using cin >> height and cin >> width;

    void draw_rectangle(int height, int width){
     
    	for(int i=0; i<height; i++){
    		for(int j=0; j<width; j++){
    			cout << "* ";
    		}
    		cout << endl;
    	}
     
    }

We have created a function named draw_rectangle(int height, int width) we have passed the function with height and width which draws a rectangle of the width and height given.

draw_rectangle(height,width);

Then we called the function in the main function which displays the rectangle of the given height and width. This is the C++ Program to Draw Rectangle Using For Loop.

Read More: C Program to Draw Rectangle Using for Loop

Conclusion

I hope after going through this post, you understand C++ Program to Draw Rectangle Using For Loop. If you have any doubt regarding the program, then contact us in the comment section. We will be delighted to assist you.

Also Read:

Leave a Comment

Your email address will not be published.