Write a program to print the palindrome pyramid pattern.
Example:
Input: n = 4
Output:
1 1 2 1 1 2 3 2 1 1 2 3 4 3 2 1
Approach 1: Palindrome Half Pyramid Pattern
C++
#include <bits/stdc++.h>using namespace std;void printPattern(int n){for (int i = 1; i <= n; i++){for (int j = 1; j <= i; j++){cout << j << " ";}for (int j = i - 1; j >= 1; j--){cout << j << " ";}cout << "\n";}}int main(){int n = 4;printPattern(n);return 0;}
Example:
Input: n = 4
Output:
1 1 2 1 1 2 3 2 1 1 2 3 4 3 2 1
Approach 2: Palindrome Full Pyramid Pattern
C++
#include <bits/stdc++.h>using namespace std;void printPattern(int n){for (int i = 1; i <= n; i++){for (int j = 1; j <= n - i; j++)cout << " ";int j = 1, k = 2 * i - 1;while (j <= 2 * i - 1){if (j <= k){cout << j << " ";}else{cout << k << " ";}j++;k--;}cout << "\n";}}int main(){int n = 4;printPattern(n);return 0;}
No comments:
Post a Comment