int m, n, pow;

	cout << "Enter m and n: ";
	cin >> m >> n;
	pow = 1;
	
	for (int i=1; i<=n; i++)
		pow = pow * m;

	cout << m << "^" << n << " = " << pow << endl;
	return 0;
}

I dont get how this is working :((

ty!

Dani AI

Generated

The variable named pow is just a running product. It starts at 1 because 1 is the multiplicative identity: multiplying by 1 leaves the value unchanged, so the first multiplication by the base produces the base itself. The for‑loop repeats that multiplication exactly n times, so after n iterations the running product equals the base raised to the n-th power. , and gave short walkthroughs of that repeated‑multiplication idea; if the loop is hard to follow, trace it on paper with a small base and exponent and watch the product grow step by step.

A few practical points that the original posts didn’t fully cover:

  • If the exponent is 0 the loop does zero multiplications and the result should be 1. If the exponent can be negative, the integer loop does not produce the correct reciprocal — handle negative exponents separately or use a floating‑point pow function.
  • Name the result variable something like resultpow can be confusing because it matches the standard library function name.
  • Watch for overflow: integer powers grow quickly. Use a wider integer type (e.g., long long) or check against std::numeric_limits before multiplying.

For better performance with large integer exponents, use exponentiation by squaring (O(log n) multiplications) instead of the simple O(n) loop:

long long ipow(long long base, unsigned int exp) {
    long long result = 1;
    while (exp) {
        if (exp & 1) result *= base;
        base *= base;
        exp >>= 1;
    }
    return result;
}

Finally, validate user input (ensure the exponent is an integer in the supported range), decide how to treat 0^0 in your program, and add comments so the intent is clear for future readers.

Recommended Answers

All 3 Replies

int m, n, pow;

	cout << "Enter m and n: ";
	cin >> m >> n;
	pow = 1;
	
	for (int i=1; i<=n; i++)
		pow = pow * m;

	cout << m << "^" << n << " = " << pow << endl;
	return 0;
}

I dont get how this is working :((

ty!

Run through it in your head. If n = 4 and m = 2, then in your for loop you have:

pow = 1 * 2;
pow = 2 * 2;
pow = 4 * 2;
pow = 8 * 2;

2^5= 2*2*2*2*2;
=4*2*2*2
=8*2*2
=16*2
=32

see 2 is decreasing one by one.

for(loop the following code n times){
pow = pow multiplied by m
}

So if we are to loop 'pow * 3' 2 times, that would be:
pow = 1 * 3 = 3
pow = 3 * 3 = 9

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.