Hello all,

I'm working with exponentiation and I have an assignment to write a code for loop initialization and loop body but unfortunately, I don't even know what that means.

I was given the following information:

Input x // can be any float
Input y // has to be a positive integer

Set result = 1 // initial value

For i = 1 to y
result = result * x

Can anyone PLEASE translate what that means and show me an example of a loop initialization and loop body code? Please advise if you need more info. I apologize in advance for being slow.

Dani AI

Generated

This thread is describing a simple repeated-multiplication algorithm to compute a power. "Loop initialization" is the part where you set the loop counter (the starting value). The loop condition is the check that decides when the loop stops. The loop body is the statement(s) that run every iteration (the work you repeat). For this problem the body should multiply an accumulator by the base value each time, and the counter and condition must be chosen so the body runs exactly y times.

is pointing in the right direction but there are two common mistakes to watch for. First, the loop bound must produce exactly y iterations: either start the counter at 0 and run while counter < y, or start at 1 and run while counter <= y. Off-by-one choices change how many multiplies you perform. Second, the value you multiply into the accumulator must be the base (x), not the loop counter. Also make sure the accumulator is a floating type (double or float) if x can be fractional.

Edge cases and practical notes: if y == 0 the result should be 1 by definition. If you later need to support negative exponents, compute the positive power and take the reciprocal. For large y you can hit precision loss or overflow; for most real projects use the standard library power routine instead of a manual loop when appropriate. To debug, test small, known cases (for example base 2 exponent 3 gives 8) and print the accumulator each iteration to confirm the loop runs the expected number of times.

This keeps the logic simple: choose the counter and condition so the body runs y times, keep the accumulator initialized to the multiplicative identity, and multiply by the base inside the loop.

Recommended Answers

All 2 Replies

Input = cin
x is a float
y is a int
r is a int

for i to y means :

for(int i = 1; i < y; i++)
{
   //code goes here
}

The "code goes here" part is result = result * i;

Input = cin
x is a float
y is a int
r is a int

for i to y means :

for(int i = 1; i < y; i++)
{
   //code goes here
}

The "code goes here" part is result = result * i;

Thanks for the help. I'll try that. I'm still very new to programming.

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.