Solved

Creating a power program with an array

Posted on 2003-10-21
26
251 Views
Last Modified: 2010-04-02
Hey all!  Here is a problem that my teacher proposed in class.  I need to write a template function that takes two arguments: an integer n and a variable v of a parameterized type. The function computes and returns the nth power of v. Also write a driver function (i.e. the main function) to ask the user to enter a positive integer (n). Now use the template function to compute the nth power of 8.5 and displayed the result, then use the template function to compute the nth power of 8 and displayed the result. Continue to ask the user for another integer and repeat the computation until the user gives a negative integer.

To be honest, I have no idea where to start.  I know that I have to use an array (because that is the chapter we are in), but other than that I am lost.  Please help.  Thank you.
0
Comment
Question by:marcypark
  • 11
  • 10
  • 5
26 Comments
 
LVL 86

Expert Comment

by:jkr
ID: 9595426
>>I know that I have to use an array

No, this does not require arrays at all. To give you a start, here's a really short template class solution (not a template function - this is left as an excercise to the reader *g*)

template<int N> struct NthPower {

   double ReturnIt ( double d) { return pow ( d, N);}
};

As we are not supposed to do your homework, you are to proceed from here and get back with some results on your own :o)
0
 

Author Comment

by:marcypark
ID: 9595452
This is not a homework problem.  It was only a question he proposed in class.  He is not going to give us the answer and I am not going to be graded on it, but I would like to figure it out anyhow.  

JKR -- I am not understanding the notation you are using.  I am using Visual C++ 6.0.  So, is the notation different?
0
 
LVL 86

Expert Comment

by:jkr
ID: 9595475
>>This is not a homework problem.  It was only a question he proposed in class

Well, the more you should be interested in doing most of by yourself :o)

>>JKR -- I am not understanding the notation you are using.  I am using Visual C++ 6.0

Me, too - what is so strange about it?
0
 

Author Comment

by:marcypark
ID: 9595566
I am new a C++ so I am not too familiar with it yet. When you wrote:

template<int N> struct NthPower {

   double ReturnIt ( double d) { return pow ( d, N);}
};

is this just an example of what it should look like?
0
 
LVL 19

Expert Comment

by:Dexstar
ID: 9595577
JKR is right.  You'll learn more if you do these exercises yourself.  OTOH, I'm new the EE and I need the points, so here is your function template:

template<typename TYPE>
TYPE ComputePower( int nPower, TYPE nValue )
{
      if ( nPower > 0 )
      {
            return nValue * ComputePower(nPower-1, nValue);
      }
      else
      {
            return 1;
      }
}

You can write your own driver function, but it will have the basic form of:
    int nUserInput;
    int nDisplayValue1;
    float nDisplayValue2;

// Get the User Input

// Exit if it is is less than 0

// Compute the values
nDisplayValue1 = ComputePower(nUserInput, 8);
nDisplayValue2 = ComputePower(nUserInput, 8.5f);

// Display the values

// Get the next user input


Hope this helps,
Dex*
0
 

Author Comment

by:marcypark
ID: 9595617
Thank you both JKR and Dexster.  Here is what I have come up with so far, but I have numerous errors and warnings:

#include <iostream.h>

int ComputePower(int nPower, float nValue);

int main ()
{
      cout << "Please enter a postive integer or enter a negative integer to end:" << endl;
      cin >> nPower;
      
      if (nPower > 0)
      {
            return nValue * ComputePower(nPower-1, nValue);
            cout << "The " << nPower << "th power of 8.5 is " << nDisplayValue1;
            cout << "The " << nPower << "th power of 8 is " << nDisplayValue 2;
      }
      else
      {
            return 1;
      }
}

int ComputePower(int nPower, TYPE nValue )
{
      int nUserInput;
    int nDisplayValue1;
    float nDisplayValue2;

      nDisplayValue1 == ComputePower(nUserInput, 8);
      nDisplayValue2 == ComputePower(nUserInput, 8.5f);
}
0
 
LVL 86

Expert Comment

by:jkr
ID: 9595640
First of all, use

#include <iostream>
using namespace std;

instead of

#include <iostream.h>

The 1st one is the standard. Then, declare the integer variables you are using in your "main()" function (nDisplayValueX, nPower etc :o)
0
 

Author Comment

by:marcypark
ID: 9595675
I know only have one error and three warnings.  The warnings come from the "==" used in the function and the error comes from the function needing to return a value, but would the value be? (Thank you for sticking with me :) )

#include <iostream>
using namespace std;

int ComputePower(int nPower, float nValue);

int main ()
{
      int nDisplayValue1;
      float nDisplayValue2;
      int nPower;
      int nValue=0;
      cout << "Please enter a postive integer or enter a negative integer to end:" << endl;
      cin >> nPower;
      
      if (nPower > 0)
      {
            return nValue * ComputePower(nPower-1, nValue);
            cout << "The " << nPower << "th power of 8.5 is " << nDisplayValue1;
            cout << "The " << nPower << "th power of 8 is " << nDisplayValue2;
      }
      else
      {
            return 1;
      }
}

int ComputePower(int nPower, float nValue )
{
      int nUserInput;
    int nDisplayValue1;
    float nDisplayValue2;

      nDisplayValue1 == ComputePower(nUserInput, 8);
      nDisplayValue2 == ComputePower(nUserInput, 8.5f);
}
0
 
LVL 86

Expert Comment

by:jkr
ID: 9595692
Well, now you have to make 'ComputePower()' return a value - are you sure you want it to be an 'int'?
0
 

Author Comment

by:marcypark
ID: 9595694
Should it be void?
0
 

Author Comment

by:marcypark
ID: 9595710
I now have no errors and no warnings, but the program quits after I enter a number and the results are no diplayed and also, the program does not repeat.  Here is an update of what I have:

#include <iostream>
using namespace std;

float ComputePower(int nPower, float nValue);

int main ()
{
      int nDisplayValue1;
      float nDisplayValue2;
      int nPower;
      int nValue=0;
      cout << "Please enter a postive integer or enter a negative integer to end:" << endl;
      cin >> nPower;
      
      if (nPower > 0)
      {
            return nValue * ComputePower(nPower-1, nValue);
            cout << "The " << nPower << "th power of 8.5 is " << nDisplayValue1;
            cout << "The " << nPower << "th power of 8 is " << nDisplayValue2;
      }
      else
      {
            return 1;
      }
}

float ComputePower(int nPower, float nValue )
{
      int nUserInput=0;
    int nDisplayValue1;
    float nDisplayValue2;

      nDisplayValue1 = ComputePower(nUserInput, 8);
      nDisplayValue2 = ComputePower(nUserInput, 8.5f);
      return nDisplayValue1 && nDisplayValue2;
}
0
 

Author Comment

by:marcypark
ID: 9595739
Now the program runs and displays the output, but the output is 0 for both the power of 5 of 8.5 and 8.  How can I get the result displayed properly?
0
 
LVL 86

Expert Comment

by:jkr
ID: 9595749
Um, you only can return ONE value from a function. Reconsider your use of 'ComputePower()', calling it recursively is not a good idea - and you are not using template functions :o)

Consider

#include <math.h>

template<int N>
doubleComputePower (double d) {

  return pow ( d, N);
}

and think about what templates actually serve for...
0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
LVL 86

Expert Comment

by:jkr
ID: 9595752
Ooops:

#include <math.h>

template<int N>
double ComputePower (double d) {

 return pow ( d, N);
}
0
 
LVL 86

Expert Comment

by:jkr
ID: 9595773
BTW, a word about template instantiation: It would be

double d1 = ComputePower<5>(8.5);

0
 
LVL 86

Expert Comment

by:jkr
ID: 9595781
Disregard the last posts, I think you are not referring to the template I am thinking of :o)

Consider

#include <math.h>

doubleComputePower (double d1, d2) {

 return pow ( d1, d2);
}
0
 

Author Comment

by:marcypark
ID: 9595786
I am confused now about where the double goes and what exactly it is used for.
0
 
LVL 86

Expert Comment

by:jkr
ID: 9595828
"double" is the data type of the value this function returns - as opposed to an integer or a string. E.g.

double ReturnDouble() {

  double d = 3.141;

  return d;
}

int ReturnInt () {

  int n = 42;

  return n;
}
0
 
LVL 19

Expert Comment

by:Dexstar
ID: 9600423
marcypark,

You should refer back to your teachers original requirements of "to write a template function that takes two arguments: an integer n and a variable v of a parameterized type. The function computes and returns the nth power of v."

None of what you've posted so far meets that requirement.  Here is exactly the function template that you need:

template<typename TYPE>
TYPE ComputePower( int nPower, TYPE nValue )
{
      if ( nPower > 0 )
      {
            // Because X^Y = X * (X^(Y-1))
            return nValue * ComputePower(nPower-1, nValue);
      }
      else
      {
            // Because X^0 = 1
            return 1;
      }
}

This function template solves all of your problems.  You see where it says "typename TYPE", that is your way of telling the compiler that sometimes you want to call this function with an int, sometimes you want to call it with a float, and sometimes you want to call it with a double.  You can just use this function, and use whatever datatype you want in place of TYPE, and the compiler will do the rest for you.  This is the solution that your teacher wanted.

Now all you have to do is show that it works (it does, I tested it) by calling it with an int (the example your teacher wanted you to use is 8) and then calling it again with a float or double (e.g, 8.5).

For instance,
      double x = ComputePower( 2, 8.5 );      // x = 72.25
      int i = ComputePower( 2, 8 );            // i = 64

See?  You can just that one function template for BOTH types (double and int), and the compiler works it out for you.

Hope this helps,
Dex*

0
 
LVL 19

Expert Comment

by:Dexstar
ID: 9600467
Okay, jkr doesn't like my recursive solution...  :P

Well, you can't use pow() because that requires doubles, which can't meet the requirement of "a template function that takes two arguments: an integer n and a variable v of a parameterized type" without a lot of casting.  But here is a solution that meets the requirements, but is not recursive:

template<typename TYPE>
TYPE ComputePower( int nPower, TYPE nValue )
{
     TYPE nReturnValue = 1;

     while ( nPower-- > 0 )
     {
          nReturnValue *= nValue;
     }

     return nReturnValue;
}

Is that better, jkr?  :)

Dex*
0
 
LVL 86

Expert Comment

by:jkr
ID: 9601453
>>Okay, jkr doesn't like my recursive solution...  :P

I just think that templates as C++ understands them seem to be a *too* advanced topic given the questions Marcy was asking...
0
 

Author Comment

by:marcypark
ID: 9604109
Well, I have taken in all of your comments, but I do not know what:

template<typename TYPE>
TYPE ComputePower( int nPower, TYPE nValue) is. In my class, we have not learned anything like this.  So, I am confused about what I am suppose to do.  Please help so I can figure this thing out.
0
 
LVL 19

Expert Comment

by:Dexstar
ID: 9607914
Well, jkr is right.  This is kind of an advanced topic.  But you said your teacher used the words "function template", so that's what I gave you.  Let me explain what it is.

You would understand if I had something like this, right?
      int ComputePowerInt( int nPower, int nValue )
      {
           int nReturnValue = 1;
      
           while ( nPower-- > 0 )
           {
                nReturnValue *= nValue;
           }
      
           return nReturnValue;
      }

Then you can just use code like this:
      int nX = ComputePowerInt( 2, 8 );      // Find 8 squared
      int nY = ComputePowerInt( 3, 9 );      // Find 9 to the 3rd power

That would be great for working with ints.  But if you also wanted to do floats, you would need something like this:
      int ComputePowerFloat( int nPower, float nValue )
      {
           float nReturnValue = 1;
      
           while ( nPower-- > 0 )
           {
                nReturnValue *= nValue;
           }
      
           return nReturnValue;
      }

And for doubles, you would need something like this:
      int ComputePowerDouble( int nPower, double nValue )
      {
           double nReturnValue = 1;
      
           while ( nPower-- > 0 )
           {
                nReturnValue *= nValue;
           }
      
           return nReturnValue;
      }

Isn't that a big hassle?  To have 3 versions of the exact same thing, with the only difference being the datatype?  Wouldn't it be nice if I could write that one time and use it with different datatypes?  Well, in C++, you can.  It is called a function template!

So take a look at this:
      template<typename TYPE>
      TYPE ComputePower( int nPower, TYPE nValue )
      {
           TYPE nReturnValue = 1;
      
           while ( nPower-- > 0 )
           {
                nReturnValue *= nValue;
           }
      
           return nReturnValue;
      }

The "template<typename TYPE>" means "I want to use different datatypes with this function.  So, I'm just going to use the word TYPE in place of the datatype name to be used".  If you do it like that, then you can use code like this:
      double x = ComputePower( 2, 8.5 );      // x = 72.25
      int i = ComputePower( 2, 8 );            // i = 64

See?  I call the same function, sometimes with Floats, and sometimes with Ints, but it still works!

Okay, that's the best explanation I can give you for Function Templates.  Any good C++ book will have a chapter on them.  If your book doesn't, try this link instead:
      http://cplus.about.com/library/weekly/aa070202a.htm

Hope this helps,
Dex*
0
 

Author Comment

by:marcypark
ID: 9610637
Well, here is what I came up with but it is far from right.  What am I still doing wrong?

#include <iostream>
#include <math.h>
using namespace std;

int ComputePower (int nPower, int nValue);

int main ()
{
      int nDisplayValue1=0;
      float nDisplayValue2=0;
      int nPower;
      int nReturnValue=0;
      int nX=0;
      int nY=0;
      cout << "Please enter a postive integer or enter a negative integer to end:" << endl;
      cin >> nPower;
      
      if (nPower > 0)
      {
            cout << "The " << nPower << "th power of 8.5 is " << nX<< endl;
            cout << "The " << nPower << "th power of 8 is " << nY << endl;
            //return nValue * ComputePower(nPower-1, nValue);
      
      }
      else
      {
            return 1;
      }
      return 0;
}

  int ComputePowerInt( int nPower, int nValue )
     {
          int nReturnValue = 1;
     
          while ( nPower-- > 0 )
          {
               nReturnValue *= nValue;
                     int nX = ComputePowerInt( 2, 8 );     // Find 8 squared
     int nY = ComputePowerInt( 3, 9 );
          }
     
          return nReturnValue;
     }

0
 
LVL 19

Accepted Solution

by:
Dexstar earned 250 total points
ID: 9610726
marcypark,

Try this as a solution:
#include <iostream>
#include <math.h>
using namespace std;

template<typename TYPE>
TYPE ComputePower( int nPower, TYPE      nValue )
{
      TYPE nReturnValue =      1;

      while ( nPower-- > 0 )
      {
            nReturnValue *= nValue;
      }

      return nReturnValue;
}

int main ()
{
       int nPower;

       do
       {
            cout << "Please enter a postive integer or enter a negative integer to end: " << endl;
            cin >> nPower;
            if ( nPower >= 0 )
            {
               cout << "The " << nPower << "th power of 8 is " << ComputePower(nPower, 8) << endl;
               cout << "The " << nPower << "th power of 8.5 is " << ComputePower(nPower, 8.5) << endl;
            }
      }
       while ( nPower >= 0 );

       return 0;
}

Does that make more sense?
Dex*
0
 

Author Comment

by:marcypark
ID: 9610981
Thank you so much Dex and jkr!!!
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
C Language combined operators 28 106
FMX StringGrid1->Canvas->FillRect Problem 3 127
Least Squares Curve Fitting 4 60
passing data from one form to another form in c++ 27 75
In days of old, returning something by value from a function in C++ was necessarily avoided because it would, invariably, involve one or even two copies of the object being created and potentially costly calls to a copy-constructor and destructor. A…
Introduction This article is a continuation of the C/C++ Visual Studio Express debugger series. Part 1 provided a quick start guide in using the debugger. Part 2 focused on additional topics in breakpoints. As your assignments become a little more …
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.
The viewer will be introduced to the technique of using vectors in C++. The video will cover how to define a vector, store values in the vector and retrieve data from the values stored in the vector.

910 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now