header

While 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 variables are:

The graphic below illustrates just the processing logic; the input and output is not shown.

Example

The variable, p, is given an initial value of 1. If n is initially zero, then the test fails immediately and p is still 1. This is correct because b0 = 1 for any nonzero b. If n is initially greater than zero, then the value of p is repeatedly multiplied by the base value, b. After each multiplication, the value of n is decreased by 1. Eventually, 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 Comment
  2 3 ? Initial values after input.
Execute: p = 1 2 3 1 Initialize the result.
Test: n > 0 2 3 1 Test condition is true.
Execute: p = p * b 2 3 2 p*b  =  1*2  =  2
Execute: n = n - 1 2 2 2 n-1  =  3-1  =  2
Test: n > 0 2 2 2 Test condition is true.
Execute: p = p * b 2 2 4 p*b  =  2*2  =  4
Execute: n = n - 1 2 1 4 n-1  =  2-1  =  1
Test: n > 0 2 1 4 Test condition is true.
Execute: p = p * b 2 1 8 p*b  =  4*2  =  8
Execute: n = n - 1 2 0 8 n-1  =  1-1  =  0
Test: n > 0 2 0 8 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 For Loop Example page contains a program that does the same thing another way.