| 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 A reference document on the basic elements of C++.
3. The Patterns
|
A. Input
Let's say that we want the message "Please enter your first integer
value" to appear on the screen. The code for this is: Don't worry too much for now about exactly how this works. Just note
that you need to put 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: 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. B. The Use 'main' and Other Details 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 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:
As a statement it is either true or false.
In C++ this is not a statement but an instruction. It means: 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:
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: Finally, there is the bit of code:
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 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: 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: 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.
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: 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:
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?
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: Now, the output will be 2.5.
E. Precedence 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: 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: Now the answer would be 12.
Finally, if an expression has two operators from the same precedence
level, for example:
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: 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.
|
|