header

For Loop Example

Consider a simple program that asks the user to supply an integer base value and a positive integer exponent. The program then displays the value of the base raised to the specified exponent. The program uses these variables:

The graphic below illustrates just the processing logic; the input of b and n and the output of p are not shown.

The variable, p, is given an initial value of 1. The counter, c, is initialized at zero because at that point the program has gone through the loop zero times. If n is zero, then the test fails immediately and p is still 1. This is correct because b0 = 1 for any nonzero b. If n is greater than zero, then the value of p is repeatedly multiplied by the base value, b. After each multiplication, the value of c is increased by 1. Eventually, the counter reaches the value of n, the loop terminates, and p = bn.

The table below illustrates a sample run of this program where the user entered a value of 2 for the base and a value of 3 for the exponent.

Action b n p c Comment
  2 3 ? ? Initial values after input.
Execute: p = 1 2 3 1 ? Initialize the result.
Execute: c = 0 2 3 1 0 Initialize the counter
Test: c < n 2 3 1 0 Test condition is true.
Execute: p = p * b 2 3 2 0 p * b  =  1 * 2  =  2
Execute: c = c + 1 2 3 2 1 c + 1   =  0 + 1  =  1
Test: c < n 2 3 2 1 Test condition is true.
Execute: p = p * b 2 3 4 1 p * b  =  2 * 2  =  4
Execute: c = c + 1 2 3 4 2 c + 1   =  1 + 1  =  2
Test: c < n 2 3 4 2 Test condition is true.
Execute: p = p * b 2 3 8 2 p * b  =  4 * 2  =  8
Execute: c = c + 1 2 3 8 3 c + 1   =  2 + 1  =  3
Test: c < n 2 3 8 3 Test condition is false.

When the test condition becomes false, the loop will terminate and the final value of the result, 8, will be displayed.

Note: the While Loop Example page has a program that does the same thing another way.