CS (151) COURSE - INTRODUCTION TO PROGRAMMING C++

CS (151) - INTRODUCTION TO PROGRAMMING C++

Teacher: Dr. Shrestha



Fall Semester, 2000

Class hour: 5:00 - 10:00 Friday

Materials for November 17, 2000
*****************************

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

Control Structures


Save days' work in your diskette !

    Examples Using the "for" structure

    Vary the control variable from 1 to 100 in increments of 1.
    for ( int i = 1; i <= 100; i++ )

    Vary the control variable from 100 to 1 in increments of -1 (decrements of 1)
    for ( int i = 100; i >=1; i--)

    Vary the control variable from 7 to 77 in steps of 7
    for ( int i = 7; i <= 77; i +=7 )

    Vary control variable from 20 to 2 in steps of -2
    for ( int i = 20; i>=2; i =-2 )

    Vary control variable over the following sequence of values:
    2, 5, 8, 11, 14, 17, 20.
    for ( int j = 2; j <=20; j +=3 )

    Vary the control variable over the following sequence of values:
    99, 88, 77, 66, 55, 44, 33, 22, 11, 0.
    for ( int j = 99; j >= 0; j -= 11 )

    EXAMPLE

    //C++ Program using "for" structure to sum all the even 
    //integers from 2 to 100.
    #include <iostream.h>
    

    int main() { int sum = 0;

    for ( int number = 2; number <= 100; number += 2 ) sum += number;

    cout << "Sum is " << sum << endl;

    return 0; }

    Example

    	A person invests $ 1000.00 in a savings account 
    yielding 5 % interest. Assuming that all interests is left 
    on deposit in the account, calculate and print the amount 
    of money in the account at the end of each year for ten 
    years. Use the following formula for determining these 
    amounts:

    n a = p(1 + r)

    where p = original amount invested (Principal), r = annual interest rate, n = number of years, and a = amount on deposit at the end of the nth year.

    C++ PROGRAM

    //Calculation of Compound Interest #include <iostream.h> #include <iomanip.h> #include <math.h>

    int main() { // The type "double" is a floating-point type much //like "float" but with greater precision.

    double amount, // amount on deposit principal = 1000.0,// starting principal rate = .05; // interest rate

    cout << "Year" << setw( 21 ) << "Amount on deposit" << endl;

    for ( int year = 1; year <=10; year++ ) { // function "pow( x, y ) calculates the // value of "x" raised to the "yth" power. // This function requires "math.h" file. amount = principal * pow( 1.0 + rate, year ); cout << setw( 4 ) << year // This means a field width of 4. << setiosflags( ios::fixed | ios::showpoint ) << setw( 21 ) << setprecision( 2 ) << amount << endl; }

    return 0; }

    ASSIGNMENT: Peter Minuit Problem Legend has it that in 1626 Peter Minuit purchased Manhattan for $ 24.00 in barter. Did he make a good investment? To answer this question, modify the above compound interest program to begin with a principal of $24.00 and to calculate the amount of interest on deposit if that money had been kept on deposit until this year (372 years from 1998). Run the program with interest rates of 5%, 6%, 7%, 8%, 9%, and 10% to observe the wonders of compound interest.

    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.

    C++ Program

    // Counting letter grades
    
    # include <iostream.h>
    
    int main()
    {
        int grade,		// one grade
    	aCount = 0,	// number of A's
    	bCount = 0,	// number of B's
    	cCount = 0,	// number of C's
    	dCount = 0,	// number of D's
    	fCount = 0;	// number of F's
    
        cout << "Enter the letter grades." << endl
    	 << "Enter the EOF character to end input." << endl;
    
        while ( ( grade = cin.get() ) !=EOF ) {
    
    	// EOF is system dependent. Try CTRL-Z
    
    	switch ( grade ) { // switch nested in while
    		
    	// case and default need a colon :, 
    	// not a semicolon.
    
    	case 'A':	// grade was uppercase 'A'
    	case 'a':	// or lowercase 'a'
    	++aCount;
    	break;		// necessary to exit switch
    
    	case 'B':	// grade was uppercase 'B'
    	case 'b':	// or lowercase 'b'
    	++bCount;
    	break;
    
    	case 'C':	// grade was uppercase 'C'
    	case 'c':	// or lowercase 'c'
    	++cCount;
    	break;
    
    	case 'D':	// grade was uppercase 'D'
    	case 'd':	// or lowercase 'd'
    	++dCount;
    	break;
    
    	case 'F':	// grade was uppercase 'F'
    	case 'f':	// or lowercase 'f'
    	++fCount;
    	break;
    
    	// for additional protection
    
    	case '\n':	// ignore newlines,
    	case '\t':	// tabs,
    	case ' ':	// and spaces in input
    	break;
    
    	default:	// catch all other characters
    
    	   cout << "Incorrect letter grade entered."
    		<< "Enter a new grade." << endl;
    	   break;	// optional
    	}
    	}
       cout << "\n\nTotals for each letter grade are:"
    	<< "\nA: " << aCount
    	<< "\nB: " << bCount
    	<< "\nC: " << cCount
    	<< "\nD: " << dCount
    	<< "\nF: " << fCount << endl;
    return 0;
    }
    

    In the program, the value of the assignment "grade = cin.get()" is compared with the value of EOF (means end-of-file). The user types a system-dependent keystroke combination to mean "end-of-file", CTRL-Z for MS-DOS.

    THE do/while REPETITION STRUCTURE
    - similar to "while" structure

    Example>

    // Using the do/while repetition structure 
    
    #include <iostream.h>
    
    int main()
    {
    	int counter = 1;
    
    	do {
    		cout << counter << "  ";
    	} while ( ++counter <=10 );
    
    	cout << endl;
    
    	return 0;
    }
    

    THE break AND continue STATEMENTS

    The "break" and "continue" statements alter the flow of control. The "break" statement when executed in a 'while, for, do/while, or switch' structure causes immediate exit from that structure. Program execution continues with the first statement after the structure. Common uses of "break" statements are to escape from a loop, or to skip the remainder of a switch structure.

    The "continue" statement, when executed in a 'while, for, or do/while' structure skips the remaining statements in the body of that structure, and proceeds with the next iteration of the loop.

    Example

    //Using the break statement in a for structure
    
    #include <iostream>
    
    int main()
    {
    	// x declared here so it can be used after
            // the loop.
         int x;
    
         for ( x = 1; x <= 10; x++ ) {
    
    	if ( x == 5 )
    	    break; // break loop only if x is 5
    
         cout << x << " ";
         }
         cout << "\nBroke out of loop at x of " << x 
              << endl;
         return 0;
    }
    ------------------------------------------------------------
    // Using the continue statement in a for structure
    
    #include <iostream>
    
    int main()
    {
      for ( int x = 1; x <= 10; x++ ) {
    
    	if ( x == 5 )
    	  continue; // skip remaining code in loop
    		    // only if x is 5
    
    	cout << x << " ";
         }
      cout << "n\Used continue to skip printing the value 5"
           << endl;
      return 0;
    }
    

    LOGICAL OPERATORS

    logical AND - &&
    example
    if (gender == 1 && age >= 65 )
    ++seniorFemales;

    logical OR - ||
    example
    if ( semesterAverage >=90 || finalExam >= 90 )
    cout <<"Student grade is A" ,, endl;

    logical NOT - !
    example
    if ( !( grade == sentinelValue ) )
    cout << "The next grade is " << grade << endl;

    **********************************************************
    REMMEMBER IN C++, EQUALITY is == AND ASSIGNMENT is =
    **********************************************************

    CHAPTER (3) - FUNCTIONS

    Modules in C++ are called 'functions' and 'classes'.Some of the functions are the standard library functions while some of them are programmer-defined functions.

    Math library functions
    Here x and y are of type "double"

    sqrt( x )- square root of x
    sqrt( 900.0 ) is 30.0

    pow( x, y )- x raised to power y
    pow( 2, 3 ) is 8.0

    ceil( x )- rounds x to the smallest integer not less than x
    ceil( 9.2 ) is 10.0

    fabs( x )- absolute value of x
    fabs( 2.3) is 2.3

    floor( x )- rounds x to the largest integer not greater than x
    floor( 9.2 ) is 9.0

    fmod( x, y )- remainder of x/y as a floating point number
    fmod( 2.5, 1.5 ) is 1.0

    FUNCTIONS

    Functions allow the programmer to modularize a program. All variables declared in function definitions are local variables which means they are known only in the function in which they are defined.

    Customized Functions

    Consider a program with a user-defined function "square" that calculates the squares of the integers from 1 to 10

    //Creating and using a programmer-defined function #include <iostream.h> int square( int ); // function prototype int main() { for ( int x = 1; x <= 10; x++ ) cout << square( x ) << " "; cout << endl; return 0; } // Function definition int square( int y ) { return y * y; }

    The format of a function definition is

    return-value-type function-name( parameter list )
    {
    declarations and statements
    }

    Consider a programmer-defined function "maximum" that determines and returns the largest of three integers. The three integers are input. Next, the integers are passed to "maximum" which determines the largest integer. This value is returned to "main" by the "return" statement in "maximum". the value returned is assigned to the variable "largest", which is then printed.

    // Finding the maximum of three integers #include <iostream.h> int maximum( int, int, int ); // function prototype int main() { int a, b, c; cout << "Enter three integers: "; cin >> a >> b >> c; // a, b, and c below are arguments to the maximum // function call cout << "Maximum is: " << maximum( a, b, c ) << endl; return 0; } // Function maximum definition // p, q, and r below are parameters to the "maximum" int maximum( int p, int q, int r ) { int max = p; if ( q > max ) max = q; if ( r > max ) max = r; return max; }

    FUNCTION PROTOTYPES
    -Important feature of C++ programming
    -The function prototype for maximum is "int maximum( int, int, int )
    -This prototype states that "maximum" takes three arguments of type "int", and returns a result of type "int". Notice that this function prototype is the same as the header of the function definition of "maximum" except the names of the parameters (p,q,and r) are not included.


THANKS FOR STOPPING BY !

THINGS CHANGE - COME BACK AGAIN !

TAKE CARE !

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