In: Computer Science
C++
recursive function that draws the following shape.
X
XXX
XXXXX
XXXXXXX
XXXXXXXXX
XXXXXXXXX
XXXXXXX
XXXXX
XXX
X
The length of the longest row in the shape and the shape's character are function parameters.
In above shape the longest row is 9 and the pattern's character is "X".
Recurisive Function : This is a function that gets called during the execution. The process of this repeation takes several times during the execution. Once all the process is finished then only we will be getting the output.
PROGRAM SPECIFICATIONS:
In the implemention of the code I have provided some space after X its because for easy counting of the letter as it is mentioned the longest row is "9".It will become the output look more good enough also. Since I the question it is mentioned the code should be in C++. I have meet that criteria also.
PROGRAM CODE ;
#include <iostream>
using namespace std;
//Half pyramid recusion
//This function is for printing the half pyramid of X
void printn(int num)
{
//inital condition
if (num == 0)
return;
cout << "X ";
printn(num - 1 );
}
void pattern(int n, int i)
{
if (n == 0)
return;
//checking the condition using if loop
if(i%2!=0)
{
printn(i);
}
cout<<endl;
pattern(n - 1 , i+1);
}
/* Here we are doing the inversion of the pyramid */
void printPatternInverted(int n, int i)
{
// intial condition
if (n < 1)
return;
// to print the pattern of a particular row
if (i <= n && n%2!=0)
{
cout << "X ";
// recursively print rest of the stars
// of the row
printPatternInverted(n, i + 1);
}
else
{
cout<<endl;
// print the pattern of the remaining rows recursively
printPatternInverted(n-1, 1);
}
}
//main function begins here....
int main()
{
//declaration of variables
int n = 9;
//calling the recurison function
pattern(n , 1);
printPatternInverted(n, 1);
return 0;
}
PROGRAM SCREENSHOT :
I have done this program using online GDB complier and attaching the screenshot of input and output.
INPUT SCREENSHOT
OUTPUT SCREENSHOT