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
#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;
}
Comments
Leave a comment