Click here to Skip to main content
15,895,606 members
Please Sign up or sign in to vote.
3.50/5 (2 votes)
See more:
hello every Body ..

am a c++ beginner and i would like to know how can i draw a rectangle in C++

this is what i have tried so far but , there is nothing on the top and the bottom of my rectangle, please can any one help me get code to draw a rectangle, or a triangle in c++

this is ma code below
#include <iostream>
#include <string>

using namespace std;

 int main( void )
 { 
	 string spaces( 20, ' ' ); 

	 cout<< '#' << spaces << "#\n";
	 cout<< '#' << spaces << "#\n";
	 cout<< '#' << spaces << "#\n";
	 cout<< '#' << spaces << "#\n";
	 system("pause");
	 return 0;
 }
Posted
Updated 14-Mar-10 21:46pm
v2

1 solution

just define a string border(20,'#') and cout it before and after the sides:

C++
#include <iostream>
#include <string>
using namespace std;
 int main( void )
 {
     string border( 20, '#');
     string spaces( 20, ' ' );
     cout<< '#' << border << "#\n";
     cout<< '#' << spaces << "#\n";
     cout<< '#' << spaces << "#\n";
     cout<< '#' << spaces << "#\n";
     cout<< '#' << spaces << "#\n";
     cout<< '#' << border << "#\n";
     system("pause");
     return 0;
 }


But now try to understand this:

C++
#include <string>
#include <iostream>
int main()
{
    static const int WIDTH=18;
    static const int HEIGHT=8;

    std::string border(WIDTH-2,'#');
    std::string spaces(WIDTH-2,' ');
    std::cout << '#' << border << '#' << std::endl;
    for(unsigned int i=1; i<HEIGHT-1; ++i)
    {
        std::cout << '#' << spaces << '#' << std::endl;
    }
    std::cout << '#' << border << '#' << std::endl;

    system("pause");
    return 0;
}


Do you understand the use of constants and of the control structures ?!?
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900