Midge
Midge

Reputation: 59

How to print a rectangle of asterisks in C++

I have been told to ask the user to input how many rows and columns for a rectangle they would like to print and in what symbol they want it. I am unaware as to how to do this and all my google searching only got me as far as printing one row. Directions dictate that the rows should be 3 and the columns should be 7 with the character '$'. I'm still a beginner so please go easy on me. This is what I have:

#include <iostream>
#include <iomanip>

using namespace std;

void PrintChar(int row = 5, int column = 10, char symbol = '*');

int main()
{
    int rows, columns;
    char symbol;

    cout << "How many rows and columns do you want, and with what symbol (default     is *) ?" << endl;
    cin >> rows >> columns >> symbol;

    PrintChar(rows, columns, symbol);

}

void PrintChar(int row, int column, char symbol)
{

    for (int y = 1; y <= column; y++)
    {
        cout << symbol;
}

That prints out a full line of the symbol and that's where my thinking stops. If you could help me with the final rows, that would be greatly appreciated.

Upvotes: 0

Views: 26088

Answers (4)

Pankaj Prakash
Pankaj Prakash

Reputation: 2428

Seems as a basic star patterns looping exercise. Use nested loops to print the required pattern

for(i=1; i<=n; i++)  
{  
    for(j=1; j<=m; j++)  
    {  
        cout<<"*";  
    }  
    cout<<"\n";  
}

Here n is the number of rows and m is number of columns each row.

Upvotes: 0

amald
amald

Reputation: 346

Using nested loop you can achieve that.

void PrintChar(int row, int column, char symbol)
{

    for (int x = 0; x < row; x++)
    {
       for (int y = 1; y <= column; y++)
       {
           cout << symbol;
       }
       cout << endl;
    }
}

Upvotes: 1

codedude
codedude

Reputation: 6549

This should do the trick. Added a newline to make it look like a rectangle.

#include <iostream>
#include <iomanip>

using namespace std;

void PrintChar(int row = 5, int column = 10, char symbol = '*');

int main() {

    int rows, columns;
    char symbol;

    cout << "How many rows and columns do you want, and with what symbol (default     is *) ?" << endl;
    cin >> rows >> columns >> symbol;

    PrintChar(rows, columns, symbol);

    return(0);

}

void PrintChar(int row, int column, char symbol) {
    for (int y = 1; y <= column; y++) {
        for (int x = 1; x <= row; x++) {
            cout << symbol;
        }
        cout << endl;
    }
}

Upvotes: 2

Siddhartha Ghosh
Siddhartha Ghosh

Reputation: 3198

  • First, int main() should have a return statement.

  • There should be 2 nested for loops inside PrintChar, outer one for the rows and inner one for the columns, like:-

    for (int x = 1; x <= rows; x++) { cout << endl; for (int y = 1; y <= columns; y++) { cout << symbol; } }

Upvotes: 2

Related Questions