Monday, May 24, 2010

Drawing fractals using C++ and recursion?

similar to:


*


**


.*


****


. *


. **


. *


********


. *


. **


. *


. ****


. *


. **


. *


(don't need the periods)


Create a recursive function to draw a fractal 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:


void pattern(int nstars, int startcol);





Where nstars is the maximum number of stars to draw essentially the width), and startcol is the column in which to begin drawing stars. Note that the number of stars should always be a power of 2. To help you see the recursive nature of the pattern, consider the pattern produced by pattern(8,0).





i know that it needs a loop in it. Something like:


// A loop to print exactly i spaces:


for(int k = 0; k %26lt; i; k++){


cout %26lt;%26lt; " ";


}


// A loop to print n asterisks, each followed by a space:


for(int k = 0; k %26lt; n; k++){


cout %26lt;%26lt; "* ";


}





I am completely lost on this. How would i do this in C++? Any help would be greatly appreciated!

Drawing fractals using C++ and recursion?
Your function should be





void pattern (int nstars, int startcol)


{


if(nstars != 0)


{


-- loop thru and go to the right column


-- get the random number


-- print as many astrixes as the random number





// recusive call


pattern (nstars - random, startcol);


}





}








--------------------------------------...





for(int i = 0; i%26lt;= startcol; i++)


{


cout%26lt;%26lt;" "; //This will move the cursor to the right column


}





for(int j = 0; j%26lt;= randomNum; j++)


{


count"*";//Print the asterix


}





cout%26lt;%26lt;endl; //This will move the cursor to the next line and get it ready for the next iteration.





What I don't understand is the number of lines you have don't make sense. you said the image showed 8 stars, but the example you have has more than 8 asterisks.





--------------------------------------...





oh ok, I understand now, you have a total of 32 stars and you need to distribute the stars in such a way that no one row will have more than 8 stars.





Thats easy, stick with the code you have written above, you have to select a random number for each row so that you get the number of stars for the row. the random number needs to be between 1 and whatever nstars is. also your recursive function needs to send the total number of stars also. Its based on this that you will perform your recursion





void pattern(int totStars, int nStars, int startCol)


{


if (totStars != 0) // Condition to stop recursion


{


//for loop to get to the right start column


// get random number between 1 and nStars


// for loop to print total number of asterisks


// remember to go to next line


pattern(totStars - randomNum, nStars, startCol) //recursive function call.


}


}

hibiscus

No comments:

Post a Comment