Name: _____________________ Class: Comp 217
SSN/ID:   _____________________ Section & Group: ____________
Selection Control & I/O


Highlights of this lab:

In this lab, you will

Lab Exercise:

Back to Highlights

Boolean Data Type and Boolean Expressions

In C++, the data type bool is used to represent Boolean data. Each bool constant or variable contains one of two values: true or false. true and false are two C++ constants. true has the value 1. false has the value 0.

If a testing expression is not of bool type, it is coerced to bool type automaticaly when it is evaluated. A nonzero value is coerced to true and a zero value is coerced to false.

A Boolean expression can be a simple Boolean variable or constant or it can be a more complex expression involving one or more of the relational operators. Relational operators take two operands and test relationships between them. The following table shows the relational operators and the corresponding C++ symbols.

Relational Operators
C++ Symbol Description
== Equal To
!= Not Eqaul To
> Greater Than
< Less Than
>= Greater Than Or Equal To
<= Less Than Or Equal To

For example, The Boolean expression

	number1 < number2 
is evaluated to true if the value stored in number1 is less than the value stored in number2, and evaluated to false otherwise.

When a relational operator is applied between variables of type char, the assertion is in terms of where the two operands fall in the collating sequence of a particular character set.

For example,

	character1 < character2 
is evaluated to true if the value stored in character1 comes before the character stored in character2 in the collating sequence of the machine on which the expression is being evaluated. You can think of collating sequence as being in alphabetic order to help you understand it. ASCII character set is widely used.

A simple Boolean expression is either a Boolean variable or a Boolean constant or an expression involving the relational operators that evaluates to either true or false. These simple Boolean expressions can be combined using logical operations defined on Boolean values. There are three Boolean operators: AND, OR and NOT. Here is a table showing how they are used in C++.

Logical Operators
C++ Symbol Meaning
&& AND is a binary Boolean operator. If both operands are true, the result is true. Otherwise, the result is false.
|| OR is a binary Boolean operator. If at least one of the operands is true, the result is true. Otherwise, if both operands are false, the result is false.
! NOT is a unary Boolean operator. NOT changes value of its operand. If the operand is true, the result is false. If the operand is false, the result is true.

Precedence of Operators

If relational operators and Boolean operators are combined in the same expression in C++, the Boolean operator NOT (!) has the highest precedence, the relational operators have the next highest precedence, and the Boolean operators AND (&&) and OR (||) have the lowest. Expressions in parenthese are always evaluated first.

The following table summarizes the precedence of all the C++ operators we have seen so far.

C++ Operator Precedence
++ -- Highest Precedence
! Unary + Unary -
* / %
+ -
<< >>
< <= > >=
== !=
&&
||
= Lowest Precedence

Operators in the same line in the table have the same precedence. If an expression contains several operators with the same precedence, most of the operators group from left to right.

Back to Highlights

If Statement

The if statement allows the programmer to change the logical order of a program; i.e., it makes the order in which the statements are executed differ from the order in which they are listed in the program.

If-Then Statement

The if-then statement uses a Boolean expression to determine whether to execute a statement or to skip it. Here is the syntax template:
if (Expression)

Statement
The expression in parentheses can be of any simple data type. Almost without exception, this will be a logical (Boolean) expression; if not, its value is implicitly coerced to type bool (nonzero value means true, zero value means false).

Now, let's look at the following statement:

if (number < 0)
	number = 0;

sum = sum + number;
The expression (number < 0) is evaluated. If the result is true, the statement number = 0; is executed. If the result is false, the statement is skipped. In either case, the next statement to be executed is sum = sum + number;.

If-Then-Else Statement

If-Then-Else statement uses a Boolean expression to determine which one of the two statements to execute. Here is the syntax template:
if (Expression)

Statement1A else
Statement1B
The expression in parentheses will be evaluated with the result of true or false. Here is an example:
cout << "You are ";
if (age >= 65)
   cout << "a senior ";
else
   cout << "not a senior ";
cout << "citizen." << endl;
The characters "You are " are sent to the output stream. The expression age >= 65 is evaluated. If the result is true, the characters "a senior " are sent to the output stream. If the result is false, the characters "not a senior" is sent to the output stream. In either case, the next statement to be executed sends the the characters "citizen." to the output stream.

There is one thing to point out here: any statement in the if statement could be a block or a compound statement; i.e., more than one simple statement are enclosed in a pair of braces.

Nested If Statement

An if-then statemenet uses Boolean expression to determine whether to execute or skip a statemenet. An if-then-else statement uses a Boolean expression to determine which one of the two statements to execute. The statements to be executed or skipped could be simple statements or compound statements (blocks). They also can be an if Statement. An if statement within another if statement is called a nested if statement.

The following example is a nested If statement.

cout << "You are ";
if (age >= 65)
   cout << "a senior." << endl;
else
   if (age >= 19)
      cout << "an adult." << endl;
   else
      if (age >= 13)
	 cout << "a teenager." << endl;
      else
	 cout << "a child." << endl;
cout << "You are a great person." << endl;
The characters "You are " are sent to the output stream.
The expression age >= 65 is evaluated. If the result is true, the characters "a senior." are sent to the output stream.
If the result is false, the expression age >= 19 is evaluated.
If the result is true,the characters "an adult." are sent to the output stream.
If the result is false, the expression age >= 13 is evaluated.
If the result is true,the characters "a teeneager." are sent to the output stream.
If the result is false, the expression "a child." is sent to the output stream.
In any case above, the next statement to be executed sends the the characters "You are a great person." to the output stream.
Notice: once age has a value, only one statement is selected to be executed. If we add braces to the program segment, it would be easy to read. Let's look at it now:
cout << "You are ";
if (age >= 65) {
  cout << "a senior." << endl;
} else {
  if (age >= 19) {
    cout << "an adult." << endl;
  } else {
    if (age >= 13) {
      cout << "a teenager." << endl;
    } else {
      cout << "a child." << endl;
    }
  }
}
cout << "You are a great person." << endl;

Back to Highlights

State of an I/O Stream

We know any of the following can cause an input stream to enter the fail state:
  1. Invalid input data
  2. An attempt to read beyond the end of a file
  3. An attempt to open a nonexistent file to input
C++ provides a way to test the state of a stream: The stream name used in the expression returns true value if the state is ok and false value if the state is in the fail state.

Here is an example program that reads four floating point data values from a file and write to another file in the reverse order.

// Program iodemo.cpp demonstrates how to use files

#include <iostream>
#include <fstream>
using namespace std;

int main() {
    cout  << fixed  << showpoint;

    float val1, val2, val3, val4;	// declares 4 variables
    ifstream inData;			// declares input stream
    ofstream outData;			// declares output stream

    // binds program variable inData to file "Data.In"
    inData.open("Data.In");

    //Testing the state of the stream
    //true means the last I/O operation on that stream succeeded
    //false means the last I/O operation on that stream failed
    if (!inData) {
       cout << "Can't open the input file successfuly." << endl;
       return 1;
    }

    // binds program variable outData to file "Data.Out"
    outData.open("Data.Out");

    //Testing the state of the stream
    if (!outData) {
       cout << "Can't open the output file successfuly." << endl;
       return 2;
    }

    inData  >> val1 >> val2 >> val3 >> val4;	// inputs 4 values

    

    outData  << val4  << endl;
    outData  << val3  << endl;
    outData  << val2  << endl;
    outData  << val1  << endl;	// outputs 4 values

    return 0;
}

Notice that inData and outData are identifiers in the program; "Data.In" and "Data.Out" are character strings. Data.In is the name of the input data file that we have created; Data.Out is the name of the file where the answers are stored.

If the input file Data.In cannot be found, 1 is returned to the operating system. If the output file Data.Out cannot be opened or created, 2 is returned to the operating system. If there is no input and output error, 0 is returned to the operating system. Notice that the main() is exited as soon as a value is returned. Therefore, Returning 0 value means normal completion of a program; returning any other value signals an error. When you write your own program, you may choose the value to return to indicate different error conditions.

You can use the emacs text editor to create the input data file according to the requirement of the data type and format in your program. Input data file must exist and contain correct data. Otherwise, you will get input failure.

For example, in the preceding iodemo.cpp program, the input file should look like this:

5.5
6.6
7.7
8.8
You may run the program and and test the state of the I/O stream.

Back to Highlights


Lab Exercise — Seclection Control Structure

Exercise 1:

Exercise 2:

Back to Highlights

Hand In: This lab handout with the answers filled in attached to a listing of your final exercises
(use the enscript command from your Programming Style Sheet to print it out:
enscript -E -G -2rj -M Letter -PECT2_PS <filename> or a2ps <filename>).


Ricky J. Sethi <rickys at sethi.org>
Last modified: Sun Jul 24 18:43:26 PDT 2005