for loop exponents

I can't figure out how to get the proper output. The code gives me an output like: Enter a positive integer: 5
5^5=25
• asks the user to a positive integer between 1 and 10
• checks that the value entered is valid, if not ask the user repeatedly
until an integer between 1 and 10 is entered.
• calculates and prints out x
x
(DO NOT USE pow() ) as shown
below
Here is an example of the program should work:
Enter a number between 1 and 10: 6
6^1 = 6
6^2 = 36
6^3 = 216
6^4 = 3296
6^5 = 19776
6^6 = 118656
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
 #include <iostream>
using namespace std;

int main() {
    int x;

    cout << "Enter a positive integer: ";
    cin >> x;
    while (x <= 0) {
        cout << "Please enter a positive value: ";
        cin >> x;
    }
    int result = 1;
    for (int i = 1; i <= x; i++){
        result = i++ * x;}

    cout <<x<<"^"<<x++<<"="<<result<< endl;
    return 0;
your for loop is really weird.
The brute force loop looks like this.
result = 1;
for(k = 0; k < power; k++)
result*= base;
Last edited on
yeah, it probably does look weird because honestly I don't know what I'm doing
Your:
1
2
3
4
5
int result = 1;
for ( int i = 1; i <= x; i++ ) {
  result = i++ * x;
}
cout << x << "^" << x++ << "=" << result << endl;

is equivalent to:
1
2
3
4
5
6
7
int result;
for ( int i = 1; i <= x; i += 1 ) {
  result = i * x;
  ++i;
}
cout << x << "^" << x << "=" << result << endl;
++x;

is equivalent to:
1
2
3
4
5
6
int result;
for ( int i = 1; i <= x; i += 2 ) {
  result = i * x;
}
cout << x << "^" << x << "=" << result << endl;
++x;

The result is overwritten on every iteration.

In other words, you do show x * (x-1) or x * x depending on whether x is even or odd.


1
2
3
4
result = 1;
for ( k = 0; k < power; k++ ) {
  result *= base;
}

is equivalent to:
1
2
3
4
result = 1;
for ( k = 0; k < power; k++ ) {
  result = result * base;
}

The result accumulates from each iteration.
it probably does look weird because honestly I don't know what I'm doing
Programming can be very frustrating when you first start doing it.

It might help you understand what's going on if you add temporary code to print out i and result inside your loop:
1
2
3
4
5
    int result = 1;
    for (int i = 1; i <= x; i++) {
	result = i++ * x;
	cout << "i=" << i << " result = " << result << '\n';
    }

Enter a positive integer: 6
i=2 result = 6
i=4 result = 18
i=6 result = 30
6^6=30

Well that's a big old mess! Here's another run:
Enter a positive integer: 10
i=2 result = 10
i=4 result = 30
i=6 result = 50
i=8 result = 70
i=10 result = 90
10^10=90


Why does i go up by 2's? Look at the code and fix that.
When I entered 10, result goes up by 20's. See if you can fix that.

Look at your variables x, i, and result. What does each one represent? Be clear about this. Be sure you're using each one appropriately.
Topic archived. No new replies allowed.