ann_txg
ann_txg

Reputation: 11

Output of the shape

How can I improve code that would output this fixed-size shape to the console?

Shape:

#....
.#...
#.#..
.#.#.
#.#.#
.#.#.
#.#..
.#...
#....

I wrote the code, but it seems to me incorrect. Although he copes with this task. I want to combine all the elifs into an if, which is spelled out at the beginning. I think there is some kind of dependency between 10, 8, 6, 4 that will allow me to do this. I can't find this dependency to improve the code.

#include <iostream>
using namespace std;

int main() {
    for (int x = 1; x < 10; x++) {
        for (int y = 1; y < 6; y++) {
            if ((x == y) or (x == (10 - y))) cout << "#";
            else if ((x == (8 - y)) and (x > y)) cout << "#";
            else if ((x == (6 - y)) and (x > y)) cout << "#";
            else if ((x == (4 - y)) and (x > y)) cout << "#";
            else cout << ".";
        }
        cout << endl;
    }
    return 0;
}

Upvotes: 0

Views: 140

Answers (1)

fana
fana

Reputation: 1870

Employing a string "#.#.#....", all you have to do for each line is decide which part of this string to display.

#include <cmath>
#include <iostream>
#include <string>

int main() {
    const std::string S = "#.#.#....";
    for (int row = 0; row < 9; ++row) {
        std::cout << S.substr(std::abs(row - 4), 5) << '\n';
    }
}

Upvotes: 2

Related Questions