Examples of Programs Having Loops and Branches 
Our typical exams have two parts. Part 1 contains short questions of the form like the "self-test exercises"
that you find in the textbook. A good way to study for this type of problems is to go through the
"self-test exercises", and check with the solutions that are also provided. Part 2 requires you to write full-length programs like those you have been doing for your homework assignments. Examples of such problems can be found in the textbook under the heading: "Programming Projects".
Here are three examples of full-length programs involving loops and branches.
- 
// A computer game in which the player has 6 chances to guess at
// a secret number randomly picked between 1 and 6 by the program.
// Use is made of a predefined function rand().
// Each call to rand() returns an integer randomly distributed 
// between 0 and 32767 (= 2^15 - 1, a predefined constant RAND_MAX).
#include <iostream>
using namespace std;
int main ( )
{
        // Initialize variables
        int solution,   // the secret number 
                guess,      // the number picked by the player
                loop;       // the loop control variable
        // Generate a number between 1 and 6 randomly
        // Note: the number given by rand( ) % 6 is always between 0 and 5 
        solution = rand( ) % 6 + 1;  
        for ( loop = 1; loop <= 6; loop++)
        {
                // Enter a number from the keyboard
                cout << "Enter a number between 1 and 6: ";
                cin >> guess;
                // See if the player picks the correct number
                if (guess == solution)
                {
                    // Correct number
                        cout << "You've guessed the right number after "
                            << loop << " trial(s).\n";
                        return 0; // Game is over, quit program immediately
                }
                else
                {
                        // Incorrect number
                        cout << "The number is not correct. Please try again.\n";
                }
            }// end for loop
        cout << "You had 6 trials to guess at a number between 1 and 6,\n"
                << "and you still have not come up with the correct number.\n"
                << "You must be really really stupid!\n";
} // end of main
 - 
// Program to compute the exponential function of a real value x.
// Algorithm: uses the series representation of the exponential function:
// exp(x) = 1 + x + x^2/2! + x^3/3! + ... + x^m/m! + ...
// For given values of x and m, where m(=20) is the last term to be summed, 
// sum the series and compare with the exact result.
// Display the results for k=1, 2, ..., 20.
// Let the user input the value of x, and allow the user to re-calculate 
// for any other values of x.
// Version 1: sum up to the mth term with no tolerance checking.
 
#include <iostream>
#include <cmath>  // needed for the exponential function exp( )
using namespace std;
int main ( )
{
        int k,      // loop index 
             m = 20; // maximum number of loops
        double x,   // value of x
             xk,     // x to the power k
             sum,    // sum of series
             fac,    // factorial of k: k!
             expx;   // exact value of exp(x)
        char key;   // character key to see if user wants to continue
        //cout.setf(ios::scientific);       // use scientific notation
        cout.setf(ios::fixed|ios::showpoint);   // fixed point & show decimal point
        cout.precision(6);          // show 6 decimal places
        do
        {
                sum = 1.0;  // reset sum to 1
                 xk = 1.0;   // reset xk to 1
                fac = 1.0;  // reset k! to 1
        
                cout << "Enter the value of x: ";
                 cin >> x;
                expx = exp(x);  // exact value for exp(x)
                for (k = 1; k <= m; k++)
                {
                        xk *= x;            // compute x^k
                        fac *= double(k);   // compute k!
                        sum += xk / fac;    // compute & accumulate x^k / k!
                        cout << k << ' ' << sum << ' ' << expx << endl;
                }
                cout << "Enter \'Y\' or \'y\' to continue,\n"
                            << "or any other key to quit: ";
                cin >> key;
        } while (key == 'Y' || key == 'y');
}// end of main
 - 
// Program to compute the exponential function of a real value x.
// Algorithm: uses the series representation of the exponential function:
// exp(x) = 1 + x + x^2/2! + x^3/3! + ... + x^m/m! + ...
// For given values of x and m, where m(=20) is the last term to be summed, 
// sum the series and compare with the exact result.
// Display the results for k=1, 2, ..., 20.
// Let the user input the value of x, and allow the user to re-calculate 
// for any other values of x.
// This second version stops summing the series as soon as we reach a term
// that contributes less than 1 part in a million to the series.
// Note that fabs(x) is a predefined function (in cmath) that 
// takes the absolute value of a float.
// Version 2: sum up to the mth term or till the error tolerance is met.
 
#include <iostream>
#include <cmath>  // needed for the exponential function exp( )
using namespace std;
int main ( )
{
        int k,      // loop index 
             m = 20; // maximum number of loops
        double x,   // value of x
             xk,     // x to the power k
             sum,    // sum of series
             dsum,   // keep tract of the next contribution to the sum
             fac,    // factorial of k: k!
             expx;   // exact value of exp(x)
        char key;   // character key to see if user wants to continue
        //cout.setf(ios::scientific);       // use scientific notation
        cout.setf(ios::fixed|ios::showpoint);   // fixed point & show decimal point
        cout.precision(6);          // show 6 decimal places
        do
        {
                sum = 1.0;  // reset sum to 1
                dsum = 1.0; // reset dsum to 1
                 xk = 1.0;   // reset xk to 1
                fac = 1.0;  // reset k! to 1
        
                cout << "Enter the value of x: ";
                 cin >> x;
                expx = exp(x);  // exact value for exp(x)
                for (k = 1; k <= m && fabs(dsum) > 1e-6; k++)
                {
                        xk *= x;            // compute x^k
                        fac *= double(k);   // compute k!
                        dsum = xk / fac;    // next contribution to the sum
                        sum += dsum;    // compute & accumulate x^k / k!
                        cout << k << ' ' << sum << ' ' << expx << endl;
                }
                cout << "Enter \'Y\' or \'y\' to continue,\n"
                            << "or any other key to quit: ";
                cin >> key;
        } while (key == 'Y' || key == 'y');
}// end of main
 - 
// Program to compute the exponential function of a real value x.
// Algorithm: uses the series representation of the exponential function:
// exp(x) = 1 + x + x^2/2! + x^3/3! + ... + x^m/m! + ...
// For given values of x and m, where m(=20) is the last term to be summed, 
// sum the series and compare with the exact result.
// Display the results for k=1, 2, ..., 20.
// Let the user input the value of x, and allow the user to re-calculate 
// for any other values of x.
// This second version stops summing the series as soon as we reach a term
// that contributes less than 1 part in a million to the series.
// Note that fabs(x) is a predefined function (in cmath) that 
// takes the absolute value of a float.
// Version 3: much more efficient handling of the basic loop.
 
#include <iostream>
#include <cmath>  // needed for the exponential function exp( )
using namespace std;
const double TOLERANCE(1e-6);     // sum is stopped when magnitude of new term < TOLERANCE
int main ( )
{
        int k,      // loop index 
             m = 20; // maximum number of loops
        double x,   // value of x
             sum,    // sum of series
             dsum,   // keep tract of the next contribution to the sum
             expx;   // exact value of exp(x)
        char key;   // character key to see if user wants to continue
        //cout.setf(ios::scientific);       // use scientific notation
        cout.setf(ios::fixed|ios::showpoint);   // fixed point & show decimal point
        cout.precision(6);          // show 6 decimal places
        do
        {
                sum = 1.0;  // reset sum to 1
                dsum = 1.0; // reset dsum to 1
        
                cout << "Enter the value of x: ";
                 cin >> x;
                expx = exp(x);  // exact value for exp(x)
                for (k = 1; k <= m && fabs(dsum) > TOLERANCE; k++)
                {
                        dsum *= x / k;    // next contribution to the sum
                        sum += dsum;    // compute & accumulate x^k / k!
                        cout << k << ' ' << sum << ' ' << expx << endl;
                }
                cout << "Enter \'Y\' or \'y\' to continue,\n"
                            << "or any other key to quit: ";
                cin >> key;
        } while (key == 'Y' || key == 'y');
}// end of main