Darn function does'nt work the way i want it

Hello gurru's of C++

Once again I have a very simple problem that I need some insight on
it a for loop. I wrote a simple program where the program should just return the power of a number to ouput.

I have researched this problem and I got it to work with a recursive if / else loop
1
2
3
4
5
6
ulong Powerof (ushort x, ushort y)
{
	if (y == 1) // test
		return x;
	else
		return (x * Powerof (x, --y));


But, this is not want I want.

I want to use a -for loop-

I have tried several different options, all had no success.
I understand how the for loop works <for ( intialize, Test, Action) and after a hundred different tries I have'nt gotten one of my attempts to work Please help.

Here is my entire program: Let me know what you think.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include "stdafx.h"
#include <iostream>
using namespace std;
typedef unsigned short ushort;
typedef unsigned long ulong;

ulong Powerof (ushort x, ushort y);							//function prototype			

int _tmain(int argc, _TCHAR* argv[])
{
	cout << "This program will return the power of the inputted numbr " << endl << endl;
	ushort x;
	ulong Answer;
	cout << "input the base number: ";
	cin >> x;
	ushort y;
	cout << "Input the power of multiplier: ";
	cin >> y;
	Answer = Powerof (x, y);
	cout << "Base Number " << x << " to the " << y << " power is: " << Answer;
	char response;
	cin >> response;
	return 0;
}

ulong Powerof (ushort x, ushort y)
{
	if (y == 1) // test
		return x;
	else
		return (x * Powerof (x, --y));
}
I want to use a -for loop-

Well, here's a version which is self-contained, and uses a loop. But I use a while rather than a for loop. Maybe it will give you an idea.

1
2
3
4
5
6
7
8
9
ulong Powerof (ushort x, ushort y)
{
    ulong result = 1;

    while (y--)
        result *= x;

    return result;
}
Topic archived. No new replies allowed.