-4

I have to write a program that calculates n times n for the numbers between 1 and 9 using a function. The output should be like 1, 4, 27, 256...

I can feel I'm very close to finishing it but I just can't figure out what the problem is, here is the code I wrote:

#include <iostream>
using namespace std;
int result, number, n;

void function1()
{
    result = number;
    for (int x = 1; x < number; x++)
    {
        result = number*result;
    }
}
int main()
{
    for (n = 1; n < 10; n++)
    {
        function1();
        cout << result << endl;
        system("pause");
        return 0;
    }
}

1 Answers1

0

Try this :-

#include <iostream>
#include <math>
using namespace std;
int result, number, n;

void function1(int number)
{
  int result;
  result = pow(number,number);
  cout<<result;
}
int main()
{
  for (n = 1; n < 10; n++)
  {
    function1(n);
    system("pause");
  }
  return 0;
}
3Demon
  • 550
  • 3
  • 9
  • i've never heard of pow before, is there a simplier way to do this or i have to use pow? – erdemcagri1 Dec 01 '14 at 21:26
  • you can also implement this program by using loop as he has done it, he just forgot to pass the parameters into the function, rest was allright... :-) for example if we have to calculate n power n we can do, result = n; for(i=1;i<=n;i++) { result = result * n; } this will also do the same thing..... – 3Demon Dec 01 '14 at 21:33
  • @ÇağrıErdem _"i've never heard of pow before, is there a simplier way to do this or i have to use pow?"_ Probably not. The [`double std::pow( double base, double exp );`](http://en.cppreference.com/w/cpp/numeric/math/pow) function _Computes the value of base raised to the power `exp` or `iexp`._ If you simply want to raise values by `2`, you can use straightforward multiplication of `n` with itself like: `n*n`. If the exponent isn't fixed, use `pow()`. – πάντα ῥεῖ Dec 01 '14 at 21:43