cs1ch2sec2.htm
 

Chapter Two
The Basics of C++ and Program Development
 
Section II. Branch Statements
Section II : Our First Program Section I: Variables Section III: Iteration Section IV: Branch Statements

  


Table of Contents

Learning C++:
An Index of Entry Points


2. The

of C++

A reference document on the basic elements of C++.



3. The Patterns





A. Input
Now that we have our variables declared (let's just use the four integers), it is time to learn how to write the code to actually handle the input and output. First, the input: If you want a user to enter something, it is always a good idea to tell them exactly what you expect of them. Such statements are called prompts. For example:

"Please enter a value between 1 and 100."
"Choose from one of the menu items below"
"Enter your social security number"
"Type Q to quit".

Let's say that we want the message "Please enter your first integer value" to appear on the screen. The code for this is:

cout << "Please enter your first integer value";
     {Be sure to include the double quote marks and the semicolon at the end.)

Don't worry too much for now about exactly how this works. Just note that you need to put

'cout <<'

before the message. (Such a message is technically referred to as a string since it is a collection of characters. For more details on 'cout' and strings, read the material in Chapter 9, Part IV, Section F. )

With this code the computer will display our message but it will NOT accept any input. We need a second instruction for that purpose:

cin >> value1;

When the computer sees this instruction, it stops and waits for the user to type in a value. If the value is an integer (because 'value1' is declared as an integer), it is stored in the memory location symbolized by 'value1'. Otherwise, the computer outputs an error message and the program stops, or worse, goes into an infinite loop. (This behavior is explained in chapter 11.)

This description of what will happen when "cin >> value1" is executed is another example of 'semantics'. All programming languages have a syntax and a semantics. For example, the semicolon (;) at the end of the lines above is part of the C++ syntax - the basic rules that must be followed. As we noted, these lines of code also have a meaning to the computer - their semantics.

*********************

You have seen enough little chunks of code. It is time to see the whole program. Here it is - although there are a number of elements we have not yet discussed.

        // Program to add 3 numbers;
        // File: Ch2Prg1.cpp

        #include <iostream.h>

        void main()
        // Purpose: To add 3 numbers and output the sum
        // Receives: NONE
        // Returns:  NONE

        {      
             int value1;
             int value2;
             int value3;
             int sum;

             cout << "Please enter your first integer value ";
             cin >> value1;

             cout << "Please enter your second integer value ";
             cin >> value2;

             cout << "Please enter your third integer value ";
             cin >> value3;

             sum = value1 + value2 + value3;
             cout << "The sum is: " << sum << endl;
        }

B. The Use 'main' and Other Details
Probably most of this makes sense without any further explanation. Programming languages are not meant to be obscure and, if you write your code using good variable names and with good indentation (more on this later), the code should be at least semi-readable.

Still, there is some of what looks like mumbo-jumbo so let's go through the code. First, all the lines beginning with '//' are comments. This means that they are for us, the readers of the code. They are ignored by the compiler or translator. You could write a letter to someone in the middle of a program and as long as you put the letter in comments, it would have no affect on the program.

The first two comments simply say what the program is to do and the name of the file where the program is stored. The line that begins with '#' is a bit more interesting. Instructions for input and output are not part of C++ itself. Someone had to write the code that actually tells the computer how to do input and output. This code is written in C++ and is provided as part of the C++ package. Since our program does input and output, we need to insert this code into our program.

That code is divided into two parts - declarations and definitions. At this point we are most interested in the declarations and the part of the code that contains the declarations we need is in a file called iostream.h. The #include instruction says to bring this code into our program. (We will talk about the use of '<' and '>' later, in chapter 5. For now, just be sure you include them and this whole line as part of any program that has input or output.)

The line void main() (or some variation) must be part of all programs. Later, in chapter 4, we will talk about pieces of code called functions. At that point we will discover that "void main()" is a function declaration. All programs must have a 'main' because C++ compilers are written to translate the code inside 'main' as the beginning of the program. Without a 'main' there is no beginning! For now, in all your programs type this line exactly as shown here. (Actually, this is a Borland C++ variation from the C++ standard. If you are using a different version of C++, you may need to type "int main()".)

Following the declaration of main there are three lines of comments. The first line should be clear. The last two lines will be explained when we talk about functions. For now, always include these last two lines exactly as written here. The first line should be changed for each program to reflect the purpose of the program you are writing.

Following this is a line with the single character '{'. This marks the beginning of the code inside the function 'main'. Note that there is also a corresponding closing bracket, '}' at the end of the function.

You have already seen the four variable declarations and the pair of lines to get the user's first input. The next four lines simply use the same basic pattern to prompt for and retrieve from the user the second and third integer values. Note how all inputs really are pairs - a prompt instruction followed by an input instruction.

C. The Calculation and Output
Once we have the 3 inputs we can do the addition. This is accomplished through the line of code:

sum = value1 + value2 + value3;

This line is probably clear but be careful - the equal sign (=) in C++ does not mean what it means in mathematics. In mathematics this line would be a sentence, a statement with the meaning:

"The variable 'sum' has the same value as the one you would get by
adding the variables 'value1', 'value2', and 'value3'."

As a statement it is either true or false.

In C++ this is not a statement but an instruction. It means:

Go out to the memory locations symbolized by the
variables 'value1', 'value2', 'value3' and retrieve the values
found there. Add those three values and store the result in the
memory location symbolized by the variable 'sum'.

The equal sign (=) is the symbol or 'operator' that causes the 'store' operation.

We shall return to this point in a moment but first let's look at the last lines of this program, specifically:

cout << "The sum is: " << sum << endl;

This causes three things to be output. First is the string "The sum is: " and second is the value in the variable sum. By putting together the string and the variable we have a nicer looking output. To simply output the value in 'sum', as we could do if we wrote the code:

cout << sum;
would mean that the user would see a number appear on the screen without any explanation.

Finally, there is the bit of code:

... << endl;

This last word (endl) is what is called an output manipulator. Like 'cout', 'cin' and other declarations we need for basic input and output, it is declared in the file iostream.h. It indicates to the system that a carriage (line) return should take place. In other words, the system will place any further output on a new line. (Note how computers still use the language of manual typewriters.) In this particular case, it is not important since we are only outputting one value in this program. Later, as we output many values and sentences, the use of carriage returns will make our output more readable and pleasing to the eye. (Note that '<<' is used three times in this one instruction. This is similar to the use of '+' in "value1 + value2 + value3" above.)

A few final comments about syntax. Observe how most lines in the program end with a semicolon. We will get more precise about this later but for now, be sure to include a semicolon at the end of all input, output, and arithmetic instructions.

You might be interested in running this program to see how it works. Remember, C++ code needs to be translated into the language of a computer before it can be executed on that computer. If you are ambitious, you can follow the instructions for the compiler you are using and do your own compiling. (If you are using Borland C++, the compilation instructions are here.)

D. More on Mathematics and Assignment Statements
Another example might make clearer the distinction between how mathematics and C++ interpret the '=' symbol. Consider the code fragment:

int variable1;
variable1 = variable1 + 1;

There is no way this could be a true mathematical statement. It is impossible for a variable to be equal to itself plus 1. But, as a C++ instruction it means:

Go out to the memory location symbolized by the name
'variable1' and retrieve the value found
there. Then add 1 to that value and store the result
back into the memory location symbolized by 'variable1'.

That's a bit like taking all the socks out of your sock drawer, adding a pair to the pile, and then putting all the socks back into the draw. Or, it's like writing down the total of some set of numbers on a piece of paper and later looking up that total, adding some value to the total, erasing the old total, and writing the new total on the same paper.

We will let mathematicians worry further about the mathematical meaning of '='. In most programming languages, including C++, the '=' symbol is really an operator - a symbol that causes the computer to perform some operation. In addition to the assignment operator, there are a number of other C++ operators, many of which have essentially the same meaning as their mathematical counter-parts. We have already seen one example of this - the '+' symbol or operator. C++ also includes the other basic arithmetic operators:

        Subtraction       -
        Multiplication    *
        Division          /
Division can be tricky. For example, suppose you have the following code:
// A Program to test division
// File: Ch2prg2.cpp

#include <iostream.h>

void main()
// Purpose:     To explore how division works with integers
// Receives:    None
// Returns:     None

{
     int var1 = 5;
     int var2 = 2;

     double result;

     result = var1 / var2;   // There is a problem here 
     cout << "The result is: " << result;
}

Before we can talk about the division question, there are a number of new ideas introduced here. First, note that it is possible to initialize a variable when you declare it. To initialize a variable is to give it a value before it is used in the program. In this case, we are initializing the variable 'var1' to 5 and 'var2' to 2.

Since this is a simple program to demonstrate a few points about division, it makes sense to initialize our variables and avoid requiring a user to type in some values. Therefore, there are no inputs. But, we still want to see the results of our work, so we include an output.

cout << "The result is:" << result;

By the way, what is in the memory location symbolized by the variable 'result' before the division/store instruction is executed? Remember, this variable was never initialized. The answer is that we do not know what will be in this memory location. The act of attaching the name 'result' to some memory location does not usually change the contents of that memory location. So, the location has whatever it had before, which, as far as we are concerned, is garbage!

OK, now for a discussion of division. First, note that we declared 'result' to be a double. We did that because we knew that the answer would not be an integer: 5 / 2 = 2.5! In general, when doing division, it is wise to:

      declare as a double any variable that will hold the result of a division
      operation since the result has a good chance of containing a decimal. 

Unfortunately, if you run this program the output is 2 - not 2.5! What happened? The problem is that the division is done by the computer before it looks at the type of the variable that will hold the result. The computer sees two integers and therefore uses a set of division instructions that only work with integers and only produce integer answers. These instructions are faster than those associated with division of doubles but, in the process, they drop the .5 from the answer. (This is called truncation.) Here we have a nice little GOTCHA and it brings up an important point. Maybe you will always remember this little fact in your programming but there are many other little points like this and it is likely that you will forget one or more of them sometime. Expert programmers certainly do! A program may look just fine but produce strange answers. The moral of the story is:

ALWAYS TEST YOUR PROGRAMS

So, how do we fix this problem. There are a number of ways that we will see later but the quickest way for now is to change one or both of the first two variables to be doubles. How about the following line of code?

int var1 = 5.0;

Do you see any problems???? Take a moment to answer.

Can you put a decimal value into an integer? No! So, we need to rewrite the code as:

double var1 = 5.0;

Now, the output will be 2.5.

E. Precedence
There is one other issue we need to discuss concerning these four basic arithmetic operators - and actually all operators. Suppose one has the code fragment:

int var1 = 6;
int var2 = 2;
int var3 = 3;
int result;
result = var1 - var2 * var3;

What will be in the memory location symbolized by the variable 'result' after this line is executed? Doesn't the answer depend on the order in which the operations are performed? If we do the subtraction first, followed by the multiplication, the answer is 12. If we do the multiplication first, the answer is 0! So, which way does the computer do it? Programming languages like C++ have a set of rules called the Rules of Operator Precedence to handle this. We shall see that C++ has a large number of operators so these rules can be a bit complex. At this point we have seen 7 operators:

'+',    '-',    '*',    '/',    '>>',    '<<',    '='
(We have not talked about '>>' and '<<' as operators but they are.)

The highest precedence (meaning that operators with this precedence are executed first in any expression) goes to '*' and '/'. Next is '+' and '-', followed by '<<' and '>>'. Last is '='. So, for the expression above the answer is 0 because 'var2' is multiplied by 'var3' before the result is subtracted from 'var1'. If one wanted to have the subtraction executed first, one could use parentheses as in:

result = (var1 - var2) * var3;

Now the answer would be 12.

Finally, if an expression has two operators from the same precedence level, for example:

result = var1 * var2 / var3;

the operators are executed in order from left to right. A full list of all the operators and their level of precedence is in the Operator Precedence Table.

To wrap up this section here is a piece of code that calculates an hourly worker's salary ignoring issues such as overtime:

// A program to calculate a simple salary 
// File: ch2prg3.cpp

#include <iostream.h>

void main()
// Purpose:     to calculate a simple salary
// Receives:    NONE
// Returns:     NONE
        
{
     double rateOfPay;
     double salary;   
          // variables involving money should be
          // declared as doubles

     double hoursWorked;  // can be a fraction of an hour
        
     cout << "Please enter your rate of pay ";
     cin >> rateOfPay;
     cout << "Please enter the hours you worked this week ";
     cin >> hoursWorked;
     salary = hoursWorked * rateOfPay;
     cout << "Your salary is: " << salary;
}

Note again the names chosen for variables, the comments added, and the indentation. All programs should consistently follow some set of rules - follow some style. The code in this material follows a style described here.


Topics Covered in the "Essentials of C++"
Operators
Variables and Initialization
Operator Precedence

Top of Section Main Menu Next Section