For input n=5
ABCDEDCBA
ABCD DCBA
ABC CBA
AB BA
A A
Using an array to print this pattern eliminates the need to use if statements and nested for loops. We create an array with all the alphabets from the first row and keep two markers – left and right which converts alphabets into blank spaces each row
#include<iostream> using namespace std; int main() { int n,i; cout<<"Enter number of lines : "; cin>>n; int size = 2*n; //Array size; char a[size],ch='A'; for(i=0;i<n;i++) //Fill up array with the alphabets of first row a[i] = a[size-2-i] = ch++; a[size-1] = '\0'; int left=n-1,right=n-1; // These track the alphabets to be converted into spaces each row for(i=1;i<=n;i++) { cout<<a<<endl; a[left--] = a[right++] = ' '; } }
Leave a Reply