Consider the following incomplete C program that calculates

Consider the following incomplete C program that calculates and prints the result of base raised to power of exponent. i.e.. base^exponent, where exponent greaterthanorequalto 0. In mathematical form (for simplicity, base = b. exponent = e). b^e = {1, if e = 0 b times b^e -1, if e greaterthanorequalto 1 Define function power 1 that implements b^e in the iterative approach. Using a suitable repetition structure, power 1 performs multiplication on b repeatedly, for e times. For example, power 1 (5, 3) returns the result of 5*5*5. i.e.. 125. (ii) Define the function power 2 that implements the recursive version of be. The recursive algorithm works as below. (b) Complete Table Q1 that compares recursive and iterative functions.

Solution

Code:

#include<stdio.h>
using namespace std;

int power1(int,int);
int power2(int,int);

int main()
{
   printf(\"5^3=%d\ \",power1(5,3));
   printf(\"5^3=%d\ \",power2(5,3));
   return 0;  
}

int power1(int b,int e)
{
   int i;
   int res=1;
   for(i=0;i<e;i++)
   {
       res*=b;
   }
   return res;
}


int power2(int b,int e)
{
   if(e==0)
   return 1;
   else
   return b*power2(b,e-1);
}

question iterative recursive
control strc used for loop recusion
rep achieved using for loop using recursice function
rep terminated by testing condition, counting the value of i by using base case e=0
cause of infinite loop improper implementation of condition not using proper base case
 Consider the following incomplete C program that calculates and prints the result of base raised to power of exponent. i.e.. base^exponent, where exponent grea

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site