Serge V.
Serge V.

Reputation: 3623

draw border using for loop

I'm trying to make a simple border using for loop. I don't get a proper result. Specifically, my right border is not shown. Please help.

const int width = 20;
const int height = 20;

void Drow() 
{
    system("cls");                      // clear the screan
    for (int i = 0; i < width; ++i) 
    {
        cout << "*";                    // upper border
    }       

    for (int i = 0; i < height-2; i++) 
    {
        for (int j = 0; j < width; j++) 
        {
            if (j == 0 || j == width - 1)
            {
                cout << "*";            // left and right borders
            }
        }
        cout << endl;
    }

    for (int i = 0; i < width; i++)     // lower border
        cout << "*";
}

Upvotes: 0

Views: 2135

Answers (2)

Jerry Coffin
Jerry Coffin

Reputation: 490408

Unless I were feeling seriously masochistic, I'd do the job a bit differently.

My immediate reaction would be to write code more on this general order:

std::string h_border = std::string(width, '*' ) + "\n";
std::string v_border = "*" + std::string(width - 2,  ' ') +"*\n";

std::cout << h_border;
for (int i = 0; i < height - 2; i++)
    std::cout << v_border;
std::cout << h_border;

Upvotes: 1

coyotte508
coyotte508

Reputation: 9725

In your second loop, you draw the borders but you forgot to draw the inside of your rectangle.

Add this to the if:

else {
    cout << " ";
}

As πάντα ῥεῖ pointed out, you also forgot to use endl after the firt and last loops.

Live Demo

Upvotes: 3

Related Questions