user1467995
user1467995

Reputation: 17

How to draw a rectangle for c++ with loops?

So i have this code which makes a box, but want to make the corners +, the lengths |, and the widths - . Also want to input a number so you can draw them like cout<<"enter the length number" etc... how would i do that?

Here is what i have to make a box:

#include <iostream.h> 
#include <string.h> 

void main() 
{ 
  for(int z=1; z<=79; z++) 
  { 
    cout << ""; 
  } 

  cout << endl; 

  for(int i=1; i<=5; i++) 
  { 
    cout << ""; 
    for(int j=1; j<=77; j++) 
    { 
      cout << " "; 
    } 

    cout << "" << endl; 
  } 

  for(int y=1; y<=79; y++) 
  { 
    cout << ""; 
  } 

  cout << endl; 
}

Upvotes: 1

Views: 36294

Answers (2)

Firefox_
Firefox_

Reputation: 1

#include <iostream>
using namespace std;

void draw_rect( int width, int height)
{   
int i;  
cout << char(218); 
for (i=0; i<width-2; i++) 
cout << char(196);
cout << char(191) << endl;

for (i=0; i<height-2; i++)
{
cout << char(179);
for (int j=0; j<width-2; j++) 
cout << " ";
cout << char(179) << endl;
}
cout << char(192);

for(i=0; i<width-2; i++)
cout << char(196);
cout << char(217) << endl;
}

int main()
{
draw_rect(20,10);
return 0;
}

Upvotes: 0

Mantas Norvaiša
Mantas Norvaiša

Reputation: 101

Draws a rectangle where int height is the height and int width is the width

#include <iostream>

void draw_rect(int width,int height) 
{
    using std::cout;
    cout << "+";
    for (int i = 0; i < width - 2; i++)
    {
        cout << "-";
    }
    cout << "+\n";

    for (int i = 0; i < height - 2; i++)
    {
        cout << "|";
        for (int j = 0; j < width - 2; j++)
        {
            cout << " ";
        }
        cout << "|\n";
    }

    cout << "+";
    for (int i = 0; i < width - 2; i++)
    {
        cout << "-";
    }
    cout << "+\n";
}

int main ()
{
    draw_rect(8,6);
    return 0;
}

And for how to get user input read this: Basic C++ IO

Upvotes: 2

Related Questions