Create a recursive function to draw this pattern, given a maximum number of star
ID: 3555110 • Letter: C
Question
Create a recursive function to draw this pattern, given a maximum number of stars (which should be a power of 2) and a column on which to begin drawing stars. The prototype for the function should look like:
Where nstars is the maximum number of stars to draw (essentially the width), and startcol is the column in which to begin drawing stars. The pattern shown above was generated by callingpattern(16,0). Note that the number of stars should always be a power of 2, but you aren't required to check for this in your function. To help you see the recursive nature of the pattern, consider the pattern produced by pattern(8,0):
Fractal star pattern 8 columns wide
With recursive thinking, the function needs only eight or nine lines of code (not counting comments). PLEASE INCLUDE COMMENTS SO I WILL KNOW WHAT IS GOING ON....
Your main function need only act as a driver to call the pattern function once. Set up a constant to hold the desired number of stars (should be set to 16 when you turn in your program). The call from main should start printing in column 0.
Explanation / Answer
#include <stdlib.h>
#include <iostream>
using namespace std;
void pattern(int nstars, int startcol){
/* where we stop */
if (nstars==1) {
for(int k = 0; k < startcol; k++){
cout << " ";
}
cout << "* ";
cout << endl;
return;
}
/* draw upper part ot the star */
pattern(nstars/2, startcol);
/* draw line */
for(int k = 0; k < startcol; k++){
cout << " ";
}
for(int k = 0; k < nstars; k++){
cout << "* ";
}
cout << endl;
/* draw lower part */
pattern(nstars/2, startcol+nstars);
}
int main(int argc, char** argv) {
pattern(16,0);
return (EXIT_SUCCESS);
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.