Chapter Two
Chapter Two
C++ BASICS
2.1. Brief introduction to C++
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. Would it be possible, they wondered, to write programs that resembled the
mathematical formulas they were trying to compute and have the computer itself translate those formulas
into machine language? 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++.
Over the years, computer programs have become larger and more complex. Even though
C is an excellent programming language, it has its limits. In C, once a program exceeds from 25,000 to
100,000 lines of code, it becomes so complex that it is difficult to grasp as a totality. The purpose of C++ is
to allow this barrier to be broken. The essence of C++ is to allow the programmer 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. C++ does give access to some
lower-level functionality than other languages (e.g. memory addresses).
Comments are parts of the source code disregarded by the compiler. They simply do nothing. Their purpose
is only to allow the programmer to insert notes or descriptions embedded within the source code. C++
supports two ways to insert comments:
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.
#include <iostream.h>
Lines beginning with a hash sign (#) are directives for the preprocessor. They are not regular code lines with
expressions but indications for the compiler's preprocessor. This line uses the preprocessor directive
#include to include the contents of the header file iostream.h in the program. iostream.h is a standard C++
header file and contains definitions for input and output and it is included because its functionality is going
to be used later in the program. Preprocessor directives must be specified in their own line and do not have
to end with a semicolon (;).
Example 1: The line #include <iostream.h> instructs the compiler to include the declaration of the standard
input and output facilities into the program. It is used to copy and insert all the content of the mentioned
header file which is iostream.h into the source program (our own program). Otherwise, the compiler won’t
recognize the operators and the functions used and will refuse to compile the program.
Example 2: Look at the statement in line 5 of the C++ program given as example right to the general format
above. It is cout<<”Hello World”; ‘cout<<’ is an operator whose code is written in the iostream.h header
file. If the content of the header file is not included prior to the compilation process, the compiler will not
recognize this statement at all.
Therefore, this line of the program (as well as all include directives) is used to include header files. Note
that there are a number of header files with their own content and it is possible to include multiple header
files. If you intend to use one of the operators or functions defined in one of these files, include them at the
beginning of your program.
int main ()
This line corresponds to the beginning of the definition of the main function. The main function is the point
by where all C++ programs start their execution, independently of its location within the source code. It
does not matter whether there are other functions with other names defined before or after it the instructions
contained within this function's definition will always be the first one to be executed in any C++ program.
For that same reason, it is essential that all C++ programs have a main function.
The word main is followed in the code by a pair of parentheses ( ). That is because it is a function
declaration: In C++, what differentiates a function declaration from other types of expressions is these
parentheses that follow its name. What is contained within these braces is what the function does when it is
executed.
return 0;
The return statement causes the main function to finish. 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 expected without any errors during its execution. This is the most usual way to
end a C++ console program.
The 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, instead of
int main ()
{
cout << " Hello World!";
return 0;
}
We could have written:
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. 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:
// my second program in C++
#include <iostream.h>
int main ()
{
cout << "Hello World! ";
cout << "I'm a C++ program";
return 0;
}
Output: Hello World! I'm a C++ program
int main () { cout << " Hello World! "; cout << " I'm a C++ program "; return 0; }
We were also free to divide the code into more lines if we considered it more convenient:
int main ()
{
cout <<
"Hello World!";
cout
<< "I'm a C++ program";
return 0;
}
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
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:
cout << "Hello"; // prints Hello
cout << Hello; // prints the content of Hello variable
The insertion operator (<<) may be used more than once in a single statement:
cout << "Hello, " << "I am " << "a C++ statement";
This last statement would print the message Hello, I am a C++ statement on the screen. The utility of
repeating the insertion operator (<<) is demonstrated when we want to print out a combination of variables
and constants or more than one variable:
cout << "Hello, I am " << age << " years old and my zipcode is " << zipcode;
If we assume the age variable to contain the value 24 and the zipcode variable to contain
90064 the output of the previous statement would be:
Hello, I am 24 years old and my zipcode is 90064
It is important to notice that cout does not add a line break after its output unless we explicitly indicate it,
therefore, the following statements:
cout << "This is a sentence.";
cout << "This is another sentence.";
Will be shown on the screen one following the other without any line breaks between them: This is a
sentence. This is another sentence.
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.
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 key after the character has been introduced.
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 b another one for variable b that may be
separated by any valid blank separator: a space, a tab character or a newline.
Compilation process
When you write a program in C++, your first step is to create a file that contains the text of the program,
which is called a source file. Before you can run your program, you need to translate the source file into an
executable form. The first step in that process is to invoke a program called a compiler, which translates the
Source Object file
fileinto an object file containing the corresponding machine-language
source file instructions. This object file
is then combined with other object files to produce an executable file that can be run on the system. The
other object files typically include predefined object files, called libraries that contain the machine-
// my first program in C++ 0100110001000101
language instructions for various operations commonly required by programs. The process of combining all
#include <iostream.h> Compiler 01001001010110001101001001
the()individual object files into an executable file is called linking. The process is illustrated by the diagram
int main 01010001010
{ shown below.
cout << "Hello World!";
return 0;
}
Linker
Executable file
Syntax error: syntax refers to the order in which components (token) of the programming language must
come. If there invalid order of token is provided in the language description we call this error as syntax
error. Compiler can easily detect syntax error during compilation. Therefore such error is also called
compilation time error. We can’t compile a source code, which has a syntax error. Therefore syntax error
should be corrected during compilation. The strategy is simple: compile your code, if there is a compilation
error, try to correct it and repeat the process until you get an error free code during compilation.
Logical error: the program designed and compiled without error has an objective. The objective is for any
input the program should process the input and generate an output. However, there may be a case that the
program may not provide the expected output for a known input. Such problem is called logical error.
Logical error can be corrected through intensive testing for various possible cases. Generally getting syntax
error free code is simple but avoiding logical error is a bit difficult and programmer must spent a lot time on
testing.
Various programming language provide advanced debugging tools to correct logical errors.
Example:
salary // valid identifier
salary2 // valid identifier
2salary // invalid identifier (begins with a digit)
_salary // valid identifier
Salary // valid but distinct from salary
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 can store a relatively small amount of data: one single character or a small integer
(generally an integer between 0 and 255). In addition, the computer can manipulate more complex data
types that come from grouping several bytes, such as long numbers or non-integer numbers.
Next you have a summary of the basic fundamental data types in C++, as well as the range of values that
can be represented with each one:
Declaration of variables
In order to use a variable in C++, we must first declare it specifying which data type we want it to be. The
syntax to declare a new variable is to write the specifier of the desired data type (like int, bool, float...)
followed by a valid variable identifier. A declaration is a statement that introduces a name into the program.
It must specify a type for that name.
For example, the declaration
int inch;
Specifies that inch is if type int; that is, int is an integer variable.
int a;
float mynumber;
These are two 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, the
variables a and mynumber can be used within the rest of their scope in the program.
If you are going to declare more than one variable of the same type, you can declare all of them in a single
statement by separating their identifiers with commas. For example:
int a, b, c; or
int a;
int b;
int c;
Expressions
Anything that evaluates to a value is an expression in C++. An expression is said to return a value. Thus,
3+2; returns the value 5 and so is an expression. All expressions are statements.
The complicated expression: x = a + b;
Thus, this statement is also an expression. Because it is an expression, it can be on the right side of an
assignment operator:
y = x = a + b;
This line is evaluated in the following order: Add a to b. Assign the result of the expression a + b to x.
Assign the result of the assignment expression x = a + b to y. If a, b, x, and y are all integers, and if a has the
value 2 and b has the value 5, both x and y will be assigned the value 7. So, the general form of expression
and variables, evaluated from the right to left, is:
variable = any_expression;
Statements
In C++ a statement controls the sequence of execution, evaluates an expression, or does nothing (the null
statement). All C++ statements end with a semicolon, even the null statement, which is just the semicolon
and nothing else. One of the most common statements is the following assignment statement:
x = a + b;
Unlike in algebra, this statement does not mean that x equals a+b. This is read, "Assign the value of the sum
of a and b to x," or "Assign to x, a+b." Even though this statement is doing two things, it is one statement
and thus has one semicolon. The assignment operator assigns whatever is on the right side of the equal sign
to whatever is on the left side.
Compiler read a statement in the source code it looks for the characters and for the terminating semicolon
and ignores the white space. For example, three of the following examples are same.
x = 2 + 3; or
x=2+3; or
x=
2
+
3;
Whitespace: Whitespace (tabs, spaces, and newlines) is generally ignored in statements. The assignment
statement previously discussed could be written as
x=a+b; or as x = a+ b;
Initialization of variables
When declaring a regular local variable, its value is by default undetermined. But you may want a variable
to store a concrete value at the same moment that it is declared. In order to do that, you can initialize the
variable. There are two ways to do this in C++:
The first one, known as c-like, is done by appending an equal sign followed by the value to which the
variable will be initialized:
type identifier = initial_value ;
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;
2.4. Operators
Operators are symbols that tell the computer to perform certain mathematical or logical manipulation. C++
provides many built-in operators for composing expressions. An expression, by the way, is any computation
which yields a value. The several C++ operators can be classified in to:
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.
== Equality 5 = = 5 // gives 1
!= Inequality 5 ! = 5 // gives 0
1 C++ provides library functions (e.g., strcmp) for the lexicographic comparison of string.
Operator Name Example
The assignment operator has a number of variants, obtained by combining it with the arithmetic and bitwise
operators (Table 2.7). Assuming that n is an integer variable,
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
b=a;
cout <<"b=",a;
};
17 | P a g e
Worksheet 2
For each of the problems write a C++ code to perform the required task. Your
program should be based on the flow chart you drawn in the first worksheet.
1. Receive a number and determine whether it is odd or even.
2. Obtain two numbers from the keyboard, and determine and display which (if
either) is the larger of the two numbers.
3. Receive 3 numbers and display them in ascending order from smallest to largest
4. Add the numbers from 1 to 100 and display the sum
5. Add the even numbers between 0 and any positive integer number given by the user.
6. Find the average of two numbers given by the user.
7. Find the average, maximum, minimum, and sum of three numbers given by the user.
8. Find the area of a circle where the radius is provided by the user.
9. Swap the contents of two variables using a third variable.
10. Swap the content of two variables without using a third variable.
11. Read an integer value from the keyboard and display a message indicating if this
number is odd or even.
12. read 10 integers from the keyboard in the range 0 - 100, and count how many
of them are larger than 50, and display this result
13. Take an integer from the user and display the factorial of that number
18 | P a g e