CS (151) - INTRODUCTION TO PROGRAMMING C++

Teacher: Dr. Shrestha



Fall Semester, 2000

Class hour: 5:00 - 10:00 Friday

Materials for November 10, 2000
*****************************

Chapter (2) (Contd.)
********************

Control Structures


Save days' work in your diskette !

    SENTINEL-CONTROLLED REPETITION
    - A repetition procedure for solving a problem by using a sentinel value also called a signal value, a dummy value, or a flag value to indicate "end of data entry".

    - Sentinel-controlled repetition is often called indefinite repetition because the number of repetitions is not known before the loop begins executing.

    EXAMPLE
    - Develop a class averaging program that will process an arbitrary number of grades each time the program is run.

    IDEA
    - The sentinel value must be chosen so that it cannot be confused with an acceptable input value, As grades on a quiz are normally nonnegative integers, -1 is an acceptable value for this problem. Thus, a run of the class average program might process a stream of inputs such as 90, 85, 95, 70, and -1. The program would then compute and print the class average for the grades 90, 85, 95, and 70. The program will see the flag -1 not as a grade input but as a signal to indicate end of the grade data.

    PSEUDOCODE
    - Development of well-structured programs is usually done using a method called top-down, stepwise refinement as is done in the pseudocode below.

    Initialize total to zero
    Initialize counter to zero

    Input the first grade (possibly the sentinel)
    While the user has not as yet entered the sentinel
    Add this grade into the running total
    Add one to the grade counter
    Input the next grade (possibly the sentinel)

    If the counter is not equal to zero (to avoid division by zero)
    Set the avergae to the total divided by the counter
    Print the average
    else
    Print "No grades were entered"

    C++ PROGRAM

    // Class average program with sentinel controlled repetition.
    # include <iostream.h> # include <iomanip.h> // This preprocessor directive is needed to produce parametrized stream // manipulator i.e. print results to a desired number of precision, The // default is 6 digits.

    int main()
    {
    int total, // sum of grades
    gradeCounter, // number of grades entered
    grade; // one grade
    float average; // average of grades

    // initialization phase
    total = 0; // Clear total
    gradeCounter = 1; // prepare to loop

    // processing phase
    cout << "Enter grade, type -1 to indicate the end: ";
    cin >> grade; // input grade

    while ( grade != -1) { // loop until -1 is entered
    total = total + grade; // add grade to total
    gradeCounter = gradeCounter + 1; // increment counter
    cout << "Enter grade, type -1 to indicate the end: ";
    // In a sentinel controlled loop, the prompts requesting data // entry should explicitly remind the user what the sentinel // value is.
    cin >> grade;
    }

    // termination phase
    if ( gradeCounter != 0 ) {
    // A special operator called a cast operator will be used to handle // the average calculation. This results in a floating point value // for the average as desired.
    average = static_cast< float >( total ) / gradeCounter;
    cout << "Class average is " << setprecision( 2 )
    // Two digits of precision
    << setiosflags( ios::fixed | ios::showpoint )
    // This is a stream manipulator. This sets two output // formatting options because of | symbol.
    << average << endl;

    }
    else
    cout << "No grades were entered" endl;

    return 0; //indicate program ended successfully
    }

    The option "ios::fixed" causes a floating point value to be output in FIXED POINT FORMAT. The "ios::showpoint" option forces the decimal point and trailing zeros to print even if the value is a whole number amount such as 85.00.

    NESTED CONTROL STRUCTURE
    Examination Result Problem

    You have been given a list of 10 students. Next to each name is written a 1 if the student passed the exam and a 2 if the student failed. Write the program such that it analyzes the results of the exam as follows:

    (1) Input each test result (i.e. a 1 or a 2). Display the message "Enter result" on the screen each time the program requests another test result.
    (2) Count the number of test results of each type.
    (3) Display a summary of the test results indicating the number of students who passed and the number of students who failed.
    (4) If more than 8 students passed the exam, print the message "Raise tuition."

    Observations

    (1) The program must process 10 test results. A counter-controlled loop is to be used.
    (2) Each test result is a number - either a 1 or a 2. Each time the program reads a test result, the program must determine if the number is a 1 or a 2. We test for a 1 in our algorithm. if the number is not a 1, we assume that it is a 2.
    (3) Two counters are used - one to count the number of students who passed the exam and one to count the number of students who failed the exam.
    (4) After the program has processed all the results, it must decide if more than 8 students passed the exam.

    PSEUDOCODE

    Initialize passes to zero
    Initialize failures to zero
    Initialize student counter to one

    While student counter is less than or equal to ten
    Input the next exam result

    If the student passed
    Add one to passes
    else
    Add one to failures

    Add one to student counter

    Print the number of passes
    Print the number of failures

    If more than eight students passed
    Print "Raise tuition"

    C++ PROGRAM

    //Analysis of examination results
    #include <iostream.h>

    int main()
    {
    // initialize variables in declarations
    int passes = 0, // number of passes
    failures = 0, // number of failures
    studentCounter = 1, // student counter
    result; // one exam result

    // process 10 students; counter-controlled loop
    while ( studentCounter <=10 ) {
    cout << "Enter result (1=pass, 2=fail): ";
    cin >> result;

    if ( result == 1) // if/else nested in while
    passes = passes + 1;
    else
    failures = failures + 1;

    studentCounter = studentCounter + 1;
    }

    // termination phase
    cout << "Passed " << passes << endl;
    cout << "Failed " << failures << endl;

    if ( passes > 8 )
    cout ,, "Raise tuition " << endl;

    return 0;
    // successful termination
    }

    ASSIGNMENT OPERATORS
    The statement

    c = c + 3;

    can be abbreviated with the addition assignment operator += as

    c += 3;

    Any statement of the form

    variable = variable operator expression;

    where operator is one of the binary operators +, -, *, /, or %, can be written in the form

    variable operator= expression;

    INCREMENT AND DECREMENT OPERATORS

    If a varaible a is incremented by 1, the increment operator ++ can be used rather than the expressions c = c + 1 or c += 1.
    operator placed before the variable - preincrement or predecrement
    operator placed afte the variable - postincrement or post decrement
    ++a -> increment a by 1, then use the new variable of a in the expression in which a resides.
    a++ -> use the current value of a in the expression in which a resides, then increment a by 1.

    ESSENTIALS OF COUNTER-CONTROLLED REPETITION
    Counter-controlled repetition requires:
    1. The name of a control variable.
    2. The initial value of the control variable.
    3. The condition that tests for the final value of the control variable.
    4. The increment or decrement by which the control varaible is modified each time through the loop.

    Example

    //counter-controlled repetition
    # include <iostream.h>

    int main() { int counter = 1; //initialization

    while ( counter <= 10 ) { // repetition condition cout << counter << endl; ++counter; // increment } return 0; }

    THE for REPETITION STRUCTURE
    The for repetition structure handles all the details of counter-controlled repetition.

    Example

    // Counter-controlled repetition with the for structure
    3include <iostream.h>
    

    int main() { // Initialization, rewpetition condition, and incrementing // are all included in the for structure header.

    for ( int counter = 1; counter <=10; counter++ ) cout << counter << endl;

    return 0; }

    The general format for the for structure is
    for ( expression1; expression2; expression3)
    statement

    THE switch MULTIPLE-SELECTION STRUCTURE

    Occasionally, an algorithm will contain a series of decisions in which a variable or expression is tested separately for each of the constant integral values it may assume, and different actions are taken. C++ provides the switch multiple selection structure to handle such decision making.

    The switch structure consists of case labels, and an optional default case.


THANKS FOR STOPPING BY !

THINGS CHANGE - COME BACK AGAIN !

TAKE CARE !

AFTER TODAY'S CLASS IS OVER, LOOK AT THE ASSIGNMENT.