C++ program to print a rectangle using star or any other character

C++ program to print a rectangle using star :

In this post, we will learn how to print a rectangle using star or using any other character. Our program will take the width and height of the rectangle and it will print the rectangle on console.

With this program, you will learn how to take user inputs, how to run loops and how to print on console in C++.

C++ program:

To print a rectangle, we need the height and width for the rectangle and we can print the rectangle based on these two values.

We need two nested loops for that. The outer loop will iterate to height amount of time and this is reponsible to point each row of the rectangle. The inner loop will iterate to print the stars for each row of the rectangle. We will also read the character from the user that we use to print the rectangle.

Below is the complete C++ program :

#include <iostream>
using namespace std;

int main()
{
    int height, width;
    char symbol;

    cout << "Enter the height of the rectangle : " << endl;
    cin >> height;

    cout << "Enter the width of the rectangle : " << endl;
    cin >> width;

    cout << "Enter the character to print the rectangle : " << endl;
    cin >> symbol;

    for (int i = 0; i < height; i++)
    {
        for (int j = 0; j < width; j++)
        {
            cout << symbol<< " ";
        }
        cout << endl;
    }
}

Explanation:

In this program,

  • height is a variable to store the height of the rectangle.
  • width is a variable to store the width of the rectangle.
  • symbol is a variable to store the symbol we need to print the variable.
  • We are using two for loops here. The outer loop, that is using i runs for height amount of time. On each iteration, it points to one row of the rectangle. The inner loop prints the whole row.
  • The inner loop prints the symbol. It runs for width number of times. Based on the user given symbol, it can print the rectangle differently.

Let’s check how it prints the output.

Sample output:

This program will print output as like below:

Enter the height of the rectangle : 
5
Enter the width of the rectangle : 
10
Enter the character to print the rectangle : 
*
* * * * * * * * * * 
* * * * * * * * * * 
* * * * * * * * * * 
* * * * * * * * * * 
* * * * * * * * * * 

Enter the height of the rectangle : 
10
Enter the width of the rectangle : 
5
Enter the character to print the rectangle : 
&
& & & & & 
& & & & & 
& & & & & 
& & & & & 
& & & & & 
& & & & & 
& & & & & 
& & & & & 
& & & & & 
& & & & & 

c plus plus print rectangle

As you can see, it can print a rectangle with any character that the user enters.

You might also like: