100% found this document useful (1 vote)
244 views16 pages

Chapter - 2 - Fundamentals of C++ Programming

The document provides an overview of the C++ programming language and the steps involved in writing a C++ program. It discusses that C++ was developed in the 1970s as an enhancement to the C programming language. It then summarizes the six main steps in writing a C++ program: editing source code, preprocessing, compiling, linking, loading, and executing. Finally, it provides details on the structure of a basic C++ program, including the typical inclusion of header files, namespace declarations, main function, and return statement.

Uploaded by

Fikadu
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
100% found this document useful (1 vote)
244 views16 pages

Chapter - 2 - Fundamentals of C++ Programming

The document provides an overview of the C++ programming language and the steps involved in writing a C++ program. It discusses that C++ was developed in the 1970s as an enhancement to the C programming language. It then summarizes the six main steps in writing a C++ program: editing source code, preprocessing, compiling, linking, loading, and executing. Finally, it provides details on the structure of a basic C++ program, including the typical inclusion of header files, namespace declarations, main function, and return statement.

Uploaded by

Fikadu
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 16

Fundamentals of Programming –I- Chapter -2- Handout

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

World Bright, Dept. of Computer Science Page 1 of 16


Fundamentals of Programming –I- Chapter -2- Handout

In a C++ system, a preprocessor program executes automatically before the compiler’s


translation phase begins. The C++ preprocessor obeys commands called preprocessor
directives, which indicate that certain manipulations are to be performed on the program
before compilation. The preprocessor is invoked by the compiler before the program is
converted to machine language. The C++ preprocessor goes over the program text and carries
out the instructions specified by the preprocessor directives (e.g., #include). The result is a
modified program text which no longer contains any directives.

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.

World Bright, Dept. of Computer Science Page 2 of 16


Fundamentals of Programming –I- Chapter -2- Handout

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.

World Bright, Dept. of Computer Science Page 3 of 16


Fundamentals of Programming –I- Chapter -2- Handout

2.3. Structure of C++ Program


Properly written C++ programs have a particular structure. The syntax must be correct, or the
compiler will generate error messages and not produce executable machine language.
General Structure of a Simple C++ Program

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.

World Bright, Dept. of Computer Science Page 4 of 16


Fundamentals of Programming –I- Chapter -2- Handout

(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.

World Bright, Dept. of Computer Science Page 5 of 16


Fundamentals of Programming –I- Chapter -2- Handout


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:

Simple Data Types

World Bright, Dept. of Computer Science Page 6 of 16


Fundamentals of Programming –I- Chapter -2- Handout

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.

I. Integral Data Types


It is further classified into the following nine categories: char, short, int, long, bool, unsigned
char, unsigned short, unsigned int, and unsigned long.
The integral data types that are used are int, bool, and char.
a) int Data Types - Integers in C++, as in mathematics, are numbers such as the
following: -6728, -67, 0, 78, 36782, +763 Note the following two rules from these
examples:
1) Positive integers do not need a + sign in front of them.
2) No commas are used within an integer. Recall that in C++, commas are used
to separate items in a list. So 36,782 would be interpreted as two integers: 36
and 782.
b) bool Data Types
The data type bool has only two values: true and false. Also, true and false are called the
logical (Boolean) values. The central purpose of this data type is to manipulate logical

World Bright, Dept. of Computer Science Page 7 of 16


Fundamentals of Programming –I- Chapter -2- Handout

(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

II. Floating Point Data Types


To deal with decimal numbers, C++ provides the floating-point data type.
For example:

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.

World Bright, Dept. of Computer Science Page 8 of 16


Fundamentals of Programming –I- Chapter -2- Handout

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.

World Bright, Dept. of Computer Science Page 9 of 16


Fundamentals of Programming –I- Chapter -2- Handout

Syntax: - typedef DataType Identifier;


Example: - The following tells the compiler that feet is another name for int:
typedef int feet;
Now, the following declaration is perfectly legal and creates an integer variable called
distance:
feet distance;
From this, feet is an integer data types that the user creates.
2.5. Tokens in C++
The smallest individual unit of a program written in any language is called a token. C++’s
tokens are divided into special symbols, word symbols, and identifiers.
A. Special Symbols
Following are some of the special symbols:

 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.

World Bright, Dept. of Computer Science Page 10 of 16


Fundamentals of Programming –I- Chapter -2- Handout

Predefined identifiers can be redefined, but it would not be wise to do so.


Identifiers can be made of only letters, digits, and the underscore character; no other symbols
are permitted to form an identifier.

In C++, identifiers can be of any length.


Example: - The following are legal identifiers in C++: first, conversion, payRate, counter1,
etc.
The following table shows some illegal identifiers and explains why they are illegal.

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)

World Bright, Dept. of Computer Science Page 11 of 16


Fundamentals of Programming –I- Chapter -2- Handout

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++:

2.6. Input/ Output in C++


The C++ standard libraries provide an extensive set of input/output. It is a common
operations required for C++ programming. C++ I/O occurs in streams (is a sequence of
characters from source to the destination), which are sequences of bytes. If bytes flow from a
device likes a keyboard, a disk drive, or a network connection etc to main memory, this is
called input operation and if bytes flows from main memory to a device like a display
screen, a printer, a disk drive, or a network connection, etc, this is called output operation.
I/O Library Header Files
The following header files are an important to C++ programs.
► <iostream> - It defines the cin, cout, cerr and clog objects, which correspond to the
standard input stream, the standard output stream, the un-buffered standard error
stream and the buffered standard error stream, respectively. (Buffer - a part of RAM
used for temporary storage of data that is waiting to be sent to a device).
When you include a header file, you have access to all the functions defined in that file. By
including this file you will have access to a number of functions for input and output. The
two most important functions are cout and cin. Virtually all your input and output needs (at
least for keyboard input and screen output) can be handled by these two functions.

World Bright, Dept. of Computer Science Page 12 of 16


Fundamentals of Programming –I- Chapter -2- Handout

A. The Standard Output Stream (cout)


It might be a message to the user, a response for input, or the results of some data that the
program has computed. C++ provides some functions that handle screen output for you. The
first, cout, is how you display data to the screen.
Syntax:

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)

World Bright, Dept. of Computer Science Page 13 of 16


Fundamentals of Programming –I- Chapter -2- Handout

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.

World Bright, Dept. of Computer Science Page 14 of 16


Fundamentals of Programming –I- Chapter -2- Handout

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:-

There are two common types of comments in a C++ program


► Single-line comments and
► Multiple-line comments.
A. Single-Line Comments - begin with // and can be placed anywhere in the line.
Everything encountered in that line after // is ignored by the compiler.
Example: - Consider the following statement:
cout << "7 + 8 = " << 7 + 8 << endl;
You can put comments at the end of this line as follows:
cout << "7 + 8 = " << 7 + 8 << endl; //prints: 7 + 8 = 15
This comment could be meaningful for a beginning programmer.
B. Multiple-Line Comments - are enclosed between /* and */. The compiler ignores
anything that appears between /* and */.

World Bright, Dept. of Computer Science Page 15 of 16


Fundamentals of Programming –I- Chapter -2- Handout

Example: - The following is an example of a multiple-line comment:

@@@@@@@@@@@@@@ THE END @@@@@@@@@@@@@@@@@@@@

World Bright, Dept. of Computer Science Page 16 of 16

You might also like