Hay guys,
this problem would be simple but cant quite figure it out. What this set of code is ment to do is: The user enters two numbers that they wish to raise 2 to the power of. (eg 2^4, 2^8) The program then calculates the answer for 2^4, 2^5, 2^6, 2^7 and 2^8 and shows on the screen. This has to be done using funtions and this is what i have got so far:
#include <iostream>
#include <string>
using namespace std;
int getInteger(string prompt);
int main()
{
int startingNumber = 2; //the 2 that is gettin powered 2
int firstNum = 0;
int secondNum = 0;
int answer = 0;
firstNum = getInteger("Enter First number: ");
secondNum = getInteger("Enter Second number: ");
cout << "The Answer is: " << answer << endl;
system("pause");
return 0;
}
int getInteger(string prompt)
{
int answer = 0;
cout << prompt;
cin >> answer;
// has to have error checking
while (answer <= 0)
{
cout << "Invalid number";
cout << prompt;
cin >> answer;
}
return answer;
}
it can also be done using simple for loop
first input the power(p) from the user and then multiply 2 p times using a for loop and print the result in the function itself
a function like this can be made
void computePower(int power1, int power2)
{
int result1=1 ,result2=1;
for (int i=0;i<power1;i++)
{
result1 = 2*result1;
}
for (int j=0;i<power2;j++)
{
result2 = 2*result2;
}
cout << result1 << result2;
}
another way is to use recursion if you want to try it
You need the include file<cmath> to use the double pow(double,double) function
The following does the same thing as kaidranzer suggests and is a minimum main driver..
{
cout<<"Raises 2 to a power over a range\n";
cout<<"Enter 2 integers (e.g. 3 7)\n";
int a=0,b=0,numlo=2,numnext;
cin>>a>>b;//get the power range
assert(a>0 && a< b);assert(b>a && b<26); //restricts range
cout<<"2 raised to the power of "<<a<<" through "<<b<<" is: \n";
for(int i=0;i<a-1;i++)
numlo*=2;
cout<<numlo<<" ";
numnext=numlo;
for(int i=a;i<b;i++)
{numnext*=2;
cout<<numnext<<" ";
if(i%12==0)cout<<endl;//start new line
}
cout<<endl;
system(" pause");
return 0;
}