Answer to Question #307961 in C++ for Mike

Question #307961

How can I write a square pattern with a triangle insideg

and the pattern size will change according to user input


If the input integer is 0, negative or an even number, then the program will print nothing. 


Example:

Input: 9
*********
**     **
* *   * *
*  * *  *
*   *   *
*       *
*       *
*       *
*********

Input: 5
*****
** **
* * *
*   *
*****

Input: 1
*

Input: 4 
1
Expert's answer
2022-03-08T16:03:30-0500
#include <iostream>
using namespace std;


int main() {
    int n;


    cout << "Input: ";
    cin >> n;


    if (n <= 0) {
        return 0;
    }
    if (n == 1) {
        cout << "*" << endl;
        return 0;
    }

    // First line
    for (int i=0; i<n; i++) {
        cout << "*";
    }
    cout << endl;

    for (int j=1; j<(n+1)/2; j++) {
        cout << "*";
        for (int i=0; i<j-1; i++) {
            cout << " ";
        }
        cout << "*";
        int n2 = n - 4 - 2*(j-1);
        for (int i=0; i<n2; i++) {
                cout << " ";
        }
        if (n2 >= 0) {
            cout << "*";
        }
        for (int i=0; i<j-1; i++) {
            cout << " ";
        }
        cout << "*";
        cout << endl;
    }

    for (int j=(n+1)/2; j<n-1; j++) {
        cout << "*";
        for (int i=0; i<n-2; i++) {
            cout << " ";
        }
        cout << "*";
        cout << endl;
    }

    for (int i=0; i<n; i++) {
        cout << "*";
    }
    cout << endl;

    return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog