Programming Chapter 2
Programming Chapter 2
Dec 2013
C++ began as an expanded version of C. The C++ extensions were first invented by
Bjarne Stroustrup in 1979 at Bell Laboratories in Murray Hill, New Jersey. He initially
called the new language "C with Classes." However, in 1983 the name was changed to
C++. C++ allows programmers to comprehend and manage larger, more complex
programs because it includes Object Oriented features.
C++ is a high-level language: when you write a program in it, the short hands are
sufficiently expressive that you don’t need to worry about the details of processor
instructions.
The first of them, known as single line comment, discards everything from where the pair
of slash signs (//) is found up to the end of that same line. The second one, known as
block comment, discards everything between the /* characters and the first appearance of
the */ characters, with the possibility of including more than one line.
The above example program has been structured in different lines in order to be more
readable, but in C++, we do not have strict rules on how to separate instructions in
different lines. For example, we could write the above program as:
int main () { cout << "Hello World!"; return 0; }
All in just one line and this would have had exactly the same meaning as the previous
code. In C++, the separation between statements is specified with an ending semicolon (;)
at the end of each one, so the separation in different code lines does not matter at all for
this purpose. We can write many statements per line or write a single statement that takes
many code lines. The division of code in different lines serves only to make it more
legible and schematic for the humans that may read it. Let us add an additional
instruction to our first program:
I/O streams
Using the standard input and output library, we will be able to interact with the user by
printing messages on the screen and getting the user's input from the keyboard. C++ uses
a convenient abstraction called streams to perform input and output operations in
sequential media such as the screen or the keyboard. A stream is an object where a
program can either insert or extract characters to/from it. The standard C++ library
includes the header file iostream, where the standard input and output stream objects are
declared.
Standard Output (cout): By default, the standard output of a program is the screen, and
the C++ stream object defined to access it is cout. cout is used in conjunction with the
insertion operator, which is written as << (two "less than" signs).
cout << "Output sentence"; // prints Output sentence on screen
cout << 120; // prints number 120 on screen
cout << x; // prints the content of x on screen
The << operator inserts the data that follows it into the stream preceding it. In the
examples above it inserted the constant string Output sentence, the numerical constant
120 and variable x into the standard output stream cout. Notice that the sentence in the
first instruction is enclosed between double quotes (") because it is a constant string of
characters. Whenever we want to use constant strings of characters we must enclose them
even though we had written them in two different insertions into cout. In order to perform
a line break on the output we must explicitly insert a new-line character into cout. In C++
a new-line character can be specified as \n (backslash, n):
cout << "First sentence.\n ";
cout << "Second sentence.\nThird sentence.";
This produces the following output:
First sentence.
Second sentence.
Third sentence.
Additionally, to add a new-line, you may also use the endl manipulator. For example:
Standard Input (cin): The standard input device is usually the keyboard. Handling the
standard input in C++ is done by applying the overloaded operator of extraction (>>) on
the cin stream. The operator must be followed by the variable that will store the data that
is going to be extracted from the stream. For example:
int age;
cin >> age;
The first statement declares a variable of type int called age, and the second one waits for
an input from cin (the keyboard) in order to store it in this integer variable.
cin can only process the input from the keyboard once the Enter key has been pressed.
Therefore, even if you request a single character, the extraction from cin will not process
the input until the user presses Enter after the character has been introduced.
You must always consider the type of the variable that you are using as a container with
cin extractions. If you request an integer you will get an integer, if you request a character
you will get a character and if you request a string of characters you will get a string of
characters.
You can also use cin to request more than one datum input from the user:
cin >> a >> b;
is equivalent to:
cin >> a;
cin >> b;
A mistake in a program is called a bug. For this reason, the process of eliminating
mistakes in your program is called debugging. Debugging is the process of correcting
errors from the program via testing. There are three commonly recognized types of bugs
or errors, which are known as syntax errors, run-time errors, and logic errors.
A syntax error is a grammatical mistake in your program; that is, a mistake in the
allowed arrangement of words and punctuations. If you violate one of these rules-for
example, by omitting a required punctuation-it is a syntax error. The compiler will catch
syntax errors and output an error message telling you that it has found the error, where it
thinks the error is, and what it thinks the error is. If the compiler says you have a syntax
error, you undoubtedly do. However, the compiler could be incorrect about where and
what the error is.
An error that is not detected until your program is run is called a run-time error. If the
computer detects a run-time error when your program is run, then it will output an error
message. The error message may not be easy to understand, but at least it lets you know
that something is wrong. For example, division by zero: If there is any place(instruction )
which attempts to any number by zero, this error will not be syntax error instead runtime
error.
A mistake in the underlying algorithm for your program is called a logic error. If your
program has only logic errors, it will compile and run without any error message. You
have written a valid C++ program, but you have not written a program that does what you
want. The program runs and gives output, but the output is incorrect. For example, if you
were to mistakenly use the multiplication sign in place of the addition sign, it would be a
Identifiers
Identifier refers to the name of variables, functions, arrays classes, etc. created by the
programmer. They are fundamental requirements of any language. Each language has its
own rules for naming these identifiers. C++ imposes the following rules for creating valid
names (identifiers).
Variable Names
Biniam T. MU©2013/2014 Page 10
Computer programming for Engineers Programming
Dec 2013
Data Types
When programming, we store the variables in our computer's memory, but the computer
has to know what kind of data we want to store in them, since it is not going to occupy
the same amount of memory to store a simple number than to store a single letter or a
large number, and they are not going to be interpreted the same way.
The memory in our computers is organized in bytes. A byte is the minimum amount of
memory that we can manage in C++. A byte has 8 bits.
C++ supports a variety of data types and the programmer can choose the type to the
needs of the application. The basic data types in C++ are the following:
Character denoted by char is the data type that holds an integer value
corresponding to the representation of an element of the ASCII character set.
Integer denoted by int is the data type that holds an integer value or whole number.
Real denoted by:
o float is the data type that holds single precision floating point value or real
number.
o double is the data type that holds a double precision floating point value or
real number.
Boolean denoted by bool is the data type that holds a Boolean value of true or false.
The basic data types byte size are as follows:
char takes 1 byte float takes 4 bytes
int takes 2/4 bytes depending on the double takes 8/10 bytes depending on
compiler the compiler
Variable Declaration/Definition
A declaration of a variable is a statement that gives information about the variables to the
C++ compiler. A variable must be defined before using it in a program. It reserves
memory required for data storage and associates it with a symbolic name. The syntax for
defining a variable is:
int a;
float mynumber;
Are valid declarations of variables. The first one declares a variable of type int with the
identifier a. The second one declares a variable of type float with the identifier
mynumber. Once declared, variables a and mynumber can be used within the rest of their
scope in the program.
If you need to declare several variables of the same type and you want to save some
writing work you can declare all of them in the same line separating the identifiers with
commas. For example:
int a, b, c;
declares three variables (a, b and c) of type int and has exactly the same meaning as if we
had written:
int a;
int b;
int c;
Initialization of variables
For example, if we want to declare an int variable called a initialized with a value of 0 at
the moment in which it is declared, we could write:
int a = 0;
When multiple variables are being declared in a single statement, initialization is carried
out in the following way:
Data type variable name1 = value1, variable name2 = value2,…, variable nameN = valueN;
Example:
int i=10,j=5,k=8;
Operators are symbols that tell the computer to perform certain mathematical or logical
manipulation. An operator is a symbol that operates on one or more expressions,
producing a value that can be assigned to a variable. C++ provides many built-in
operators for composing expressions. An expression, by the way, is any computation
which yields a value. It is a combination of variables, constants and operators written
according to the syntax of the language. The several C++ operators can be classified in to:
1. Arithmetic Operators
Table 2.2 Common operators in C++
Biniam T. MU©2013/2014 Page 13
Computer programming for Engineers Programming
Dec 2013
% Remainder 13 % 3 // gives 1
Except for remainder (%) all other arithmetic operators can accept a mix of integer and
real operands. Generally, if both operands are integers then the result will be an integer.
However, if one or both of the operands are reals then the result will be a real (or double
to be exact).
When both operands of the division operator (/) are integers then the division is
performed as an integer division and not the normal division we are used to. Integer
division always results in an integer outcome (i.e., the result is always rounded down).
For example:
9/2 // gives 4, not 4.5!
It is possible for the outcome of an arithmetic operation to be too large for storing in a
designated variable. This situation is called an overflow. The outcome of an overflow is
machine-dependent and therefore undefined. It is illegal to divide a number by zero. This
results in a run-time division-by-zero failure, which typically causes the program to
terminate.
2. Relational Operators
A relational operator is used to make comparison between two expressions. C++
provides six relational operators for comparing numeric quantities (Table 2.4). Relational
operators usually evaluate to 1 (representing the true outcome) or 0 (representing the
false outcome). The operands of a relational operator must evaluate to
a number.
Operator Name Example
3. Logical Operators
1
C++ provides library functions (e.g., strcmp) for the lexicographic comparison of string.
= n = 25
+= n + = 25 n = n + 25
-= n - = 25 n = n - 25
*= n * = 25 n = n * 25
/= n / = 25 n = n / 25
%= n %= 25 n = n % 25
() Parentheses
[] array subscript
++ Unary post increment left to right
-- unary post decrement
* multiplication left to right
/ division
% modulus
+ addition left to right
- subtraction
< relational less than relational less left to right
< than or equal to relational greater
=> than relational greater than or
>= equal to
== relational is equal to relational is
!= not equal to
= assignment right to left
+= addition assignment
-= subtraction assignment
*= multiplication assignment
/= division assignment
%= modulus assignment
Table 2.8: Operator Precedence Levels
For example, in
a == b + c * d
c * d is evaluated first because * has a higher precedence than + and ==. The result is then
added to b because + has a higher precedence than ==, and then == is evaluated.