Happy to be here again, Recently I was given a Pattern Problem to solve by my friend, who attended an interview where they were asked to Write its solution.
So it goes like this-
Instructions :
Time Duration is 60 Minutes.
The Pattern must be dynamic, it should work for any odd number (Excluding 1 and any Negative number).
It should not run for even numbers.

If User input is 3 (N=3)

If user input is 5 (N=5)

Show Solution Code
#include <iostream> using namespace std; void printSpace(int n) { for (int i = 0; i < n; i++) { cout << " "; } } bool isOdd(int n) { return n % 2 != 0; } int countOdd(int n) { int i = 2, count = 1; if (n <= 1) { return 1; } while (i++ != n) { if (i % 2 != 0) { count++; } } return count; } void PH(int n, int tc) { int k = 0; for (int r = 1; r <= tc; r++, k = 0) { printSpace(tc + (n + 2)); printSpace(tc - r); while (k != 2 * r - 1) { cout << "@"; ++k; } cout << endl; } for (int r = 1; r <= tc; r++, k = 0) { printSpace(tc + (n + 2)); cout << "*"; cout << endl; } } void PV(int n, int tc) { int k = 0; for (int r = 1; r <= n / 2; r++, k = 0) { printSpace(tc - r); for (int i = 1; i <= r; i++) cout << "@"; printSpace(n + 2); cout << "*"; cout << "\n"; } // lower half for (int r = (n / 2) + 1; r >= 1; r--) { printSpace(((n / 2) + 1) - r); for (int j = r; j <= 2 * r - 1; ++j) cout << "@"; if (r == (n / 2) + 1) { for (int i = 0; i < n + 3; i++) cout << "*"; } cout << endl; } } int main() { int N; cout << "Enter value: "; cin >> N; if (!isOdd(N)) { cout << "\nPlease enter a Odd Number"; return 1; } int total_cols = countOdd(N); PH(N, total_cols); PV(N, total_cols); return 0; }
Well, Of course, the Code can be optimized, so play with it.
