C++ Class Part 3

By Terry Norton

Welcome to lesson 3 of our C++ class. This lesson covers chapters 5 and 6 of "C++ Primer Plus."

Chapter 5 Loops and Relational Expressions
We begin to do data analysis using loops and relational expressions to control program flow. This means we begin writing code to solve problems.

After reading Chapter 5, you should understand the following concepts: Most of this chapter is pretty well explained in the book, so I will mainly outline the highlights.
 * The for loop
 * The while loop: when to use it instead of the for loop
 * The do while loop: how and why to use an exit condition
 * Multidimensional arrays
 * Nested loops to process multidimensional arrays
 * Expressions and the role they play in C++ statements
 * The increment and decrement operators
 * Using relational operators to control loops
 * Compound statements in loops
 * Using typedef to keep code flexible
 * The different forms of get
 * Testing for end-of-file conditions

The for loop
Structure of a for loop: for (initialization; loop test; loop update) loop statements for</tt> loops are entry-condition loops. The loop test is evaluated before executing any loop statements, so the statements may not be executed at all.
 * Initialization
 * The loop variable is initialized just once
 * May include the declaration of the loop variable
 * Loop test
 * Determines whether the loop is executed
 * Generally a relational expression, but any expression is acceptable
 * Ends the loop when the test evaluates to 0
 * Loop update
 * Evaluated at the end of each pass through the loop
 * Generally used to increase or decrease the value of the variable being tested
 * The step size can be any size
 * Loop statements
 * May be one C++ statement, or can be several in a block surrounded by brackets { }</tt>

NOTE:

I was not able to compile Listing 5.3, express.cpp</tt>, if it contained the cout.setf(ios_base::boolalpha)</tt>; statement. Perhaps someone can come up with the syntax that will work with OpenWatcom. I had a look in iostream.h</tt> but didn't see anything I totally understood to make cout</tt> print true</tt> and false</tt> instead of 1</tt> and 0</tt>. Of course, if you leave this statement out it will compile.

Relational expressions
The C++ relational operators True results in 1</tt> and false results in 0</tt>
 * Less than:  < </tt>
 * Less than or equal to: <=</tt>
 * Equal to:  == </tt> (note two equal signs. Using only one would be an assignment statement)
 * Greater than:  > </tt>
 * Greater than or equal to: <tt> >= </tt>
 * Not equal to: <tt> != </tt>

String comparisons
Strings can't be handled like numbers. Special string handling functions are contained in <tt> </tt> (for OpenWatcom) library.

Relational operators don't work because string constants and array names are addresses.

The <tt>strcmp</tt> library function
 * Returns <tt>0</tt> if strings are identical
 * Returns a negative value if first string precedes second in the system collating sequence
 * Return positive if first string follows second in the system collating sequence

The <tt>while</tt> loop

 * Essentially a <tt>for</tt> loop without the initialization and update sections
 * This is another entry-condition loop, so the statements may not be executed
 * The body is either a single statement or a block of statements
 * The loop continues until the test-condition is false (zero)
 * Something within the loop body must affect the test-condition

When to use <tt>for</tt> versus <tt>while</tt> loop

 * All <tt>for</tt> loops can be rewritten as <tt>while</tt> loops
 * Primarily a matter of style, unless a continue statement is needed
 * <tt>for</tt> is used for counting loops
 * while is used more often when you don't know the number of times to loop in advance

Time-delay functions
NOTE: In Listing 5.13, <tt>waiting.cpp</tt>, use <tt> </tt> instead of <tt> </tt>. The <tt>ctime.h</tt> file does not exist. If you want, take a look at <tt>x:\Watcom\H\time.h</tt>, line 63. Here you have <tt>clock_t</tt> defined as an alias for an unsigned long: <tt>typedef unsigned long clock_t;</tt> In <tt>waiting.cpp</tt>, when you see <tt>clock_t</tt>, it means the variable is an unsigned long type. The reason this is so is because the file <tt>time.h</tt> is part of the program code:
 * Uses the <tt>clock</tt> function in the <tt>time.h</tt> library
 * <tt>CLOCKS_PER_SEC</tt> is a symbolic constant
 * <tt>clock_t</tt> is an alias for the <tt>clock</tt> return type
 * 1) include

The <tt>do while</tt> loop
This loop introduces the exit-condition loop. The statements in the loop are processed before the test condition is checked to see if the loop should continue again.

Loops and Text Input
The info about member function <tt>cin.get(ch)</tt> being wrong for C is intended for any of you that already know C. The rest of us can ignore this bit of extra info for now. We will learn about passing values into functions later. For now just learn what the member functions are doing. We haven't studied in detail member functions either at this point since we haven't covered classes to any extent. A member function, if you recall, is a function defined as part of a Class. An object of the Class can be sent a message. In this case a message is being sent to the get(ch) function of the cin object, an object of the istream Class, to read character input. The <tt>cin</tt> member functions read the input, the <tt>while</tt> loop keeps checking for the correct input until a certain condition is met to make it stop.

The End-of-File Condition
In Listing 5.17, <tt>textin2.cpp</tt>, both <tt>cin.eof</tt> and <tt>cin.fail</tt> work to detect the EOF bits <tt>eofbit</tt> and <tt>failbit</tt>. I simply substituted <tt>cin.eof</tt> for <tt>cin.fail</tt> to find this out. Ctrl+D did not work, Ctrl+Z did.

NOTE: To make the window remain open for me to read it, I had to add the following two lines before the <tt>return</tt> statement. <tt>cin.clear;</tt> <tt>cin.get;</tt> As the book states, once an EOF bit is set, there can be no more <tt>cin</tt> input, so just adding cin.get before the return statement has no effect at keeping the window open. I had to add cin.clear to clear the EOF bit to allow cin.get to once again work.

Common Idioms
This section shows how flexible programming can be. Here we are shown other ways to accomplish the same <tt>while</tt> loop task. The point here is that programming isn't strict. Sure, you have to use the correct formats, but how you solve a problem is up to each individual.

Yet Another <tt>cin.get</tt>
<tt>cin.get</tt> returns a single character, not an <tt>istream</tt> object, and does not recognize whitespace: <tt> char ch; ch = <cin.get; </tt> If you want to examine every input character, including whitespace, and return a cin object, then use the get function with a character argument (parameter): <tt> char ch; cin.get(ch); </tt>

Nested Loops and Two-Dimensional Arrays
In this section you learn to process, with loops, row and column data with C++. If you have ever seen a spreadsheet, there are rows with columns of data.

Chapter 6 Branching Statements and Logical Operators
After reading Chapter 6, you should understand the following concepts:
 * The <tt>if</tt>, <tt>if else</tt> and nested <tt>if else</tt> structures for decision making
 * The <tt>switch</tt> statement and when it is better than <tt>if else</tt>
 * Using logical operators to test more complex conditions
 * The ctype library of character functions and using them in loops and decision structures
 * The conditional operator and when to use it instead of <tt>if else</tt>
 * Fine-tuning loop and <tt>switch</tt> behavior with <tt>break</tt> and <tt>continue</tt>
 * Using loops to input numerical data

The <tt>if</tt> Statement
<tt>if</tt>
 * Used to choose whether to take a particular action
 * A True condition causes the statement to execute
 * <tt>if else</tt> extends decisions to other alternatives
 * Entire <tt>if</tt> statement is a single statement
 * Multiple statements can be enclosed in <tt>{ }</tt>

Logical expressions in C++
This is where my digital electronics education comes in handy. I had to deal with AND and OR gates constantly. That was hardware, this is software, but it's still the same. Pretty simple stuff actually. In an OR expression, any true condition makes the expression true. If all conditions are false, then the expression is false. In an AND expression, all conditions must be true for the expression to be true. If any condition is false, then the expression is false. In a NOT expression, the condition is just plain reversed. If the condition would have produced true, it's false, and if it would have been false, it's true. Just listen to your teenagers talk, everything is the opposite of what the words really mean. They have this NOT thing perfected.

The <tt>cctype</tt> Library of Character Functions
NOTE: OpenWatcom does not have a <tt>cctype.h</tt> file, so use <tt> </tt> instead. With the <tt>ctype.h</tt> library, what you are basically doing with these functions is asking if a character is a particular kind of character, such as: Is this a lower case character? Or is this a decimal digit?

The <tt>switch</tt> versus <tt>if else</tt>
When should a <tt>switch</tt> statement be used instead of an <tt>if else</tt>?
 * They are frequently interchangeable
 * <tt>switch</tt> is not appropriate for selections in ranges
 * <tt>switch</tt> labels must be integers but <tt>if else</tt> can be almost anything
 * If the labels are all integer constants, <tt>switch</tt> is usually more efficient

<tt>break</tt> and <tt>continue</tt> Statements
Now that we now know looping and decision making in C++, <tt>break</tt> and <tt>continue</tt> allow fine tuning of these processes. The need for <tt>break</tt> in a switch statement is required. As the book states, this is different than other programming languages (I'm believing the book here). I know it's different than REXX. A switch statement in REXX exits the switch after processing one of the labels. I didn't use <tt>break</tt> or <tt>continue</tt> much in REXX, but I did find them useful at times.

Number-Reading Loops
<tt>cin</tt> is becoming quite a versatile object. Here we are taught that when reading numbers into an int array, entering anything other than a number can be used to end the loop. The <tt>while</tt> loop in Listing 6.13, <tt>cinfish.cpp</tt>, while (i < MAX && cin >> fish[i])

is part of an AND expression. <tt>i < MAX</tt> is a simple relational expression, as long as the value of <tt>i</tt> is less than 5, this part is True, or 1. The second part of the AND expression looks rather strange, <tt>cin >> fish[i]</tt>. This is where the user types in the fish weight. So how in the world can an input statement be used as part of test condition for an AND expression? The neat thing about C++ is that <tt>cin</tt> is an object. So what? Whenever you are dealing with objects, you are simply sending an object a message. Remember that part? When you send a message to an object, what you are really doing is calling a function of that object. Usually the function returns something to the caller.

<tt>cin >> fish[i]</tt> is really doing two things. It's letting the user input data into the <tt>fish</tt> array, and it's also returning a value since it's a function call to the <tt>cin</tt> object. As long as the user types in numbers for the fish weight, since each element of the <tt>fish</tt> array is a <tt>double</tt> type integer, the <tt>cin</tt> object says "Yup, that's a number" and returns true, or 1, from the function member of the <tt>cin</tt> object.

I want to keep stressing what C++ is about, Classes, objects of those Classes, and the sending of messages to the object to do things. Oh sure, we have to learn all this formatting of syntax and miscellaneous necessities, but it's the objects that we deal with. Just like you do everyday. You send a message to your coffee pot everyday. You input the data: coffee grounds, water, electricity, then tell it to do something, make coffee. Same with software objects. Everything is an object. Some are already provided, like the <tt>cin</tt> object, others we get to make ourselves. We, then, just provide the correct code to get the objects talking to each other, simple messages. <tt>cin >> fish[i]</tt> is a good example. "Hey, cin, was that info I typed in OK with you?" It replies with either "yup" (true or 1) or "nope" (false or 0), "and since it was the correct type, I put the data into a fish element for you."

As you get deeper into C++, you will probably start to think there's a lot of information to absorb and remember. You may start thinking that there's no way you can keep all this stuff in your head. Or say "forget it, this is just more than I can deal with." That may be true depending on the individual, but if you have always wanted to do some programming, learning in this group setting, with others in the same boat as you all talking to each other, is far better than doing it totally on your own. But there's so much to learn, you say. Well, yes and no. Yes there's a lot to learn, but you don't have to keep it all in your head.

When I was learning Object REXX all alone, I discovered that I didn't have to know everything and keep it all in my head. As long as you are exposed to the info and understand it along way, you may not have instant recall to just whip out a chunk of code, but you will have the knowledge in your head somewhere. As you start programming, you won't quite remember how to do something, big deal, look it up, refresh your memory. That's what programming reference books are for. This book will become a reference. Your notes will too. After a while of doing things over and over, you won't need to look some things up anymore.

Right now we're essentially learning the grammar of a foreign language. Being an expert at grammar isn't the goal. Understanding Classes and Objects is the goal, that's why I keep stressing this point over and over. I want to keep the big picture in front of you so that it doesn't get lost in these miscellaneous details we need to understand. Did I ever mention I like object programming?