Question

In: Computer Science

Recursion and Iteration in C++ Locate the TODO comments in the hw02.h file. These comments provide...

Recursion and Iteration in C++

Locate the TODO comments in the hw02.h file. These comments provide direction on what needs to be done.

// hw02.h

#ifndef CSC232_HW02_H
#define CSC232_HW02_H

// TODO: All pre-conditions must be validated using the assert function imported from the following library.
// TODO: You are not allowed to use the pow function in this assignment!
#include <cassert>

#ifndef FALSE
#define FALSE 0
#endif

#ifndef TRUE
#define TRUE !FALSE
#endif

#define USE_MAIN_INPUT_FILE FALSE
#define USE_DEMO_INPUT_FILE FALSE
#define USE_TEST_INPUT_FILE FALSE

/**
 * Custom namespace for our work in CSC232.
 */
namespace csc232
{
    using integer_t = int;
    using real_t = double;

    /**
     * An iterative function used to compute x^n for some n >= 0.
     *
     * @param x a real number whose nth power is computed
     * @param n the power used in calculating x^n
     * @return x^n for n >= 0 is returned.
     * @pre n >= 0.
     * @post Power1(x, n) > 0 if n >= 0.
     */
    real_t Power1(real_t x, integer_t n)
    {
        // TODO: Implement me iteratively, i.e., without using recursion.
        return 0;
    }

    /**
     * A recursive function used to compute x^n for some n >= 0 using the following
     * recursive formulation:
     *
     * @code{.cpp}
     * x^0 = 1
     * x^n = x * x^(n - 1) if n > 0
     * @endcode
     *
     * @param x a real number whose nth power is computed
     * @param n the power used in calculating x^n
     * @return x^n for n >= 0 is returned.
     * @pre n >= 0.
     * @post Power2(x, n) > 0 if n >= 0.
     */
    real_t Power2(real_t x, integer_t n)
    {
        // TODO: Implement me using the given recursive formulation.
        return 0;
    }

    /**
     * Determines the evenness of a number.
     *
     * @param n the number under interrogation
     * @return True is returned if the given number is even, false otherwise.
     */
    bool isEven(integer_t n)
    {
        // TODO: Implement me correctly; I should be used in Power3.
        return false;
    }

    /**
     * A recursive function used to compute x^n for some n >= 0 using the following
     * recursive formulation:
     *
     * @code{.cpp}
     * x^0 = 1
     * x^n = (x^(n/2))^2 if n > 0 and n is even
     * x^n = x * (x^(n/2))^2 if n > 0 and n is odd
     * @endcode
     *
     * @param x a real number whose nth power is computed
     * @param n the power used in calculating x^n
     * @return x^n for n >= 0 is returned.
     * @pre n >= 0.
     * @post Power3(x, n) > 0 if n >= 0.
     */
    real_t Power3(real_t x, integer_t n)
    {
        // TODO: Implement me using the given recursive formulation.
        return 0;
    }
}

#endif //CSC232_HW02_H

Solutions

Expert Solution

// hw02.h

#ifndef CSC232_HW02_H
#define CSC232_HW02_H

// TODO: All pre-conditions must be validated using the assert function imported from the following library.
// TODO: You are not allowed to use the pow function in this assignment!
#include <cassert>

#ifndef FALSE
#define FALSE 0
#endif

#ifndef TRUE
#define TRUE !FALSE
#endif

#define USE_MAIN_INPUT_FILE FALSE
#define USE_DEMO_INPUT_FILE FALSE
#define USE_TEST_INPUT_FILE FALSE

/**
 * Custom namespace for our work in CSC232.
 */
namespace csc232
{
    using integer_t = int;
    using real_t = double;

    /**
     * An iterative function used to compute x^n for some n >= 0.
     *
     * @param x a real number whose nth power is computed
     * @param n the power used in calculating x^n
     * @return x^n for n >= 0 is returned.
     * @pre n >= 0.
     * @post Power1(x, n) > 0 if n >= 0.
     */
    real_t Power1(real_t x, integer_t n)
    {
        // TODO: Implement me iteratively, i.e., without using recursion.
        assert(n >= 0);
        real_t ans = 1.0;
        while(n){
            if(n & 1){
                ans *= x;
            }
            x = x*x;
            n>>=1;
        }

        return ans;
    }

    /**
     * A recursive function used to compute x^n for some n >= 0 using the following
     * recursive formulation:
     *
     * @code{.cpp}
     * x^0 = 1
     * x^n = x * x^(n - 1) if n > 0
     * @endcode
     *
     * @param x a real number whose nth power is computed
     * @param n the power used in calculating x^n
     * @return x^n for n >= 0 is returned.
     * @pre n >= 0.
     * @post Power2(x, n) > 0 if n >= 0.
     */
    real_t Power2(real_t x, integer_t n)
    {
        assert(n >= 0);
        // TODO: Implement me using the given recursive formulation.
        if( n == 0 )return 1;
        return x*Power2(x,n-1);
    }

    /**
     * Determines the evenness of a number.
     *
     * @param n the number under interrogation
     * @return True is returned if the given number is even, false otherwise.
     */
    bool isEven(integer_t n)
    {
        // TODO: Implement me correctly; I should be used in Power3.
        return n&1 ? false: true;
    }

    /**
     * A recursive function used to compute x^n for some n >= 0 using the following
     * recursive formulation:
     *
     * @code{.cpp}
     * x^0 = 1
     * x^n = (x^(n/2))^2 if n > 0 and n is even
     * x^n = x * (x^(n/2))^2 if n > 0 and n is odd
     * @endcode
     *
     * @param x a real number whose nth power is computed
     * @param n the power used in calculating x^n
     * @return x^n for n >= 0 is returned.
     * @pre n >= 0.
     * @post Power3(x, n) > 0 if n >= 0.
     */
    real_t Power3(real_t x, integer_t n)
    {
        assert(n >= 0);
        // TODO: Implement me using the given recursive formulation.
        if( n == 0 ){
            return 1;
        }
        if(n % 2 == 0){   // n is even
            real_t temp = Power2(x,n/2);
            return temp*temp;
        }
        else{             // n is odd
            real_t temp = Power2(x,n/2);
            return x*temp*temp;
        }
    }
}

#endif //CSC232_HW02_H

Related Solutions

Describe the similarities between using recursion versus iteration. Describe the difference between using recursion versus iteration.
Describe the similarities between using recursion versus iteration. Describe the difference between using recursion versus iteration.
C++ Recursion, Change the delete_node function in the header file to a recursive delete_node function, main...
C++ Recursion, Change the delete_node function in the header file to a recursive delete_node function, main is already set. Hint: It might be helpful to modify the function so that it uses a separate recursive function to perform whatever processing is needed. //////////////////////////////////////////////////////////////header.h////////////////////////////////////////////////////////////////////////////////////////////// #ifndef HEADER_H_ #define HEADER_H_ #include <iostream> using namespace std; template <class T> class LL { private:    struct LLnode    {        LLnode* fwdPtr;        T theData;    };    LLnode* head; public:    LL();...
This function uses a curious mix of iteration and recursion: function F(n) if n < 1...
This function uses a curious mix of iteration and recursion: function F(n) if n < 1 return 1 t <- 0 for i <- 0 to n for j <- i to n t <- t + j return t + F(n-1) What is the number of basic operations (additions and subtractions) performed? Answer: Θ(n³) Could you tell me how I can solve this problem??
Suppose coke (c) and hamburgers (h) provide a consumer utility of U(c,h)= (c∗h)^1/2 (a) If coke...
Suppose coke (c) and hamburgers (h) provide a consumer utility of U(c,h)= (c∗h)^1/2 (a) If coke costs 1 TL and hamburger costs 25 TL, how should this consumer spend 100 TL that his mother gives him to maximize his utility? (b) Suppose government wants to discourage coke consumption by taxing coke by 3 TL. From the point of consumer is it better to tax coke or to tax income?
Rewrite your program for finding Pascal's Triangle to use iteration (loops) instead of recursion. Include in...
Rewrite your program for finding Pascal's Triangle to use iteration (loops) instead of recursion. Include in both algorithms code to keep track of the total time used to run the algorithms in milliseconds. Run these algorithms for n = 10, n = 20, and n = 30. Print out both the original output and the time to run for both algorithms. Please make sure you comment your code thoroughly. The code should be nicely formatted and should use proper variables.
Replace the todo comments with the right code. //Create variables to use later const int TRIG_PIN...
Replace the todo comments with the right code. //Create variables to use later const int TRIG_PIN = 9; const int ECHO_PIN = 10; const int RED_PIN = 3; const int GREEN_PIN = 5; const int BLUE_PIN = 6; float duration, distance_in_cm, distance_in_feet; void setup() { //Setup pins for correct I/O pinMode(TRIG_PIN, OUTPUT); pinMode(ECHO_PIN, INPUT); pinMode(RED_PIN, OUTPUT); pinMode(GREEN_PIN, OUTPUT); pinMode(BLUE_PIN, OUTPUT); } void loop() { //Generate the ultrasonic waves digitalWrite(TRIG_PIN, LOW); delayMicroseconds(2); digitalWrite(TRIG_PIN, HIGH); delayMicroseconds(10); digitalWrite(TRIG_PIN, LOW); //Read in the echoed...
This class should include .cpp file, .h file and driver.cpp (using the language c++)! Overview of...
This class should include .cpp file, .h file and driver.cpp (using the language c++)! Overview of complex Class The complex class presents the complex number X+Yi, where X and Y are real numbers and i^2 is -1. Typically, X is called a real part and Y is an imaginary part of the complex number. For instance, complex(4.0, 3.0) means 4.0+3.0i. The complex class you will design should have the following features. Constructor Only one constructor with default value for Real...
IN C# WITH SCREENSHOTS OF THE CODE RECURSION Objectives • Learn the basics of recursion. Background...
IN C# WITH SCREENSHOTS OF THE CODE RECURSION Objectives • Learn the basics of recursion. Background There are many problems that loops simplify, such as displaying every pixel to a screen or receiving repetitive input. However, some situations that can be simplified with looping are not easily solvable using loops. This includes problems that require back tracking and being able to use information from previous iterations, which would normally be lost when using an iterative loop. In those cases, it...
Would you make separated this code by one .h file and two .c file? **********code************* #include...
Would you make separated this code by one .h file and two .c file? **********code************* #include <stdlib.h> #include <stdbool.h> #include <stdio.h> #include<time.h> // Prints out the rules of the game of "craps". void print_game_rule(void) { printf("Rules of the game of CRAPS\n"); printf("--------------------------\n"); printf("A player rolls two dice.Each die has six faces.\n"); printf("These faces contain 1, 2, 3, 4, 5, and 6 spots.\n"); printf("After the dice have come to rest, the sum of the spots\n on the two upward faces is...
PLESE CODE IN C# not java RECURSION Objectives • Learn the basics of recursion – Part...
PLESE CODE IN C# not java RECURSION Objectives • Learn the basics of recursion – Part II (last week was Part I) Submission Guidelines: You will turn in 2 program files (one for each lab problem) Tasks This lab has two parts: Write a driver program that calls this method from the Main program. • • Write a driver program that calls this method from the Main program. Note: Your program name should match the name of your java /...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT