Function

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;
}

thanks
querulous
Well you could use a loop like:
1
2
3
4
5
6
7
cout<<"Enter two integers";
cin>>a>>b;
//the func
double getpower(int a,int b)
  for(int i=a;i<b+1;i++)
  y=pow(2.0, i);
  cout>>y<<" ";

I haven`t tried it to see if pow objects to using an int i.l.o. a double but it should work with some massage.
hope this helps.
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

may the force be with you

Last edited on
Doesnt seem to work when i add ow would i have to change my code for it to work, ty guys for this btw. using visual studio
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..
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
{
    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;      
}      

hope this helps
Try a left shift. something like:

 
  int answer = 1 << input;


Or perhaps:

1
2
  int leftShift = sizeof(int)*8;
  int answer = 1 << (input <= leftShift)? input: 0;
Topic archived. No new replies allowed.