You are on page 1of 16

2017 [FUNDAMENTAL PROGRAMMING]

Chapter Two

1. Fundamentals of the C/C++ Programming Language


1.1. Brief history of c/c++

Dennis MacAlistair Ritchie was an American computer scientist who "helped shape the digital
era". He created the C programming language and with long-time colleague Ken Thompson,
the Unix operating system. Ritchie and Thompson received the Turing Award from the ACM in
1983, the Hamming Medal from the IEEE in 1990 and the National Medal of Technology from
President Clinton in 1999. Ritchie was the head of Lucent Technologies System Software
Research Department when he retired in 2007.

Bjarne Stroustrup is a Danish computer scientist, most notable for the creation and development
of the widely used C++ programming language in 1979 at Bell laboratories in Murray Hill,
New Jersy. C++ was originally called as “C with classes “, however the name was changed to C+
+ in 1983.

C++ is derived from the C language. Strictly speaking, it is a superset of C: Almost every correct
statement in C is also a correct statement in C++, although the reverse is not true. The most
important elements added to C to create C++ concern classes, objects, and object-oriented
programming. However, C++ has many other new features as well, including an improved
approach to input/output (I/O) and a new way to write comments.

The main difference between C and C++ is that C++ is object oriented while C is function or
procedure oriented. Object oriented programming is focused on writing programs that are more
readable and maintainable. It also helps the reuse of code by packaging a group of similar objects
or using the concept of component programming model.  It helps thinking in a logical way by
using the concept of real world concepts of objects, inheritance and polymorphism.

C, PASCAL, FORTRAN, and similar languages are procedural languages. That is, each
statement in the language tells the computer to do something: Get some input, add these
numbers, divide by six, display that output. A program in a procedural language is a list of
instructions. For instance, the printf() and scanf() functions, input/output in C are seldom used in
C++ because cout and cin do a better job.

Prepared by: Abnet A. Page | 1


2017 [FUNDAMENTAL PROGRAMMING]

1.2. Interpreted vs. Compiled Languages

We can make a number of distinctions between different programming languages depending on


how we write and use their programs. Firstly, a useful distinction to make is between an
interpreted language and a compiled language. Some languages, including BASIC, are
interpreted languages: this means that after you write the program, you can run (or execute) the
program straight away. With compiled languages you have to perform an intermediate step,
called the compilation. Compiling a program simply means translating it into a language that the
computer can understand. Once this has been done the computer can run your program.

1.3. Procedural vs. Object-Oriented Programs

Historically, most programming languages have been procedural languages. This means that
programs work by executing a sequence of instructions provided by the programmer. Examples
of procedural languages include BASIC, PASCAL and C. More recently, another way of
programming has gained in popularity, known as object-oriented programming. Object-oriented
programming languages allow the programmer to break down the problem into objects: self-
contained entities consisting of both data and operations on the data.

1.4. C++ and Object-Oriented Programming

C++ is an object-oriented programming language, but since C++ is derived from C, it also
contains many procedural language features too. The prime purpose of C++ programming was to
add object orientation to the C programming language, which is in itself one of the most
powerful programming languages. The core of the pure object-oriented programming is to create
an object, in code, that has certain properties and methods. An object-oriented language means
that instead of writing sequences of instructions, the programmer defines objects with attributes
and behaviors. There are few principle concepts that form the foundation of object-oriented
programming:

Prepared by: Abnet A. Page | 2


2017 [FUNDAMENTAL PROGRAMMING]

1.4.1. Object

This is the basic unit of object oriented programming. That is both data and function that operate
on data are bundled as a unit called as object.

1.4.2. Class

When you define a class, you define a blueprint for an object. This doesn't actually define any
data, but it does define what the class name means, that is, what an object of the class will consist
of and what operations can be performed on such an object.

1.4.3. Abstraction

Data abstraction refers to, providing only essential information to the outside word and hiding
their background details, i.e., to represent the needed information in program without presenting
the details.

For example, a database system hides certain details of how data is stored and created and
maintained. Similar way, C++ classes provides different methods to the outside world without
giving internal detail about those methods and data.

1.4.4. Encapsulation

Encapsulation is placing the data and the functions that work on that data in the same place.
While working with procedural languages, it is not always clear which functions work on which
variables but object-oriented programming provides you framework to place the data and the
relevant functions together in the same object.

1.4.5. Inheritance

One of the most useful aspects of object-oriented programming is code reusability. As the name
suggests Inheritance is the process of forming a new class from an existing class that is from the
existing class called as base class, new class is formed called as derived class. This is a very
important concept of object-oriented programming since this feature helps to reduce the code
size.

Prepared by: Abnet A. Page | 3


2017 [FUNDAMENTAL PROGRAMMING]

1.4.6. Polymorphism

The ability to use an operator or function in different ways in other words giving different
meaning or functions to the operators or functions is called polymorphism. Poly refers many.
That is a single function or an operator functioning in many ways different upon the usage is
called polymorphism.

1.5.The structure of C++ Programs

The best way to learn a programming language is by writing programs.

A computer program, or a program, is a sequence of statements whose objective is to


accomplish a task. Programming is a process of planning and creating a program. Typically, the
first program beginners write is a program called "Hello World", which simply prints "Hello
World" to your computer screen and it contains all the fundamental components C++ programs
have.

1. // my first program in C++


2. #include <iostream.h>
3. int main ()
4. {
5. cout << "Hello World \n";
6. }

The above program is the first program that most programming writes, and its result is the
printing on screen of the "Hello World!" sentence. It is one of the simpler programs that can be
written in C++, but it already includes the basic components that every C++ program has. We are
going to take a look at them one by one:

Prepared by: Abnet A. Page | 4


2017 [FUNDAMENTAL PROGRAMMING]

1. // my first program in C++

This is a comment line. All the lines beginning with two slash signs (//) are considered comments and do
not have any effect on the behavior of the program. The line explains a brief description of what our
program does.

2. #include <iostream.h>

Only a small number of operations, such as arithmetic and assignment operations, are explicitly
defined in C++. Many of the functions and symbols needed to run a C++ program are provided
as a collection of libraries. Every library has a name and is referred to by a header file. For
example, the descriptions of the functions needed to perform input/output (I/O) are contained in
the header file iostream.h. Similarly, the descriptions of some very useful mathematical
functions, such as power, absolute, and sine, are contained in the header file math.h. If you want
to use I/O or math functions, you need to tell the computer where to find the necessary code. You
use preprocessor directives and the names of header files to tell the computer the locations of the
code provided in libraries. Preprocessor directives are processed by a program called a
preprocessor. Note that the preprocessor commands are processed by the preprocessor before the
program goes through the compiler

Preprocessor directives are commands supplied to the preprocessor that cause the preprocessor to
modify the text of a C++ program before it is compiled. All preprocessor commands begin with
#. There are no semicolons at the end of preprocessor commands because they are not C++
statements.

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.

Prepared by: Abnet A. Page | 5


2017 [FUNDAMENTAL PROGRAMMING]

Example of C++ Standard Library/ Header Files

Header File Description


<algorithm> Standard algorithms that operate on containers
<bitset> Fixed-size sequences of bits
<complex> The numeric type representing complex numbers
<deque> Sequences supporting addition and removal at each end
<exception> Predefined exception classes
<fstream> Stream I/O on files
<functional> Function objects
<iomanip> iostream manipulators
<ios> iostream base classes
<iosfwd> Forward declarations of iostream classes
<iostream> Basic stream I/O functionality
<istream> Input I/O streams
<iterator> Class for traversing a sequence
<limits> Properties of numeric types
<list> Ordered sequences
<locale> Support for internationalization
<map> Associative containers with key/value pairs
<memory> Special memory allocators
<new> Basic memory allocation and deallocation
<numeric> Generalized numeric operations
<ostream> Output I/O streams
<queue> Sequences supporting addition at the head and removal at the tail
<set> Associative container with unique keys
<sstream> Stream I/O using an in-memory string as source or sink
<stack> Sequences supporting addition and removal at the head
<stdexcept> Additional standard exception classes
<streambuf> Buffer classes for iostreams
<string> Sequences of characters
<typeinfo> Run-time type identification
<utility> Comparison operators
<valarray> Value arrays useful for numeric programming
<vector> Sequences supporting random access

3. int main (void)

Prepared by: Abnet A. Page | 6


2017 [FUNDAMENTAL PROGRAMMING]

This line defines a function called main. A function may have zero or more parameters; these
always appear after the function name, between a pair of brackets. The word void appearing
between the brackets indicates that main has no parameters. A function may also have a return
type; this always appears before the function name. The return type for main is int

(i.e. an integer number). All C++ programs must have exactly one main function. Program
execution always begins from main.

4. This brace marks the beginning of the body of main.


5. This line is a statement.

A statement is a computation step which may produce a value. The end of a statement is always
marked with a semicolon (;). This statement causes the string "Hello World \n" to be sent to the
cout output stream. A string is any sequence of characters enclosed in double-quotes. The last
character in this string (\n) is a newline character which is similar to a carriage return on a type
writer. A stream is an object which performs input or output. Cout is the standard output stream
in C++ (standard output usually means your computer monitor screen). The symbol << is an
output operator which takes an output stream as its left operand and an expression as its right
operand, and causes the value of the latter to be sent to the former. In this case, the effect is that
the string "Hello World\n" is sent to cout, causing it to be printed on the computer monitor
screen.

6. This brace marks the end of the body of main.

1.6.Compilation process of C++

Prepared by: Abnet A. Page | 7


2017 [FUNDAMENTAL PROGRAMMING]

A program is a list of instructions that tells the computer to do things. Consider the following
C++ program:

#include <iostream.h>
int main()
{
cout << "My first C++ program." << endl;
return 0;
}

At this point, you need not be too concerned with the details of this program. However, if you
run (execute) this program, it will display the following line on the screen:

My first C++ program.

Recall that a computer can understand only machine language. Therefore, in order to run this
program successfully, the code must first be translated into machine language. In this section, we
review the steps required to execute programs written in C++.

The following steps are necessary to process a C++ program.

1. You use a text editor to create a C++ program following the rules, or syntax, of the high-
level language. This program is called the source code, or source program. The program
must be saved in a text file that has the extension .cpp. For example, if you saved the
preceding program in the file named FirstProgram, then its complete name is
FirstProgram.cpp.

Source program: A program written in a high-level language.

2. The C++ program given in the preceding section contains the statement

#include <iostream.h>. In a C++ program, statements that begin with the symbol # are called
preprocessor directives. These statements are processed by a program called preprocessor.

Prepared by: Abnet A. Page | 8


2017 [FUNDAMENTAL PROGRAMMING]

3. After processing preprocessor directives, the next step is to verify that the program obeys
the rules of the programming language—that is, the program is syntactically correct—and
translate the program into the equivalent machine language. The compiler checks the
source program for syntax errors and, if no error is found, translates the program into the
equivalent machine language. The equivalent machine language program is called an
object program Object program: The machine language version of the high-level
language program.
4. To give C++ programming instructions to your computer, you need an editor and a C++
compiler. An editor is similar to a word processor; it is a program that enables you to
type a C++ program into memory, make changes (such as moving, copying, inserting,
and deleting text), and save the program more permanently in a disk file. After you use
the editor to type the program, you must compile it before you can run it . The C++
programming language is called a compiled language. You cannot write a C++ program
and run it on your computer unless you have a C++ compiler. This compiler takes your
C++ language instructions and translates them into a form that your computer can read. A
C++ compiler is the tool your computer uses to understand the C++ language instructions
in your programs. Many compilers come with their own built-in editor. If yours does, you
probably feel that your C++ programming is more integrated. Once the program is developed
and successfully compiled, you must still bring the code for the resources used from the
IDE into your program to produce a final program that the computer can execute. This
prewritten code (program) resides in a place called the library. A program called a linker
combines the object program with the programs from libraries. Linker is a program that
combines the object program with other programs in the library and is used in the
program to create the executable code. Executable statements perform calculations,
manipulate data, create output, accept input, and so on.
5. You must next load the executable program into main memory for execution. A program
called a loader accomplishes this task. Loader is a program that loads an executable
program into main memory.
6. The final step is to execute the program.

Prepared by: Abnet A. Page | 9


2017 [FUNDAMENTAL PROGRAMMING]

Fig 1: Shows how a typical C++ program is compiled.

1.7.A simple C++ program

//Example 1: Simple Program

Prepared by: Abnet A. Page | 10


2017 [FUNDAMENTAL PROGRAMMING]

#include <iostream.h> //Line 1

int main() //Line 4

{ //Line 5

int NUMBER = 12;

int firstNum; //Line 6

int secondNum; //Line 7

firstNum = 18; //Line 8

cout << "firstNum = " << firstNum << endl; //Line 9

cout << "Line 10: Enter an integer: "; //Line 10

cin >> secondNum; //Line 11

cout << endl;

cout << "Enter secondNum = " << secondNum << endl; //Line 13

firstNum = firstNum + NUMBER + 2 * secondNum; //Line 14

cout << "Line 15: The new value of " << "firstNum = " << firstNum << endl; //Line 15

return 0; //Line 16

1.8.INPUT/OUTPUT IN C++
I. The standard input stream (cin):

Prepared by: Abnet A. Page | 11


2017 [FUNDAMENTAL PROGRAMMING]

The predefined object cin is an instance of istream class. The cin object is said to be attached to
the standard input device, which usually is the keyboard.

The syntax of cin together with >> is:

cin >> variable >> variable ...;

This is called an input (read) statement. In C++, >> is called the stream extraction operator.

//Example 2:
#include <iostream.h>
int main( )
{
char name[50];
cout << "Please enter your name: ";
cin >> name;
cout << "Your name is: " << name << endl;
}

When the above code is compiled and executed, it will prompt you to enter a name. You enter a
value and then hit enter to see the result something as follows:

Please enter your name: cplusplus

Your name is: cplusplus

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 single statement. To request
more than one datum you can use the following:

cin >> name >> age;


This will be equivalent to the following two statements:
cin >> name;
cin >> age;

II. The standard output stream (cout):

Prepared by: Abnet A. Page | 12


2017 [FUNDAMENTAL PROGRAMMING]

The predefined object cout is an instance of ostream class. The cout object is said to be
"connected to" the standard output device, which usually is the display screen(monitor). The
cout is used in conjunction with the stream insertion operator, which is written as << which are
two less than signs as shown in the following example.

The general syntax of cout together with << is:

cout << expression or manipulator << expression or manipulator...;

This is called an output statement. In C++, << is called the stream insertion operator. Generating
output with cout follows two rules:

1. The expression is evaluated, and its value is printed at the current insertion point on the output
device.

2. A manipulator is used to format the output. The simplest manipulator is endl (the last character
is the letter endl), which causes the insertion point to move to the beginning of the next line.

//Example 3:
When the above code is compiled and
#include <iostream.h>
executed, it produces the following result:
int main( )
{
Hello
cout << "Hello"; // prints Hello
cout << Hello; // prints the content of variable Hello

The C++ compiler also determines the data type of variable to be output and selects the
appropriate stream insertion operator to display the value. The << operator is overloaded to
output data items of built-in types integer, float, double, strings and pointer values.

The insertion operator << may be used more than once in a single statement as shown above and
endl is used to add a new-line at the end of the line.

Prepared by: Abnet A. Page | 13


2017 [FUNDAMENTAL PROGRAMMING]

1.9. COMMENTS IN C++

A comment is a piece of descriptive text which explains some aspect of a program. Program
comments are totally ignored by the compiler and are only intended for human readers. C++
provides two types of comment delimiters: Two types of comments

A Single line comment begins with two slashes (//) and continues to the end of the line on which
it is placed. Everything encountered in that line after // is ignored by the compiler

A Multiple line comment begins with a single slash and an asterisk (/*) and ends with an
asterisk and a slash (*/).The compiler ignores anything that appears between /* and */.

/* This program calculates the weekly gross pay for a worker, based on the total number of hours
worked and the hourly pay rate. */

//Example 4:
#include <iostream.h>
int main (void)
{
int workDays = 5; // Number of work days per week
float workHours = 7.5; // Number of work hours per day
float payRate = 33.50; // Hourly pay rate
float weeklyPay; // Gross weekly pay
weeklyPay = workDays * workHours * payRate;
cout << "Weekly Pay = " << weeklyPay << '\n';

Prepared by: Abnet A. Page | 14


2017 [FUNDAMENTAL PROGRAMMING]

Comments should be used to enhance (not to hinder) the readability of a program. The following
two points, in particular, should be noted:

I. A comment should be easier to read and understand than the code which it tries to
explain.
II. Over-use of comments can lead to even less readability.
III. Use of descriptive names for variables and other entities in a program, and proper
indentation of the code can reduce the need for using comments.
IV. Comments are not executable statements.
V. Comments are always neglected by compilers.
VI. Comments are replaced by whitespaces during preprocessors phase.
VII. Comment can be written anywhere and any times number of times
VIII. Comment can be used for documentation.

1.10. Understanding and Fixing Errors

There are three types of error: syntax errors, logical errors and run-time errors. (Logical
errors are also called semantic errors).

I. Syntax Errors

A syntax error is a violation of the syntax, or grammatical rules, of a natural language or a


programming language. Errors in syntax are detected during compilation. For example, consider
the following C++ statements:

int x; //Line 1
int y //Line 2
double z; //Line 3
y = w + x; //Line 4

When these statements are compiled, a compilation error will occur at Line 2 because the
semicolon is missing after the declaration of the variable y. A second compilation error will
occur at Line 4 because the identifier w is used but has not been declared.

Prepared by: Abnet A. Page | 15


2017 [FUNDAMENTAL PROGRAMMING]

It is very common for the omission of a single character to cause four or five error messages.

Compilers not only discover syntax errors, but also hint and sometimes tell the user where the
syntax errors are and how to fix them.

In generally, some common syntax errors include

1. Omitting or misplacing braces, parentheses, etc.


2. Misplaced end-of-comment
3. Typographical errors (in names, etc.)
4. Misplaced keywords

II. Semantics Errors/Logic Errors

The set of rules that gives meaning to a language is called semantics. For example, the order-of-
precedence rules for arithmetic operators are semantic rules.

1. May obey grammar rule, but violate other rules of the language.
2. Performing an incorrect operation on a primitive type value
3. Invoking a member function not defined
4. Not declaring a variable before using it
5. Providing multiple declarations of a variable
6. Failure to include a library header

III. Run-time Errors

 Occur during program execution (runtime!)


 Occur when the C++ run-time library detects an operation that it knows to be incorrect
 Cause program to halt execution

Examples of run-time errors include

1. Division by zero
2. Array index out of bounds
3. Null pointer reference

Prepared by: Abnet A. Page | 16

You might also like