c++ Programming 1 Manfg
c++ Programming 1 Manfg
c++ Programming 1 Manfg
Chapter One
C++ Basics
Introduction
In the early days of computing, programs were written in machine language, which
consists of the primitive instructions that can be executed directly by the machine.
Machine language programs are difficult to understand, mostly because the structure of
machine language reflects the design of the hardware rather than the needs of
programmers. In the mid-1950s, a group of programmers had an idea that profoundly
changed the nature of computing. In 1955, the initial version of FORTRAN (whose name
is an abbreviation of formula translation), which was the first example of a higher level
programming language produced. Since that time, many new programming languages
have been invented, such as COBOL, BASIC, PASCAL, C, C++, C#, JAVA etc.
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.
Page 1
Computer programming for Engineers Programming
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.
Page 2
Computer programming for Engineers Programming
definitions for input and output and it is included because its functionality is going to be
used later in the program.
You have heard about compilers of C++. But also, there is another program called
preprocessor which always run before the compiler each time one starts the compiler.
The function of the preprocessor program is to look for all lines which begin with the
pound symbol (#) throughout the program. And having these lines of the program, the
preprocessor will ‘read in’ or copy the content of the header files specified after include
into the program to make the program ready to be compiled. It is after this time the
compiler starts acting on the program (translating and checking for syntax errors).
N.B: there are a number of header files with their own content and it is possible to
include multiple header files.
Third line int main () function declarator
This line corresponds to the beginning of the definition of the main function. Every C++
program must have one function with the name main, from where the execution of the
program begins. The word main is followed in the code by a pair of parentheses ( ) which
is mandatory.
Fourth line { function begin
The function body in C++ program is enclosed between two flower brackets (curly
braces). The opening flower bracket ({ ) marks the beginning of a function. What is
contained within these braces is what the function does when it is executed.
Fifth line cout << "Hello World!"; function body
This line is a C++ statement. A statement is a simple or compound expression that can
actually produce some effect. cout represents the standard output stream in C++, and the
meaning of the entire statement is to insert a sequence of characters (in this case the Hello
World sequence of characters) into the standard output stream (which usually is the
screen).
Sixth line return 0; Return
The return statement causes the main function to finish (terminate). return may be
followed by a return code (in our example is followed by the return code 0). A return
code of 0 for the main function is generally interpreted as the program worked as
Page 3
Computer programming for Engineers Programming
expected without any errors during its execution. This is the most usual way to end a C++
console program.
Seventh line } function end
The end of a function body is marked by the closing flower bracket (closing brace}).
When the compiler gets bracket it is replaced by the statement return 0;
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:
Page 4
Computer programming for Engineers Programming
"Hello World!";
cout
<< "I'm a C++ program";
return 0;
}
And the result would again have been exactly the same as in the previous examples.
Preprocessor directives (those that begin by #) are out of this general rule since they are
not statements. They are lines read and processed by the preprocessor and do not produce
any code by themselves. Preprocessor directives must be specified in their own line and
do not have to end with a semicolon (;).
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
between double quotes (") so that they can be clearly distinguished from variable names.
For example, these two sentences have very different results:
Page 5
Computer programming for Engineers Programming
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:
cout << "First sentence." << endl;
cout << "Second sentence." << endl;
Would print out:
First sentence.
Second sentence.
The endl manipulator produces a newline character, exactly as the insertion of '\n' does.
Page 6
Computer programming for Engineers Programming
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;
In both cases the user must give two data, one for variable a and another one for variable
b that may be separated by any valid blank separator: a space, a tab character or a
newline.
Debugging
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
Page 7
Computer programming for Engineers Programming
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
logic error. Logic errors are the hardest kind of error to locate, because the computer does
not give you any error messages.
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
Page 8
Computer programming for Engineers Programming
own rules for naming these identifiers. C++ imposes the following rules for creating valid
names (identifiers).
Keywords
Keywords are certain words reserved by C++. All keywords have fixed meaning which
cannot be changed. All keywords must be written in lowercase and cannot be used as
identifiers. The list of keywords supported in C++ language is given in Table 2.1.
Page 9
Computer programming for Engineers Programming
A variable is an entity whose value can be changed during program execution and is
known to the program by a name. It is the content of a memory location that stores a
certain value. A variable can hold only one value at a time during program execution. Its
value can be changed during the execution of the program. The various components
associated with variables are the following:
Data type: char, int, float
Variable name: user view
Binding address: machine view
Value: data stored in memory location
Variable Names
Variable names are identifiers used to name variables. They are the symbolic names
assigned to the memory location. A variable name consists of a sequence of letters and
digits. The rules that apply to identifiers (given above) also apply to variable names.
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:
Page 10
Computer programming for Engineers Programming
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 double takes 8/10 bytes depending on
int takes 2/4 bytes depending on the the compiler
compiler bool takes 1 byte
float takes 4 bytes
Page 11
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
In C++, a variable can be assigned with a value during its definition or during the execution of the program. The
assignment operator (=) used in both cases. The syntax for variable initialization during its definition:
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;
% 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
== Equality 5==5 // gives 1
!= Inequality 5!=5 // gives 0
< Less Than 5 < 5.5 // gives 1
<= Less Than or Equal 5 <= 5 // gives 1
> Greater Than 5 > 5.5 // gives 0
>= Greater Than or Equal 6.3 >= 5// gives 1
Table 2.4: Relational Operators
For example:
65 < 75 // gives 1 or true
Relational operators should not be used for comparing strings1, because this will result in the string addresses
being compared, not the string contents. For example, the expression
"HELLO" < "BYE"
causes the address of "HELLO" to be compared to the address of "BYE". As these addresses are determined by
the compiler (in a machine-dependent manner), the outcome may be 0 or 1, and is therefore not indicative of the
actual check.
3. Logical Operators
1
C++ provides library functions (e.g., strcmp) for the lexicographic comparison of string.
Logical operators connect two or more relational expressions into one or reverse the logic. C++ provides three
logical operators, summarized in Table 2.5, for combining logical expressions. Like the relational operators,
logical operators evaluate to 1 or 0.
Operator Name Example
! Logical Negation !(5 == 5) // gives 0
&& Logical AND 5 < 6 && 6 < 6 // gives 0
|| Logical OR 5 < 6 || 6 < 5 // gives 1
Table 2.5: Logical Operators
Logical Negation is a unary operator, which negates the logical value of its single operand. If its
operand is nonzero it produces 0, and if it is 0 it produces 1.
Logical AND produces 0 if one or both of its operands evaluate to 0. Otherwise, it produces 1.
Logical OR produces 0 if both of its operands evaluate to 0. Otherwise, it produces 1.
Note that we talk of zero and nonzero operands (not 0 and 1). In general, any nonzero value can be used to
represent the logical true, whereas only zero represents the logical false. The following are, therefore, all valid
logical expressions:
!20 // gives 0
10 && 5 // gives 1
10 || 5.5 // gives 1
10 && 0 // gives 0
The assignment operator has a number of variants, obtained by combining it with the arithmetic operators (Table
2.6).
Operator Example Equivalent To
= 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 Table 2.6: Assignment operators
An assignment operation is itself an expression whose value is the value stored in its left operand. An assignment
operation can therefore be used as the right operand of another assignment operation. Any number of
assignments can be concatenated in this fashion to form one expression. For example:
int m, n, p;
m = n = p = 100; // means: n = (m = (p = 100));
m = (n = p = 100) + 2; // means: m = (n = (p = 100)) + 2;
This is equally applicable to other forms of assignment. For example:
m = 100;
m += n = p = 10; // means: m = m + (n = p = 10);
5. Increment/Decrement Operators
The auto increment (++) and auto decrement (--) operators provide a convenient way of, respectively, adding
and subtracting 1 from a numeric variable. These are summarized in Table 2.7. The examples assume the
following variable definition:
int k = 5;
Operator Name Example
++ Auto Increment (prefix) ++k + 10 // gives 16
++ Auto Increment (postfix) k++ + 10 // gives 15
-- Auto Decrement (prefix) --k + 10 // gives 14
-- Auto Decrement (postfix) k-- + 10 // gives 15
Table 2.7: Increment and Decrement Operators
Both operators can be used in prefix and postfix form. The difference is significant. When used in prefix form,
the operator is first applied and the outcome is then used in the expression. When used in the postfix form, the
expression is evaluated first and then the operator applied. Both operators may be applied to integer as well as
real variables, although in practice real variables are rarely useful in this form.
() 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 than or equal to relational left to right
< 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. Precedence rules can be overridden using brackets.
For example, rewriting the above expression as
a == (b + c) * d
causes + to be evaluated before *.
Operators with the same precedence level are evaluated in the order specified by the last column of Table 2.8.
For example, in
a = b += c
the evaluation order is right to left, so first b += c is evaluated, followed by a = b.