Write a program thattakes a number x and its exponent y from the user and thencalculate the result

using whileloop

e.g.

Enter a number:2

Enter exponent:4

Result is: 16

Respuesta :

Answer:

#include<iostream>

using namespace std;

//main function program start from here

int main(){

   //initialize the variables

  int num, exponent;

   int result=1;

   //print the message on the screen

  cout<<"Please enter the number: ";

  cin>>num;  //store the user enter value

  cout<<"Please enter the exponent: "; //print the message on the screen

  cin>>exponent;//store the user enter value

   //take a while loop for calculating th power.

  while(exponent != 0){

   result = result*num;

  exponent--;

  }

  cout<<"Result is: "<<result<<endl;

}

Explanation:

Create the main function and declare the variable.

Then, display the message on the screen for the user and store the value enter by the user in the variables by using the instruction cin.

Take a while loop and it run until the value of exponent not equal to zero.

and then repeated multiply the number with the previous value which stores in the result.

for example;

the number is 2 and the exponent is 3. Initially, the result store is 1.

then, result = 1 * 2=2

exponent--, then exponent update the value 2.

again loop executes,

result = 2* 2=4

exponent--, then exponent update the value 1.

again loop executes,

result = 4* 2=8

exponent--, then exponent update the value 0.

The same process happens in our code and it run until the exponent not equal to zero. when it reaches zero, the loop will be terminated.

and finally, print the output.

ACCESS MORE