Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

detail Answer only In this lab, you will implement a recursive function to the f

ID: 3546412 • Letter: D

Question


detail Answer only

In this lab, you will implement a recursive function to the following stat pattern and a driver program to test your function. Note that there is a space after each star. Your function prototype should look like this void pattern (unsigned int n, unsigned int i): // precondition: n is a positive number and it is a power of 2 // postcondition: a pattern based on the above example has been printed to the screen. //The longest line of the pattern has a starts beginning in column i of the output. // For example, the above pattern is produced by the call - pattern(8, 0) Your tasks: - implement recrsive pattern() function - write a driver program to test pattern () function. Your driver program should repeatedly ask user to input n and i --the two parameters that pattern() takes, call pattern() to print out the star pattern, until the user enter (-1, -1) for (n, i).

Explanation / Answer

Added a function to check if n was a power of two. Not sure if that was what was wanted or not but the idea on how to draw the pattern is there for you to use.


   #include<iostream>
    using namespace std;
    void recursivepattern(unsigned int n, unsigned int i)
    {
    if(n==1)
    {
    for(int j=0;j<i;j++)
    cout<<" ";
    cout<<"*";
    }
    else
    {
    recursivepattern(n/2,i);
    cout<<endl;
    for(int k=0;k<i;k++)
    cout<<" ";
    for(int p=0;p<n;p++)
    cout<<"* ";
    cout<<endl;
    recursivepattern(n/2,i+n);
    }
    }
    bool powerOfTwo(int n)
    {
         if(n == 0)
         return false;
         while(n % 2 == 0){
                 n = n/2;
         }
         if(n > 1)
         return false;
         return true;
    }
    int main()
    {
    int n,i;
    while(1){
    cout << " Enter n and i (-1 -1 to exit): ";
    cin >> n >> i;
    if( n == -1 && i == -1){
        cout << "Exiting program... ";
        return 1;
    }
    if( n < 0 || i < 0 || !powerOfTwo(n)){
        cout << "Improper input, please try again." << endl;
        continue;
    }
    recursivepattern(n,i);
    }
   
    }