5: More Control Statements

What We Will Cover


Continuations

Homework Questions?

Questions from last class?

Compiler Messages and Debugging

Counter-controlled repetition requires:

  1. A named control variable and initial value.
  2. A control variable increment.
  3. A condition that tests for the final value of the control variable.
  4. All of the above.

5.1: More Control Statements

Objectives

At the end of the lesson the student will be able to:

  • Use switch statements for branching
  • Use do-while statements to control loops
  • Use for statements to control loops
  • Use break and continue statements with loops
  • In this section, we learn about the rest of C++'s control statements
  • These statements do not add new capabilities
  • Just provide alternate ways of performing some tasks
  • Since C++ code has them, you need to know how to use them

5.1.1: switch Statements

  • The switch statement provides an alternative to an if-else chain
  • Executes a section of code depending on value of a variable
  • General form:
  • switch (integerExpression) {
       case label1:
          statements
          break;
       case label2:
          statements
          break;
       ...
       case labeln:
          statements
          break;
       default:
          statements
          break;
    }
    
  • Keyword switch identifies the start of the switch statement
  • Expression in parenthesis is evaluated for comparison to each case label
    • integerExpression must evaluate to an integer
    • Otherwise a compilation error occurs
  • Within a switch statement, keyword case labels each entry point into the code
    • Code executes if integerExpression matches the case label value
    • Execution starts with the statement immediately following the match
  • Any number of case labels can be placed in any order
  • Any value that does not match starts executing with the statement after default
  • Execution continues until the end of the switch statement or a break statement
  • The break statement causes an immediate exit from the switch statement
  • Just as case identifies possible starting points, break determines end points

For Example:

#include <iostream>
using namespace std;

const int PARCEL_POST = 0;
const int UPS = 1;
const int FED_EX = 2;

int main() {
    int shippingOption = UPS;
    cout << "Enter a shipping option: ";
    cin >> shippingOption;

    switch (shippingOption) {
        case PARCEL_POST:
            cout << "Delivery in two weeks.\n";
            break;
        case UPS:
            cout << "Delivery in three days.\n";
            break;
        case FED_EX:
            cout << "Overnight delivery.\n";
            break;
        default:
          cout << "It may never get there!\n";
    }
    cout << "Ship it!\n";

    return 0;
}

  • Notice that each case other than the last contains a break statement
  • Ensures that the switch statement is exited after a matching case is found

When to Use switch Statements

  • You can only use switch statements with integer expressions
  • Inherently less useful than if-else statements
  • Syntax is no clearer than if-else statements
  • Thus, no real need to ever use a switch statement

5.1.2: Conditional (Ternary) Operators

  • Provides a compact if-else structure
  • Syntax:
  • operand1 ? operand2 : operand3;
    
  • First operand must be a conditional expression that evaluates to true or false
  • If operand1 is true, return operand2; otherwise return operand3.

For Example

  • Following is an if-else statement
  • string outMessage;
    int celsius;
    cout << "Enter the Celsius temperature: ";
    cin >> celsius;
    
    if (celsius >= 100) {
        outMessage = "Boiling!";
    } else {
        outMessage = "Not boiling";
    }
    
    cout << outMessage << endl;
    
  • Equivalent using the conditional operator
  • string outMessage;
    int celsius;
    cout << "Enter the Celsius temperature: ";
    cin >> celsius;
    
    outMessage = (celsius >= 100)
        ?  "Boiling!"
        : "Not boiling";
    
    cout << outMessage << endl;
    

When to Use Conditional (Ternary) Operators

  • Rarely used in professional programing
  • Almost always clearer to use if-else statements

5.1.3: do-while Statements

  • Variation of the while loop
  • Syntax:
  • //Initialization
    ...
    do {
       //loop body
       ...
    } while (loopTest); //loop condition
    
  • Initialization code may precede loop body
  • Loop test is after the loop body
  • Loop must execute at least once (minimum of at least one iteration)
  • Use when you want to force a minimum of one iteration

Validity Checks

  • You can use do-while statements to filter user input
  • For example, assume we need a positive value from the user:
#include <iostream>
using namespace std;

int main() {
    //Loop initialization
    double input = 0.0;
    do {
        //loop body
        cout << "Enter a positive number: ";
        cin >> input;
        if (input < 0.0) {
            cout << "You must enter a positive number!\n";
        }
    } while (input < 0.0); //loop condition
    cout << "You entered: " << input << endl;

    return 0;
}

When to Use do-while Statements

  • Sometimes used in professional programming
  • You can accomplish the same control flow with a while loop
  • You can use it whenever you want to force a minimum of one iteration

5.1.4: for Statements

  • Provides a more compact loop
  • Syntax:
  • for (initializer; condition; increment) {
       //loop body
       ...
    }
    
  • Initialization, loop-test, and increment-expression are part of the syntax
  • initializer expression: defines the initial value used to control the loop
  • condition expression: determines when the loop will end
  • increment expression: evaluated at the end of each loop iteration
  • Statements to repeat are enclosed in curly brackets
  • Execution sequence as follows:
  1. When for statement reached -- initialization executes
  2. Check if condition is true
    • if true then continue with Step 3
    • Otherwise, continue with Step 6
  3. Execute block containing the loop body
  4. When end of loop body is reached, execute the increment
  5. Return to Step 2
  6. Loop is finished: continue with statements after the loop

Counter-Controlled-Loop Example

    #include <iostream>
    using namespace std;
    
    int main() {
        int count;
        for (count = 0; count < 5; count++) {
            cout << count << endl;
        }
    
        return 0;
    }
    
  • Note that code is indented in the loop body for readability

Counting Down

  • Can also count downwards
  • Positive numbers step higher (+inf) and negative numbers step lower (-inf)
  • What is displayed with the following?
  • #include <iostream>
    using namespace std;
    
    int main() {
        int count;
        for (count = 5; count > 0 ; count--) {
            cout << count << endl;
        }
    
        return 0;
    }
    

When to Use for Statements

  • Very often used in professional programming
  • Especially useful for counter-controlled loops

5.1.5: break and continue Statements

  • break and continue statements transfer control to another part of a program
  • Within a loop break statements an immediate exit
  • Transfers control to the statement following the loop
  • Provides a way to break out of an intentional infinite loop
  • #include <iostream>
    using namespace std;
    
    int main() {
        int count = 0;
        while (true) {
            count++;
            if (count == 3) {
                continue;
            }
            cout << count << endl;
            if (count >= 5) {
                break;
            }
        }
        cout << "After count= " << count << endl;
    }
    
  • continue statement transfers control to the loop test
  • Causes the loop to skip the rest of the current iteration
  • When executed within a loop, starts the next iteration of the loop immediately

When to Use break and continue Statements

  • Use break statements in switch statements only
  • Never use break in looping constructs
    • Poor coding habit
    • Should only have one exit point in a loop
  • In this course, you will never need to write infinite loops
  • You do not need to use continue statements either
  • You can accomplish the same operation other ways

5.1.6: Summary

  • C++ provides many control statements
  • They provide alternatives to the basic statements covered earlier
  • Of those covered today, the most useful is the for loop
  • Provides a compact looping structure often used for counter-controlled repetition

Exercise 5.1

  1. Start a text file named exercise5.txt.
  2. Prepare the exercise header as described in the HowTo on submitting exercises
  3. Label this exercise: Exercise 5.1
  4. Submit all exercises for today's lesson in one file unless instructed otherwise
  5. Complete the following and record the answers to any questions in exercise5.txt.

Specifications

#include <iostream>
using namespace std;

int main() {
    int count = 0; // initialize counter
    while (count < 5) { //loop condition
        //loop body
        cout << count << endl;
        count++; // adjust the counter
    }
    cout << "After loop count = " << count << endl;

    return 0;
}
  1. Convert the above code to use a for loop rather than a while loop.
  2. Turn in the modified code along with your exercise5.txt file
  3. Record answers to the following questions in exercise5.txt.
  4. Q1: What is the chief advantage of using a for loop?

    Q2: The for loop seems most appropriate for which type of looping pattern?

5.2: Processing Strings

Objectives

At the end of the lesson the student will be able to:

  • Compare string equality
  • Compare strings lexicographically
  • Use at() to extract characters from a string

5.2.1: String Comparison Operators

  • Comparison operators work with string objects
  • == returns true if two string objects contain the same characters in the same order
  • Also, you can use <, >, <=, >= to compare string objects
  • Objects of type string are compared using lexicographic order
  • In ASCII:
    • Digits are stored in order from 0 to 9
    • Letters of the alphabet are stored in order from A to Z
    • A blank precedes (is less than) all letters and digits
    • Digits come before lowercase letters
    • Lowercase letters come before uppercase letters
  • When two strings are compared lexicographically, their individual letter are compared a pair at a time
  • If no differences are found, the strings are equal
  • For example:
  • string s1, s2;
    s1 = "Goodbye";
    s2 = "Goodness";
    if (s1 < s2) {
        cout << "less than\n";
    } else {
        cout << "not less than\n";
    }
    
  • If a difference is found, string with the lower first letter is considered the smaller string
  • In the above example, "Goodbye" is less than "Goodness" because 'b' is less than 'n'

5.2.2: Converting Strings to Numbers

  • "1234" is a string of characters
  • 1234 is a number
  • Sometimes you need to convert C-strings to numbers
  • For instance, you may need to read string data because:
    • Reading money may involve a dollar sign
    • Reading percentages may involve a percent sign
  • To read a numbers as characters:
    1. Read input as characters string
    2. Remove unwanted characters
    3. Use a conversion function to convert the string to a numeric value
  • The conversion functions are found in the library cstdlib
  • To use the functions use the include directive
  • #include <cstdlib>
  • Included automatically with our version of g++
  • The most used functions: atoi(), atol() and atof()
  • Function atoi() to converts a string to an int value
  • int x;
    x = atoi("1234");  // returns 1234
    cout << x << endl;
    x = atoi("#1234"); // returns 0 because # is not a digit
    cout << x << endl;
    
  • Function atol() to converts a C-string to a long value
  • long y = atol("1234"); // returns 1234 as a long
    cout << y << endl;
    
  • Function atof() to converts a C-string to a double value
  • double z = 0.0;
    z = atof("9.99");  // returns 9.99
    cout << z << endl;
    z = atof("$9.99"); // returns 0 because $ is not a digit
    cout << z << endl;
    

Converting String Variables

  • To convert string variables to numbers, you must use the c_str() function
  • Required because conversion functions were designed to work with C-strings
  • We will cover C-strings later in the course
  • double z = 0.0;
    string text = "9.99";
    z = atof(text.c_str());
    cout << (z + 1 ) << endl;
    

5.2.3: Converting Numbers to Strings

  • The easiest way to convert numbers to strings is to use a stringstream
  • A stringstream class allows us to manipulate string like they were cout and cin
  • To make use of stringsteam you will need to include:
    #include <sstream>
  • For example:
  • double num;
    cout << "Enter a number: ";
    cin >> num;
    stringstream s;
    s << num;
    string myStr = s.str();
    cout << myStr << endl;
    cout << "The length of " << myStr << " is " << myStr.length() << endl;
    

5.2.4: Using at() in Loops

  • Recall that the string function at(int) returns a character at the specified index
  • With at(), we can process strings one character at a time using a loop
  • string msg = "Hello!";
    int index = 0;
    while (index < msg.length()) {
        cout << msg.at(index) << endl;
        index++;
    }
    
  • Once extracted, you can work with the char value directly

5.2.5: Summary

  • You can use comparison operators on strings just like on numbers
  • To convert strings to numbers, use the atoi(), atol() and atof() functions
  • To convert string variables to numbers, you must use the c_str() function as well
  • double z = 0.0;
    string text = "9.99";
    z = atof(text.c_str());
    cout << (z + 1 ) << endl;
    
  • Also, you can process strings using loops
  • String function at() extracts characters from a string
  • You can then work with char values

Exercise 5.2

Modify the following guessing-game program to correctly test the guess provided by the user. Save your modified program along with this weeks exercises.

#include <iostream>
using namespace std;

const string correctWord = "hello";

int main() {
    string guess;
    cout <<  "I'm thinking of a word with"
         << correctWord.length()
         << " letters.\nCan you guess it?\n";
    cin >> guess;

    // Insert test condition in place of true
    if (true) {
        cout << "*** Correct! ***\n";
    } else {
        cout << "Sorry, that is not correct.\n";
    }
    return 0;
}

5.3: Using Functions

Objectives

At the end of the lesson the student will be able to:

  • Call predefined functions
  • Generate random numbers

5.3.1: About Functions

Function -- a subprogram (method, procedure or subroutine) that executes a piece of code when called.

  • C++ comes with libraries of predefined functions such as sqrt
    • sqrt(9.0) is a function call
    • A function call can be used like any expression
  • Predefined functions are found in libraries
  • Libraries must be "included" in a program
  • #include <cmath>
  • Newer standard libraries, such as cmath, also require the directive
  • using namespace std;

5.3.2: Calling Functions

  • Function calls are analogous to a boss-worker relationship
  • The boss (calling function) asks a worker (called function) to complete a task
  • You use function calls to invoke a function
  • You use arguments to send information to a function
  • double result = pow(2.0, 3);  // result is 8.0
    cout << result << endl;
    
    double num = -2.0;
    double value = abs(num);      // value gets 2.0
    cout << value << endl;
    
  • Functions may or may not return a result to the calling function
  • A function we have used before that did not return a value is getline()
  • getline(cin, line);
  • After the function is finished, the program continues at the line after the call
  • You can use a function anyplace where it is legal to use its return type

5.3.3: Generating Random Numbers

  • As an example of function calls, let us look at random numbers
  • Random numbers are a series of numbers whose order cannot be predicted
  • Many computational problems need to use random numbers
  • Hard to find truly random numbers, even in real life
    • Dice never perfect
    • Cards never shuffled completely randomly
    • Computers can only handle numbers within a finite range and limited precision
  • Best that can be done in most cases is generate psuedorandom numbers
    • Sufficiently random for the task at hand
  • rand() is a library function that produces series of psuedorandom numbers
    • Range is 0 up to and including RAND_MAX
    • Returns an int value

Initializing the Random Number Sequence

  • To make the random numbers more random, you need to "seed" the random number generator
  • Use srand() to initialize the random sequence
  • For example:
  • srand(time(NULL));
  • The expression time(NULL) returns the number of seconds since January 1, 1970

Scaling and Shifting

  • Since the range of rand() is between 0 and RAND_MAX, will need to scale for your application
  • Also may need to shift the starting point of the numbers
  • General form for producing integer random numbers for an application:
  • shiftingValue + rand() % scalingFactor;
    
  • For example, to simulate a single die with random numbers:
  • int die = 1 + rand() % 6;
    cout << die << endl;
    

5.3.4: Dice Simulation

  • Let us use random numbers to simulate die rolling
  • #include <iostream>
    #include <cstdlib>
    using namespace std;
    
    int main(void) {
        srand(time(NULL));
    
        int die1 = 1 + rand() % 6;
        int die2 = 1 + rand() % 6;
        cout << "You rolled a " << die1
             << " and a " << die2 << endl;
    
        return 0;
    }
    
    
  • What would you change to roll the two dice 10 times?

5.3.5: Summary

  • A function is a block of code get executed when called
  • C++ has many predefined functions in several libraries
  • Libraries must be "included" in a program
  • #include <cmath>
  • Newer standard libraries, such as cmath, also require the directive
  • using namespace std;
  • Some of the library functions generate "random" numbers
  • We can use these functions to simulate the rolling of a die
  • int dieFace = 1 + rand() % 6;
    cout << dieFace << endl;
    

Exercise 5.3

  1. Label this exercise: Exercise 5.3
  2. Submit all exercises for this lesson in one file unless instructed otherwise
  3. Complete the following and record the answers to any questions in exercise5.txt.

Specifications

  1. Write a program that simulates rolling two dice.
  2. Use a loop to roll the two dice 10 times, displaying the output each time.
  3. Submit your final program along with your exercise5.txt file.

5.4: Coding Functions

Objectives

At the end of the lesson the student will be able to:

  • Declare and call functions
  • Pass values to functions
  • Return a value from a function

5.4.1: Declaring and Defining Functions

Why Write Functions?

  • Functions allow grouping of related code that performs specific task
  • Aids in structuring code
  • Makes program development more manageable
  • Makes it easier to reuse sections of code
  • Rule of thumb: If you repeat the same sequence of 3 or more lines more than once, you should create a function for the task performed.

  • Functions allow you to break big problems down into smaller subproblems
  • After solving the subproblems, all you need to do is fit the pieces together

Coding Functions

  • Two parts to defining your own functions
    1. Function declaration (prototype)
    2. Function definition
  • Function prototype syntax:
  • returnType functionName(parameterList);
  • Function definition syntax:
  • returnType functionName(parameterList) {
        // statements
    }
    
  • Both begin with the data type of the value that will be returned
    • Can be any primitive (char, int, double, etc.) or class (string, etc.) type
    • When no values are returned, use the special type: void
  • After specifying the data type, give the function a name
  • Following the name, add a set of parentheses ()
  • Within parenthesis are the parameters received by the function
  • Function prototypes end in a semi-colon ';'
  • Function definitions have a set of curly braces {...}
  • Code executed by the function is enclosed in the curly braces

For Example

  • Following code has three functions
  • Functions prototypes must precede a call to the function
  • #include <iostream>
    using namespace std;
    
    // Function declaration (prototype)
    double square(double x);
    
    // Function declaration (prototype)
    void showResults(double result);
    
    int main() {
        double result = square(5);
        showResults(result);
        return 0;
    }
    
    // Function definition
    double square(double x) {
        return x * x;
    }
    
    // Function definition
    void showResults(double result) {
        cout.setf(ios::fixed);
        cout.setf(ios::showpoint);
        cout.precision(1);
        cout << "The result is: " << result << endl;
    }
    
    

  • Function main calls function square, passing an argument of 5
  • Function square takes the argument, computes the square and returns the result
  • Programming style: note the placement of the curly braces

Programming Style: Function Naming Conventions

  • Use verbs to name functions, since they perform an action
  • Start function names with a lower case letter
  • Two common naming formats you may use:
    1. Start with a lower-case letter and use uppercase letters as separators. Do not use underbars ('_').
    2. int myFunction()
    3. Use all lower case letters and use underbars ('_') as separators.
    4. int my_function()
  • Function Comment Block: block comments before function prototypes
  • OK if formal parameter names are the same as argument names

5.4.2: Passing Values

  • Passing values to functions increases their usefulness and flexibility
  • Input values for functions are called arguments or passed values
    • Within the function, the values that are passed are called parameters
  • You can pass zero, one or more arguments to a function
  • Definition of function must specify data types and names
  • Separate multiple parameters with a comma
  • returnType functionName(Type1 param1, Type2 param2, ...) {
        ...
    }
    
  • The calling function must use values of the same data type and in the same order

For Example

#include <iostream>
using namespace std;

// Function prototype
long pow(int base, int exponent);

int main() {
    long value = pow(2, 3);
    cout << value << endl;
    return 0;
}

long pow(int base, int exponent) {
    if (exponent == 0) {
        return 1;
    }
    int loopCounter = 1;
    long result = base;
    while (loopCounter < exponent) {
        result = result * base;
        loopCounter++;
    }
    return result;
}

Common Pitfall

  • Common Mistake: declaring parameters 'again' inside a function:
  • double pow(int base, int exponent) {
        int loopCounter;  // local variable
        int base;         // NO!
    }
    
  • Compiler error results: "Redefinition error"
  • Paramters ARE like local variables
  • But paramters are initialized from arguments in the function call

5.4.3: Returning a Value

Return Statement

  • Functions that return a value must execute a return statement
  • Must return a value unless defined with a void return-type
  • For example:
  • #include <iostream>
    using namespace std;
    
    // Function declaration (prototype)
    double square(double x);
    
    // Function declaration (prototype)
    void showResults(double result);
    
    int main() {
        double result = square(5);
        showResults(result);
        return 0;
    }
    
    // Function definition
    double square(double x) {
        return x * x;
    }
    
    // Function definition
    void showResults(double result) {
        cout.setf(ios::fixed);
        cout.setf(ios::showpoint);
        cout.precision(1);
        cout << "The result is: " << result << endl;
    }
    
    

  • Function square uses a return statement because it returns a value
  • Function showResults() does not return a value
    • Return statement is optional if no value is returned
    • Return jump occurs automatically at the end of the function

Exiting Early

  • Sometimes you do not want to execute all the code in a function
  • You can use return statement to stop execution and return from anywhere
  • Control returns immediately from a function whenever a return is reached

5.4.4: Functions Calling Functions

  • Functions may call other functions
  • Within the body of the function, you can code another function call
  • We are already doing this when main() calls another function
  • You must first declare the function before you call it
    • The compiler works sequentially from start to finish
    • If it does not known about a function name, it gets stuck
  • Function declarations are usually grouped before main
    • Or even placed in another file
    • Will cover how to do this later
  • A function can even call itself
    • Known as recursion
    • Will cover later in the course

5.4.5: Tracing Function Calls

  • When functions call functions, you still need to follow the flow of execution
  • A function call transfer control to the first statement of the called function
  • When a return point is reached, control passes back to the point right after the function call
    • Return statement
    • End of function
  • If the function returns a value, that value is substituted for the function call
  • Let's trace the flow in the following code:
  • #include <iostream>
    using namespace std;
    
    // Function prototype
    long pow(int base, int exponent);
    
    int main() {
        long value = pow(2, 3);
        cout << value << endl;
        return 0;
    }
    
    long pow(int base, int exponent) {
        if (exponent == 0) {
            return 1;
        }
        int loopCounter = 1;
        long result = base;
        while (loopCounter < exponent) {
            result = result * base;
            loopCounter++;
        }
        return result;
    }
    

5.4.6: Local Variables and Scope

  • Scope determines where you can access a variable
  • Variables defined in functions can only be accessed within that function
  • Cannot be used from outside the function
  • Variables in main are not available in another function
  • Variables in another function are not available in main
  • Also note that parameters are just local variables with a special initialization mechanism

For Example

  • What is displayed by the following code??
  • #include <iostream>
    using namespace std;
    
    // Function prototype
    void square(double x);
    
    int main() {
        double x2 = 2.0;
        square(x2);
        cout << "x^2 = " << x2 << endl;
        return 0;
    }
    
    void square(double x) {
        double x2 = x * x;
        cout << "x^2 = " << x2 << endl;
    }
    
  • How could you fix the problem?

Global Named Constants Revisited

  • Available to all functions
  • Declared outside any function body
  • Declared before any function that uses it

About Global Variables

  • Declared just like a global constant without the const
  • Makes programs more difficult to understand and maintain
  • Do not use in your programs for this course
#include <iostream>
#include <cmath>
using namespace std;

const double PI = 3.14159;

// Returns the area of a circle with the specified radius.
double area(double radius);

// Returns the volume of a sphere with the specified radius.
double volume(double radius);

int main(void) {
    double radius_of_both, area_of_circle, volume_of_sphere;

    cout << "Enter a radius to use for both a circle\n"
            << "and a sphere (in inches): ";
    cin >> radius_of_both;

    area_of_circle = area(radius_of_both);
    volume_of_sphere = volume(radius_of_both);

    cout << "Radius = " << radius_of_both << " inches\n"
            << "Area of circle = " << area_of_circle
            << " square inches\n"
            << "Volume of sphere = " << volume_of_sphere
            << " cubic inches\n";

    return 0;
}

double area(double radius) {
    return (PI * pow(radius, 2));
}

double volume(double radius) {
    return ((4.0 / 3.0) * PI * pow(radius, 3));
}

5.4.7: Summary

  • A function is a block of code get executed when called
  • Two parts to defining your own functions
    1. Function declaration (prototype)
    2. Function definition
  • Function prototypes syntax:
  • returnType functionName(parameterList);
  • Function definition syntax:
  • returnType functionName(parameterList) {
        // statements
    }
    
  • Values are passed to a function by putting values of the same data type, in the same order, inside the parentheses
  • functionName(arg1, arg2, ...);
  • Values are copied from the arguments to the parameters when the function is called
  • Functions return a value of the type declared
    • When returning nothing, special return type of void is used
  • To specify a value to return, use a return statement
  • return returnValue;
  • Variables declared in a function are local to that function
  • When the function returns, the memory used for the variable is reallocated
  • Global named constants are available to all functions
  • C++ supports global variables, but never use them in this course

Exercise 5.4

  1. Label this exercise: Exercise 5.4
  2. Submit all exercises for today's lesson in one file unless instructed otherwise
  3. Complete the following and record the answers to any questions in exercise5.txt.

Specifications

The absolute value of a number is the number itself if the number is positive and the negative of the number if the number is negative. For instance, the absolute value of 1 is 1 and the absolute value of -1 is also 1.

  1. Write a program with a function named calcAbs() that accepts a parameter of type double, computes the absolute value of the parameter, and returns the absolute value.
  2. Submit your final program along with your exercise5.txt file.
  3. Record answers to the following questions in exercise5.txt.
  4. Q1: What is the absolute value of 4?

    Q2: What is the absolute value of -4?

    Q3: Which line number of your program calls the calcAbs() function?

    Q4: How did your function return the results of the computation?

You can use the following code to get started.

#include <iostream>
using namespace std;

// Function prototype
double calcAbs(double value);

int main() {
    double num = 0.0;

    cout << "Number to convert: ";
    cin >> num;
    cout << "Absolute value is: " << calcAbs(num) << endl;

    return 0;
}

// Function definition
double calcAbs(double value) {
    // Insert statements here
    return value;
}

Wrap Up

Home | WebCT | Announcements | Day Schedule | Eve Schedule
Course info | Help | FAQ's | HowTo's | Links

Last Updated: October 05 2004 @15:34:08