Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

The following program is written in a very poor style that usesglobal variables

ID: 3614924 • Letter: T

Question

The following program is written in a very poor style that usesglobal variables instead of parameters and arguments, resulting inunwanted side effects. Rewrite it using good style.

#include <iostream>
using namespace std;
int Power ();
int pow;
int x;
int result;
int main ()
{
    cout << "Enter power: ";
    cin >> pow;
    cout << "Enter value to be raised topower: ";
    cin >> x;
    cout << Power(x, pow);
}
int Power()
{
   result = 1;
   while (pow > 0)
   {
       result = result * x;
       pow--;
    }
    return result;
}

Explanation / Answer

#include <iostream> using namespace std;
int Power (int a, int p); // Declare Power function with twoparameters int main () {    int pow, x; // Declarevariables    cout << "Enter power: ";          cin >> pow;   // Ask user to input a value    cout << "Enter value to be raised topower: ";    cin >> x; // Ask user to enter the value to be raised to power    cout << Power(x, pow); }
// Function of power int Power(x, pow) {    int result = 1; // initialize the resultto 1    while (pow > 0) // Start awhile loop, set pow greater than 1    {    result = result * x;   // set result to product of result and x    pow--; // Decrease the power    }    return result; }