Following a C++ Program

On the following pages, a Java program will show you a series of C++ programs.
Each program demonstrates a different algorithm with a loop.

You will see the program execute statement by statement. You can choose to make each successive statement execute yourself, or you can have it run automatically but slowly, with a delay after each to let you see the result.

As the loop in each program runs, you will be able

and probably notice other properties as well.

The Java program will probably take several moments
to load and start running.

Please be patient and let it finish!

You can try the program in either of 2 forms:

An exercise

Exploration on your own

Here is an exercise to help you see the workings of some programs in C++.

It will take you through all 5 of the programs opposite.
Should you need to visit directly the exercise for each program, here they are (but note! each successive program is a bit harder than the previous one, so you should take them in order.)
  1. Program 1
  2. Program 2
  3. Program 3
  4. Program 4
  5. Program 5


if you just want to trace through a specific program, choose from this list:

A for-loop with a constant as its upper limit.

This one includes an if to control when a counter is increased.

A similar for-loop, but the upper limit is pre-supplied by the user.

A while-loop,

continuously taking the user's input until that input becomes -1.

A similar while-loop,

but it terminates either on reading a -1 from the user, or after a constant number of loops have run.

Almost the same,

but here the loop exits either on -1 or when the sum of all the inputs exceeds a predefined limit.
Support: Alastair Milne,
Principal Invetigator: Rika Yoshii, Ph.D.
Computer Science Dept,
Cal State University San Marcos