In: Computer Science
Exercise 5.1
Please provide code for both parts A and B.
PART A
Modify the P5_0.cpp program (located below) and use the predefined function pow to compute the ab power. Here is the definition of the pow function:
double pow (double base, double exponent);
i.e. pow takes two parameters of type double, a and b and its value returned is of type double. You need to use pow in a statement like this:
p = pow(a,b)
Please note that in order to use the pow predefined function, you need to include the cmath directive, i.e. #include.
Call your new program ex51.cpp.
Imagine, you wanted to compute hundreds of these calculations in a program. Can you use a while loop in the program to do so?
PART B
Improve the program of exercise 5.1 by using a while loop that asks the user to input a and b (of any type), computes the pow(a, b)[i.e computes p = pow(a,b)] and displays the result. Call your new improved program ex52.cpp.
CODE: P5_0.cpp program
// P5_0.cpp This C++ program computes the value of ab
for three cases.
#include
using namespace std;
int main(void)
{
int i = 0;
int a = 2, b = 4, p = 1;
while(i < b) // computing
2^4
{
p = p * a;
i++;
}
cout << a << " to
the power of " << b << " is = " << p <<
endl;
i = 0;
p = 1;
a = 3, b = 3;
while(i < b) // computing
3^3
{
p = p * a;
i++;
}
cout << a << " to
the power of " << b << " is = " << p <<
endl;
i = 0;
p = 1;
a = 5, b = 4;
while(i < b) // computing
5^4
{
p = p * a;
i++;
}
cout << a << " to
the power of " << b << " is = " << p <<
endl;
return 0;
}
Part A : exc51.cpp
Program :
#include<bits/stdc++.h>
using namespace std;
int main(void)
{
int i = 0;
double a = 2, b = 4,p;
p = pow(a,b);
cout << a << " to the power of " << b << "
is = " << p << endl;
a = 3, b = 3;
p = pow(a,b);
cout << a << " to the power of " << b << "
is = " << p << endl;
a = 5, b = 4;
p = pow(a,b);
cout << a << " to the power of " << b << "
is = " << p << endl;
return 0;
}
Output :
Imagine, you wanted to compute hundreds of these calculations in a program. Can you use a while loop in the program to do so?
Answer : Yes we can define while loop to compute hundreds of calculations in a program.please go through exc52.cpp program for clear explanation.
Part B : exc52.cpp
Program :
#include<bits/stdc++.h>
using namespace std;
int main(void)
{
int i = 0,n;
double a,b,p;
cout << "Enter no.of times to compute values :
";
cin >> n;
while(i<n){
cout << "Enter 'a' value :
";
cin >> a;
cout << "Enter 'b' value :
";
cin >> b;
p = pow(a,b);
cout <<"\n" << a << " to the power
of " << b << " is = " << p << "\n" <<
endl;
i++;
}
return 0;
}
Output :