Write a program to compute a^n (a power n) using recursion. INPUT & OUTPUT FORMAT: Input consists of 2 integers Refer sample input and output for formatting specifications SAMPLE INPUT & OUTPUT: Enter the value of a 2 Enter the value of n 8 The value of 2 power 8 is 256
Answers
Answer:
Explanation:
#include<iostream>
using namespace std;
int power(int x,int y)
{
if(y!=0)
return (x*power(x,y-1));
else
{
return 1;
}
}
int main()
{
int a,b;
cin>>a>>b;
cout<<"Enter the value of a"<<"\n"<<"Enter the value of n"<<"\n";
cout<<"The value of "<<a << " power "<<b <<" is "<<power(a,b);
}
Answer:
1. Program in C programming language
#include <stdio.h>
long power (int, int);
int main()
{
int pow, a;
long result;
printf("Enter the value of a : ");
scanf("%d", &a);
printf("Enter the value of n : ");
scanf("%d", &pow);
result = power(a, pow);
printf("The value of %d power %d is %ld", a, pow, result);
return 0;
}
long power (int a, int pow)
{
if (pow)
{
return (a * power(a, pow - 1));
}
return 1;
}
2. Program in C++ programming language
#include <iostream>
using namespace std;
int calculatePower(int, int);
int main()
{
int a, powerRaised, result;
cout << "Enter the value of a : ";
cin >> a;
cout << "Enter the value of n : ";
cin >> powerRaised;
result = calculatePower(a, powerRaised);
cout << "The value of " << a << " power " << powerRaised << " is " <<result;
return 0;
}
int calculatePower(int a, int powerRaised)
{
if (powerRaised != 0)
return (a*calculatePower(a, powerRaised-1));
else
return 1;
}
3. Program in Java programming language
import java.util.*;
class Main
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter the value of a : ");
int a=sc.nextInt();
System.out.println("Enter the value of n : ");
int exponent=sc.nextInt();
System.out.println("The value of " + a + " power " + exponent + " is " + power(a,exponent));
}
static int power(int b,int e)
{
if(e==0)
return 1;
else
return (b*power(b,e-1));
}
}
4. Program in Python programming language
def power(a,n):
if(n==1):
return(a)
if(n!=1):
return (a*power(a,n-1))
a=int(input("Enter the value of a : "))
n=int(input("Enter the value of n : "))
print("The value of" , a , "power" , n , "is" , power(a,n))
Note=> Indentation or Spacing is necessary in Python.