Notes N6

Math 10 -- D. C. Smolarski, S.J.
Santa Clara University, Department of Mathematics and Computer Science

[Return to Math 10 Homepage | Return to Notes Listing Page]

Contents


Multiple Alternatives

Edsger W. Dijkstra is sometimes referred to as the "father of structured programming." It is through his analysis of programs and languages in the 1960s that we now look at all programs in terms of three types of components:
  1. sequencing (i.e., the logical ordering of statements with the assumption that one action is completed before the next is begun);
  2. repetition (or looping) -- primarily referring to language structures that repeat an action a specified number of times or until a certain condition is achieved;
  3. choices between options -- primarily referring to language structures that permit the program to perform one set of statements (and ignore other options) based on some sort of condition.
C/C++ has a structure to choose between many alternatives:
        switch (expression)
        {
                case value1 :  statement(s);
                                        break;
                case value2 :  statement(s);
                                        break;
                case value3 :  statement(s);
                                        break;
                default            :  statement(s);
        }
NOTES:
  1. Expression can be of type char, integer or another "enumerated" type. Value1, etc. must be constants of the same type as expression.
  2. If the value of expression matches value1, then the statements after the colon following value1 are performed, and this is done only ONCE.
  3. The break statement commands the program flow to "break" completely out of the switch structure and continue with the next statement following the closing brace. If, at a given alternative, the actions statements are not concluded with a break statement, then the program flow will continue with the first statement in the next alternative. This is sometimes called the "fall-through" property.
  4. The fall through property enables the user to indicate multiple options by merely including several "case valuen :" options together (although the values may be different, each one must be preceded by a case and followed by a colon).
  5. The statements can be
            a)      single statement, e.g., a=b+c;
            b)      function call;
            c)      "null", e.g.   case  value2 : break;
            d)      multiple statements.
    
  6. value1, ... , valuen must be constants. A list of values may be included according to the style indicated above.
  7. Every possible value of expression should be listed as a possible alternative. If there are too many values to list or you wish to group certain values together as a final grouping, the default option may be included as the final line. (Note that the default option does not need a break to conclude its statements, since after its last statement, it will automatically fall through to the statement following the entire switch structure.

switch Example

Suppose you read in from a file a list of students' test scores and you want a program to translate a score (from 0 to 100) into a letter grade.
     {  int rank, score;
        ...

        rank = score / 10;
        switch (rank)
        {
           case 10 : cout << "score of 100 gets A+"  << endl;
                     break;
           case 9  : cout << "score of " << score << "gets A"  << endl;
                     break;
           case 8  : cout << "score of " << score << "gets B"  << endl;
                     break;
           case 7 : case 6 : cout << "score of " << score << "gets C"  << endl;
                     break;
           case 5 : case 4 : cout << "score of " << score << "gets D"  << endl;
                     break;
           default         : cout << "Please see the teacher" << endl;
        }

Functions -- Standard

In mathematics and in many applied fields, we occasionally use predefined functions, e.g., trig functions like sine, cosine, etc.

There are many predefined functions in C/C++. To use any, one needs to include the appropriate header file.

The most often math functions used (one needs the #include <math.h> statement) are as follows:

	sqrt(x)		square root
	sin(x)		sine - takes radians as the argument
	cos(x)		cosine - also takes radians
	floor(x)	truncates a real number to convert it to
				an integer value (drops the
				fractional part)
	fabs(x)		absolute value
	pow(x,y)	takes x to the power of y
We use these functions similar to the way we use functions in algebra, by enclosing the argument (input values) in parentheses after the function name.

EXAMPLE:

		c = sqrt(a*b);
		a = sin(alpha/2.0);
There also exist numerous other functions including many related to the strings of characters. Some of these functions are not that important for our purposes right now.

More on Programming Style

  1. Constants

    In C/C++, we can declare certain identifiers as constants. The constant declaration is usually placed along with the variable declarations and is similar to it.

    The general form is:

    const type identifier = value;

    It is permitted to reverse the order of the const and the type at the beginning of the declaration line.

    Constants are useful for repeatedly used concepts in the program which may be changed rarely.

    EXAMPLE:

    		const double pi  = 3.14159265;
    		const int maxnum = 100000;
    
    NOTE: a constant cannot be changed in a program (if this is tried, an error message will be given).

  2. Elegance and Efficiency

    "Elegance" usually refers to proofs which are simple and concise and solve a problem in a clear and complete manner. It may be hard enough to get a program running, and running correctly without having to worry about elegance, much less efficiency. But some small things can be pointed out.

    One small thing which can help the speed of a program is to take repeated unnecessary work out of loops.

    For example, instead of

    	for(num=1; num <=12; num++)
    	  {
    		miles = num * 5.0;
    		kilometers = miles * 8.0/5.0;
    		cout << miles  << kilometers << endl;
    	  }
    
    it is better to have
    	eightfifths = 8.0/5.0;
    	for(num=1; num <= 12; num++)
    	  {
    		miles = num * 5.0;
    		kilometers = miles * eightfifths;
    		cout << miles  << kilometers << endl;
    	  }
    
  3. Modularity

    One important concept in contemporary programming is modularity -- writing programs in small segments. In general, independent subsections are called subprograms. In Pascal, they are called "PROCEDURES" if they do NOT return a single value and "FUNCTIONS" if they do. In FORTRAN, they are called "SUBROUTINES" if they do NOT return a single value and "FUNCTIONS" if they do. In C/C++, they are always called "FUNCTIONS."

    Subprograms can be used in many ways, but their main usefulness is two-fold:

    1. If something has to be done more than once at different points of the program, the code can be written as a procedure and then invoked multiple times, when needed.

    2. A large program can be written as a number of subprograms, each of which can be tested separately, and when they are joined together, they make the total program much more readable.

    Subprograms are written with the main program, and are activated, executed or "called" by another section of the code (the main program or another subprogram).


This page is maintained by Dennis C. Smolarski, S.J. dsmolarski@math.scu.edu
© Copyright 1997, 1998, Dennis C. Smolarski, SJ, All rights reserved. Last changed: 5 December 1998.