General code 1
CODE NO:- 13
Q) Write a program to calculate the power of a number.
#LOGIC
Repeatedly multiply the given no. for p times where p is the given power.
For example: given(i/p) no.=2 and given(i/p) power=5
then the result will be 32 as 2^5=32
or (2*2*2*2*2=32).
#Program( In C++):
In C++ language we use ' // ' for Single line comment and /*---*/ for multi line comment
1st approach: Using for loop
/**** Using for loop ***/
#include<iostream> // header file for i/p and o/p
using namespace std;
int main()
{
int n,m,i,re=1;
cout<<"\n enter no. and power:";
cin>>n>>m;
for(i=0;i<m;i++)
{
re=re*n;
}
cout<<"\n result is:"<<re;
return 0;
}
We got this output by using DEV C++ (IDE)
2nd approach: Recursive approach
/*** RECURSIVE APPROACH***/
#include<iostream>
using namespace std;
int power(int a,int b) //defining body of power funtion
{
if(b==0)
{
return 1;
}
else if(b==1)
{
return a;
}
else
{
return a*(power(a,b-1)); //recursive call
}
}
int main()
{
int n,m,result;
cout<<"\n enter no. and power:";
cin>>n>>m;
result=power(n,m); // calling the function power
cout<<"\n result is:"<<result;
return 0;
}
We got this output by using DEV C++ (IDE)
Link: For other General Problems
Q) Write a program to calculate the power of a number.
#LOGIC
Repeatedly multiply the given no. for p times where p is the given power.
For example: given(i/p) no.=2 and given(i/p) power=5
then the result will be 32 as 2^5=32
or (2*2*2*2*2=32).
#Program( In C++):
In C++ language we use ' // ' for Single line comment and /*---*/ for multi line comment
1st approach: Using for loop
/**** Using for loop ***/
#include<iostream> // header file for i/p and o/p
using namespace std;
int main()
{
int n,m,i,re=1;
cout<<"\n enter no. and power:";
cin>>n>>m;
for(i=0;i<m;i++)
{
re=re*n;
}
cout<<"\n result is:"<<re;
return 0;
}
We got this output by using DEV C++ (IDE)
2nd approach: Recursive approach
/*** RECURSIVE APPROACH***/
#include<iostream>
using namespace std;
int power(int a,int b) //defining body of power funtion
{
if(b==0)
{
return 1;
}
else if(b==1)
{
return a;
}
else
{
return a*(power(a,b-1)); //recursive call
}
}
int main()
{
int n,m,result;
cout<<"\n enter no. and power:";
cin>>n>>m;
result=power(n,m); // calling the function power
cout<<"\n result is:"<<result;
return 0;
}
We got this output by using DEV C++ (IDE)
Link: For other General Problems
Nice
ReplyDelete