Help with nested While!

The code only executes the nested while once.. why??

int main()
{
int base, expo, power;
while (base!=0 && expo!=0)
{
count = 0;
cout<<"Enter Base: ";
cin>>base;
cout<<"Enter Exponent: ";
cin>>expo;
while(count!=expo)
{
power=base*base;
count++;
}
cout<<"Power: "<<power<<endl;
}
getch();
}

//if i put base = 5 and expo = 3 , the power displayed is still 25
Last edited on
It executes the correct number of times. The problem is with power=base*base. No mater how many times you execute that, if base is 5, base*base=25. I would change the code to start with power=1, and put power*=base;
Also, please use code tags.
@renzboi21

You never updated the value of power.
Change power=base*base; to power+=base*base; and add power = 0; after count = 0;

I don't know if you declared count as an int before main, or not, but I would add it to your list of declarations before your while statement. Keeps everything in sight, that way.
Last edited on
While your way works, try and avoid using while loops in place of for loops. It's easier to follow for most people. Granted that's a style nitpick and people like doing things differently, but doesn't...

for (int i = 0; i < expo; i++)

...seem more definitive than a while loop? Plus you also save an insignificant amount of memory overall even if not during the loop.
Assuming you mean power should be 125 in the end...

power should start at 1 (5^0 = 1) before the loop, and you should have power*=base; inside the loop

EDIT: Also, I agree with TDSGoldenSun, use a for loop.
Last edited on
Tnx Guys,
got my code to work..

*I was told to do this exercise using while loops only.
Topic archived. No new replies allowed.