I am very new to c++ and we cannot use any built in libraries yet for the following program.

The program runs fine until I add a question at the end if the user wants to quit or not. If not the program will run again to compute the power to another base number that is input by the user....and so on until they prompt to exit.

when I run it the first number input comes out fine. The next one that is input, the answer is added to the first answer....therefore being wrong.

"enter a positive integer"
"enter another integer as exponent"
9 /* 9 is correctly displayed */
"Do you want to continue"?
"enter a positive integer"
"enter another integer..."
36 /* this is where it is coming out incorrect...the 4 is being mult by 9...*/

I have feeling its something very simple that I'm doing wrong...but i have gone around in circles trying to find whats wrong. I know you cannot give answers but any help in direction will be appreciated.

Here is my code:

#include <iostream>
using namespace std;

int main ()  {

   int x;  
   int y; 
   int pwr = 1;
   bool exit = false;   
   char YesNo;
   while (!exit) {

   cout << "Enter a positive integer: ";  
   cin >> x;
   cout << "Enter another integer as the exponent: "; 
   cin >> y;
   for (int i = 1; i <= y; i++) {
	   pwr = pwr * x;
   cout << pwr << endl;
   cout << "Do you want to continue? (Y or N) \n";
   cin >> YesNo;
   if (YesNo == 'N' || YesNo == 'n')
    exit = true;  

   return 0; 

Recommended Answers

just reset pwr to 1, since pwr never goes out of scope it holds the old value

Jump to Post

better yet move declaration inside while loop

Jump to Post

All 5 Replies


The program works fine without the continue option.

just reset pwr to 1, since pwr never goes out of scope it holds the old value

better yet move declaration inside while loop

Will have to try after work tomorrow. I will let you know how it works.

Yes, this was a very simple fix. Thank you for your responses. I just moved the pwr declaration inside the While loop and works just fine now.

Thank you!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.21 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.