Im stuck on a problem can someone please help. Are instructor wants us to use the for loop method instead of a Pow function and wants us to go as high as the 5th power.
This is the assignment: Write a program that will ask the user for two integer numbers.
Use a for loop to raise the first number to the power of the second number.
I recommend using the long type instead of int type.
This is what i have so far.. Can someone give me some advice and also tell me what im doing wrong..Thx
#include <iostream>
using namespace std;
int main()
{
long int i;
long int y;
long int total;
total = 1;
cout << "Enter a number: ";
cin >> i;
cout << "Raise first number to the power of: ";
cin >> y;
for(i=1; i<=y; i++){
total = i * i *i;
}
cout << i << '\t' << "to the" << '\t' << y << '\t' << "power is: " << total << '\n';
The first time through the loop i == 1, so total is set to the value of 1 * 1 * 1 (1).
The second time through the loop i == 2, so total is set to the value of 2 * 2 * 2 (8).
The third time... and so forth, until the last time through the loop where i == y, so
total is set to the value of y * y * y (ie, y^3).
Well i was missing with it right now and this is what i did...It gives me the 5th power of any number but if i ask it to give me the 3rd power of a number it sill gives me the 5th..Is there something i need to change that i might be doing wrong..
using namespace std;
int main()
{
long int i;
long int x;
long int y;
long int total;
total = 1;
cout << "Enter a number: ";
cin >> x;
cout << "Raise first number to the power of: ";
cin >> y;
for(i=1; i<=y; i++){
total = x*x*x*x*x;
}
cout << x << '\t' << "to the" << '\t' << y << '\t' << "power is: " << total << '\n';
Just wondering, but aside from the inside of the loop, isn't there a problem with the loop instructions? For example, if the user inputed a number to the power of 1, wouldn't the loop still run one time and output a number to the power of two?
The confusing part to me is why use 5 as a limit? Wouldn't it be the same thing no matter what?
Would it be worth it to try and build a loop based program that deals with negative exponents and fractions as well for learning purposes?
Here's how I would've done it up to the end of his loop with what I changed on line 14:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
usingnamespace std;
int main()
{
longint i;
longint x;
longint y;
longint total;
total = 1;
cout << "Enter a number: ";
cin >> x;
cout << "Raise first number to the power of: ";
cin >> y;
for(i=1; i<=y; i++){
total = total*x;
}
Guess I spoiled it for him... I got confused because if I were working on this from scratch I probably would have set total = x and set the loop condition to i<y. Same thing just cutting out one loop iteration? Although I guess the way it is now has the added advantage of calculating stuff to the power of 0.
I still don't get why you would design it to go up to the power of 5.