Chapter - 2 - Fundamentals of C++ Programming
Chapter - 2 - Fundamentals of C++ Programming
CHAPTER TWO
C++ PROGRAMMING LANGUAGE
2.1. A Brief History of C++
C++, as the name implies, is essentially based on the C programming language. The C
programming language was devised in the early 1970s at Bell Laboratories by Dennis
Ritchie. C++ was developed by Bjarne Stroustrup starting in 1979 at Bell Labs in Murray
Hill, New Jersey, as an enhancement to the C language and originally named C with Classes
but later it was renamed C++ in 1983. C++ is a superset of C.
C++ is a statically typed, compiled, general-purpose, case-sensitive, free-form programming
language that supports procedural, object-oriented, and generic programming. It is regarded
as a middle-level language, as it comprises a combination of both high-level and low-level
language features.
Standard Libraries
Standard C++ consists of three important parts:
a) The core language giving all the building blocks including variables, data types and
literals, etc.
b) It gives a rich set of functions manipulating files, strings, etc.
c) The Standard Template Library (STL) giving a rich set of methods manipulating data
structures, etc.
2.2. Steps of Writing a C++ Program
When you write a program you are typing a code. The code you type is the source code. The
process of taking your source code and creating an executable code is called compiling. The
C++ programs typically go through six phases: edit, preprocess, compile, link, load and
execute.
1. Edit – (Creating a Program)
This is accomplished with an editor program. C++ editors are like Dev-C++, Visual-C++,
NetBeans, Eclipse, etc. You type a C++ program (called source code) using the editor. C++
source code filenames often end with the .cpp.
2. Preprocess
3. Compile
Then, the C++ compiler translates the program code (source code into an object code). The
outcome may be incomplete due to the program referring to library routines which are not
defined as a part of the program. For example, the << operator which is actually defined in a
separate IO library.
4. Linking
C++ programs typically contain references to functions and data defined elsewhere, such as
in the standard libraries. The object code produced by the C++ compiler typically contains
“holes” due to these missing parts. A linker links the object code with the code for the
missing functions to produce an executable program (with no missing pieces). If the program
compiles and links correctly, an executable image is produced.
5. Loading
Before a program can be executed, it must first be placed in memory. This is done by the
loader, which takes the executable image from disk and transfers it to memory. Additional
components from shared libraries that support the program are also loaded.
6. Execution
Finally, the computer, under the control of its CPU, executes the program one instruction at a
time. Some modern computer architectures can execute several instructions in parallel.
It is summarized as follows:
In practice all these steps are usually invoked by a single command and the user will not even
see the intermediate files generated.
Generally, each steps of writing a full C++ program and how each steps are connected to
each others are shown with the following figure.
You can type the text as shown above (simple Program.cpp) into an editor and save it to a
file named simple Program.cpp. The common file extension of c++ source code is .cpp.
After creating this file with a text editor and compiling it, you can run the program. The
program prints the message.
(Simple
Program.cpp) contains six non-blank lines of code described as follows:
►
This line is a preprocessing directive. All preprocessing directives within C++ source code
begin with a # symbol. This one directs the preprocessor to add some predefined source code
to our existing source code before the compiler begins to process it. This process is done
automatically and is invisible to us.
Here we want to use some parts of the iostream library, a collection precompiled C++ code
that C++ programs (like ours) can use. The iostream library contains routines that handle
input (cin) and output (cout) that include functions such as printing to the display, getting
user input from the keyboard, and dealing with files.
Two items used in (Simple Program.cpp), cout and endl, are not part of the C++ language
itself. These items, along with many other things related to input and output, were developed
in C++, compiled, and stored in the iostream library. The compiler needs to be aware of these
iostream items so it can compile our program. The #include directive specifies a file, called a
header, that contains the specifications for the library code. The compiler checks how we use
cout and endl within our code against the specifications in the <iostream> header to ensure
that we are using the library code correctly.
Most of the programs we write use this #include <iostream> directive, and some programs
we will write in the future will #include other headers as well.
►
The name std stands for “standard,” and the using namespace std line indicates that some of
the names we use in our program are part of the so-called “standard namespace.” With this
line in our program, the compiler knows that we will be using routines that belong to the
standard library.
►
This specifies the real beginning of our program. Here we are declaring a function named
main. All C++ programs must contain this function to be executable. The opening curly
brace ‘{‘ at the end of the line marks the beginning of the body of a function. The body of a
function contains the statements the function is to execute.
►
The body of our main function contains only one statement. This statement directs the
executing program to print the message This is a simple C++ program! on the screen. A
statement is the fundamental unit of execution in a C++ program. All statements in C++ end
with a semicolon (;).
►
The return statement causes the main function to finish. It may be followed by a 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 closing curly brace marks the end of the body of a function. Both the open curly brace
and close curly brace are required for every function definition.
2.4. Data Types
It is s set of values together with a set of operations. When programming, we store the
variables in our computer's memory, but the computer must know what we want to store in
them since storing a simple number, a letter or a large number is not going to occupy the
same space in memory.
Our computer's memory is organized in bytes. A byte is the minimum amount of memory
that we can manage. A byte can store a relatively small amount of data, usually an integer,
decimal numbers, etc. But in addition, the computer can manipulate more complex data types
that come from grouping several bytes, such as long numbers or numbers with decimals.
There are two types of data types.
a) Built-in Data Types
b) User-defined Data Types
A. Built-in Data Types - are data types the come within the IDE. There are a number of
basic data types built in to all programming languages. C++ built-in data types fall into
the following three categories. They are:
It is the fundamental data type in C++ because it becomes a building block for the structured
data type. There are three categories of simple data:
1) Integral - is a data type that deals with integers, or numbers without a decimal part.
2) Floating-point - is a data type that deals with decimal numbers.
3) Enumeration - is a user-defined data type. The enumeration type is C++'s method for
allowing programmers to create their own simple data types.
It is summarized as follows with their corresponding storage spaces.
(Boolean) expressions. In C++, bool, true, and false are reserved words.
c) char Data Types
Almost universally, a char has 8 bits so that it can hold one of 256 different values. The 256
values represented by an 8 bit byte can be interpreted as the values 0 to 2 5 5 or as the values
127 to 127. The data type char is the smallest integral data type. It is mainly used to represent
characters that is, letters, digits, and special symbols. Thus, it can represent every key on
your keyboard. When using the char data type, you enclose each character represented within
single quotation marks.
Examples of values belonging to the char data type include the following: 'A', 'a', '0', '*', '+',
'$', '&', ' '
Note that a blank space is a character and is written as ' ', with a space between the single
quotation marks.
The data type char allows only one symbol to be placed between the single quotation marks.
Thus, the value 'abc' is not of the type char. All the individual symbols located on the
keyboard that are printable may be considered as possible values of the char data type.
Escape Character
To represent real numbers, C++ uses a form of scientific notation called floating-point
notation. The following table shows how C++ might print a set of real numbers using one
machine’s interpretation of floating-point notation. In the C++ floating-point notation, the
letter E stands for the exponent.
C++ provides three data types to manipulate decimal numbers: float, double, and long
double. On most newer compilers, the data types double and long double are the same. As in
the case of integral data types, the data types float, double, and long double differ in the set of
values.
a) float Data Types
The data type float is used in C++ to represent any real number between -3.4E+38 and
3.4E+38. The memory allocated for a value of the float data type is four bytes.
b) double Data Types
The data type double is used in C++ to represent any real number between -1.7E+308 and
1.7E+308. The memory allocated for a value of the double data type is eight bytes.
The maximum and minimum values of the data types float and double are system dependent.
Other than the set of values, there is one more difference between the data types float and
double. The maximum number of significant digits that is, the number of decimal places in
float values is six or seven. The maximum number of significant digits in values belonging to
the double type is 15.
The maximum number of significant digits is called the precision. Sometimes float values
are called single precision, and values of type double are called double precision. If you are
dealing with decimal numbers, for the most part you need only the float type; if you need
accuracy to more than six or seven decimal places, you can use the double type.
Note:-
In C++, by default, floating-point numbers are considered of type double. Therefore, if
you use the data type float to manipulate floating-point numbers in a program, certain
compilers might give you a warning message, such as ‘‘truncation from double to float.’’
To avoid such warning messages, you should use the double data type.
B. User Define Data Type – It allows programmers to create their own data types. Such
kind data types is called enumerations. It has the following format. You can create a new
name for an existing type using keyword typedef.
The first row includes mathematical symbols for addition, subtraction, multiplication,
and division.
The second row consists of punctuation marks taken from English grammar. Note that
the comma is also a special symbol. In C++, commas are used to separate items in a list.
Semicolons are used to end a C++ statement. Note that a blank, which is not shown
above, is also a special symbol. You create a blank symbol by pressing the space bar
(only once) on the keyboard.
The third row consists of tokens made up of two characters that are regarded as a single
symbol. No character can come between the two characters in the token, not even a
blank.
B. Identifier
Identifiers are names of things that appear in programs, such as variables, constants, and
functions. All identifiers must obey C++’s rules for identifiers.
A C++ identifier consists of letters, digits, and the underscore character ( _ ) and must begin
with a letter or underscore.
Some identifiers are predefined; others are defined by the user. In the C++ program in
Example:-
cout and cin - is a predefined identifier and
Num, Today20, etc. - is a user-defined identifier.
Valid Invalid
Abc m/h
ABC Main
25or6to4 Double
1_time first name
a_1 student Number
String
_______
Whitespaces
Every C++ program contains whitespaces. Whitespaces include blanks, tabs, and newline
characters. In a C++ program, whitespaces are used to separate special symbols, reserved
words, and identifiers. Whitespaces are nonprintable in the sense that when they are printed
on a white sheet of paper, the space between special symbols, reserved words, and identifiers
is white. Proper utilization of whitespaces in a program is important. They can be used to
make the program readable.
C. Keywords (Reserved Words)
Some of the word symbols include the following: int, float, double, char, const, void,
return. The letters that make up a reserved word are always lowercase. It is considered to
be a single symbol.
Furthermore, word symbols cannot be redefined within any program; that is, they cannot be
used for anything other than their intended use.
The following table shows the keywords that exists in C++:
The operator << is called the stream insertion or put to operator. It inserts the contents of the
variable on its right to the object on its left.
Example:-
Output:
Hello Word
The cout command tells:
The C++ compiler to redirect the output to the default display device, usually that¡¦s
the monitor.
It is short form for console output or Common output.¡¨
<< Operator must be after cout.
The arrows literally point you in the direction the text will be sent.
The code is sent out of the program, thus the arrows point out of the code.
endl command:
It causes the insertion point to move to the beginning of the next line.
To use it just end your quotation marks, then type the << endl command, and
terminate it with a semicolon.
It is useful in creating a new line.
It flushes C++¡¦s buffer stream, means that as you send content to the screen via cout,
it is placed in a temporary buffer.
It causes that buffer to be emptied.
B. The Standard Input Stream (cin – Common Input)
It is used to get data in from the user. Input is handled with the cin command. A single input
statement can read more than one data item by using the operator >> several times. Every
occurrence of >> extracts the next data item from the input stream.
Syntax:
The operator >> is known as extraction or get from operator & assigns it to the variable on its
right.
Example1:-
When the above code is compiled and executed, it will prompt you to enter a dept and year.
The C++ compiler also determines the data type of the entered value and selects the
appropriate stream extraction operator to extract the value and store it in the given variables.
The stream extraction operator >> may be used more than once in a sing le statement. To
request more than one datum you can use the following:
cin>>dept>>year;
This will be equivalent to the following two statements:
cin>>dept;
cin >>year;
Other Input Options
The two other most commonly used methods are get and getline.
The get function will retrieve a single character, no matter how much the user types in.
The getline function will retrieve a certain number of characters, a number that you
specify. This is particularly important when putting the data into an array.
Simply using the cin will allow the user to try and put more characters into the array than it
can hold. This is referred to as overflowing. The getline function allows you to specify how
many bytes you will get from the user¡¦s input. Each character the user types takes up one
byte.
Example:-
The getline is the safe choice if you want to enter a string of characters into an array.
2.7. Comments in C++
The program that you write should be clear not only to you, but also to the reader of your
program. Part of good programming is the inclusion of comments in the program. Typically,
comments can be used to
► Identify the authors of the program,
► Give the date when the program is written or modified,
► Give a brief explanation of the program, and
► Explain the meaning of key statements in a program.
Comments are for the reader, not for the compiler. So when a compiler compiles a program to
check for the syntax errors, it completely ignores comments. In C++, comments are shown in
green.
Example:-