OS/2 eZine - http://www.os2ezine.com
Spacer
July 16, 2003
 
Terry Norton is originally from California, moving to Vermont in 1984. His field of expertise is electrical engineering, having worked in electronics from 1969 until 1990. Starting in the Air Force for 6 years, then becoming Plant Engineer at Econco Broadcast Service in Woodland, CA. Upon moving to Vermont, he worked at Joslyn Defense System working in the field of EMP, Electro-Magnetic Pulse. In 1990 he retired from full time electronics to enter, along with his wife Lorraine, the field of helping the handicapped for an agency of the State of Vermont. Terry's first venture into the computer world was building his first 286 computer running DOS. He started using using OS/2 when version 2.0 was released. He's stayed with OS/2 ever since. At age 54, he now wishes to learn computer programming, a goal he has had for a number of years. Not necessarily as a career move, but for the self-satisfaction and love of OS/2 and eComstation.

If you have a comment about the content of this article, please feel free to vent in the OS/2 eZine discussion forums.

There is also a Printer Friendly version of this page.



Spacer
Previous Article
Home
Next Article


JPhotoBrush Pro - Award Winning Multi-Platform Image Editor that runs in OS/2


C++ Lesson 3: Loops and Relational Expressions

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:

  • 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

Most of this chapter is pretty well explained in the book, so I will mainly outline the highlights.


The forloop

Structure of a for loop: for (initialization; loop test; loop update) loop statements

  • 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 { }

for loops are entry-condition loops. The loop test is evaluated before executing any loop statements, so the statements may not be executed at all.

NOTE:

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

Relational expressions

The C++ relational operators

  • Less than: <
  • Less than or equal to: <=
  • Equal to: ==     (note two equal signs. Using only one would be an assignment statement)
  • Greater than: >
  • Greater than or equal to: >=
  • Not equal to: !=

True results in 1 and false results in 0

String comparisons

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

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

The strcmp library function

  • Returns 0 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 while loop

  • Essentially a for 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 for versus while loop

  • All for loops can be rewritten as while loops
  • Primarily a matter of style, unless a continue statement is needed
  • for 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, waiting.cpp, use <time> instead of <ctime>. The ctime.h file does not exist.

    • Uses the clock() function in the time.h library
    • CLOCKS_PER_SEC is a symbolic constant
    • clock_t is an alias for the clock() return type

    If you want, take a look at x:\Watcom\H\time.h, line 63. Here you have clock_t defined as an alias for an unsigned long:

      typedef unsigned long clock_t;

    In waiting.cpp, when you see clock_t, it means the variable is an unsigned long type. The reason this is so is because the file time.h is part of the program code:   #include <time>

    The do while 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 cin.get(ch) 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 cin member functions read the input, the while 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, textin2.cpp, both cin.eof() and cin.fail() work to detect the EOF bits eofbit and failbit. I simply substituted cin.eof() for cin.fail() 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 return statement.

     cin.clear();
     cin.get();

    As the book states, once an EOF bit is set, there can be no more cin 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 while 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 cin.get()

    cin.get() returns a single character, not an istream object, and does not recognize whitespace:

     char ch;
     ch = <cin.get();

    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):

     char ch;
     cin.get(ch);

    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 if, if else and nested if else structures for decision making
    • The switch statement and when it is better than if else
    • 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 if else
    • Fine-tuning loop and switch behavior with break and continue
    • Using loops to input numerical data

    The if Statement

    The if type statements are pretty simple. So I will just mention the highlights:
    • Used to choose whether to take a particular action
    • A True condition causes the statement to execute
    • if else extends decisions to other alternatives
    • Entire if statement is a single statement
    • Multiple statements can be enclosed in { }

    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 cctype Library of Character Functions

    NOTE:

    OpenWatcom does not have a cctype.h file, so use <ctype> instead.

    With the ctype.h 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 switch versus if else

    When should a switch statement be used instead of an if else?

    • They are frequently interchangeable
    • switch is not appropriate for selections in ranges
    • switch labels must be integers but if else can be almost anything
    • If the labels are all integer constants, switch is usually more efficient

    break and continue Statements

    Now that we now know looping and decision making in C++, break and continue allow fine tuning of these processes. The need for break 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 break or continue much in REXX, but I did find them useful at times.

    Number-Reading Loops

    cin 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 while loop in Listing 6.13, cinfish.cpp,

     while (i < MAX && cin >> fish[i])

    is part of an AND expression. i < MAX is a simple relational expression, as long as the value of i is less than 5, this part is True, or 1. The second part of the AND expression looks rather strange, cin >> fish[i]. 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 cin 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.

    cin >> fish[i] is really doing two things. It's letting the user input data into the fish array, and it's also returning a value since it's a function call to the cin object. As long as the user types in numbers for the fish weight, since each element of the fish array is a double type integer, the cin object says "Yup, that's a number" and returns true, or 1, from the function member of the cin 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 cin object, others we get to make ourselves. We, then, just provide the correct code to get the objects talking to each other, simple messages. cin >> fish[i] 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?

    Previous Article
    Home
    Next Article

    Copyright (C) 2003. All Rights Reserved.