You are on page 1of 117

Chapter One

Introduction

What is programming?
Programming is a skill that can be acquired by a computer professional that gives him/her the
knowledge of making the computer perform the required operation or task.

 Computer programming is critical if one wants to know how to make the computer perform
a task. Most users of a computer only use the available applications on the computer.
Computer programmers produce these applications. Thus if someone is interested to make
such kind of applications, he/she needs to learn how to talk to the computer, which is
learning computer programming.
 Computer programming is the act of writing computer programs, which are a sequence of
instructions written using a Computer Programming Language to perform a specified task by the
computer
 Programming Language: is a set different category of written symbols that instruct computer
hardware to perform specified operations required by the designer.
 A computer program is a sequence of instructions written using a Computer Programming
Language to perform a specified task by the computer.

1.1 Why do we need to learn computer programming?


 Increased ability to express ideas.
• It is believed that the depth at which we think is influenced by the expressive power of the
language in which we communicate our thoughts. It is difficult for people to conceptualize
structures they can’t describe, verbally or in writing.
• Language in which they develop Software places limits on the kinds of control structures,
data structures, and abstractions they can use.
 Improved background for choosing appropriate languages
• Many programmers, when given a choice of languages for a new project, continue to use
the language with which they are most familiar, even if it is poorly suited to new projects.
 Greater ability to learn new languages
• Programming languages are still in a state of continuous evolution, which means
continuous learning is essential.
• Programmers who understand the concept of Object Oriented programming (OOP) will
have easier time learning Java.
 Understand significance of implementation
• Understanding of implementation issues leads to an understanding of why languages are
designed the way they are.
 Ability to design new languages
•The more languages you gain knowledge of, the better understanding of programming
languages concepts you understand.
 Overall advancement of computing
• In some cases, a language became widely used, at least in part, because those in positions
to choose languages were not sufficiently familiar with Programming Language concepts.

1.2 Overview of Computer Organization


Regardless of differences in physical appearance, virtually every computer may be envisioned as
being divided into six logical units or sections:
 Input Unit: it obtains information from various input devices and places this information at
the disposal of the other units so that the information may be processed or stored.
 Output Unit: it takes information that has been processed by the computer and places it on
various output devices to make the information available for use outside the computer.
 Memory unit: it retains information that has been entered through the input unit, so the
information may be made immediately available for processing when it is needed. The
memory unit also retains processed information until that information can be placed on
output devices by the output unit.
 Central Processing Unit (CPU): it is the computer’s coordinator and is responsible for
supervising the operations of the other sections. CPU tells the input unit when information
should be read into memory, tells ALU when information from the memory should be used
in calculation and tells output unit when to send information from the memory to certain
output devices.
 Arithmetic and Logic unit: is a part found inside the Central Processing Unit and is responsible
for performing calculations such as addition, subtraction, multiplication and division. It also
performs comparisons.
 Secondary Storage device: Programs or data used by other units normally are placed on
secondary storage devices (such as disks) until they are needed, possibly hours, days,
months, or even years later.

1.3 Understand programming languages


There are many different types of programming languages and not any computer programming language
can do anything. There are limitations, and actually, different languages are used for different tasks.
Web languages

Used for creating and editing pages on the web. Can do anything from putting plain text on a webpage, to
accessing and retrieving data from a database.

 HTML: - Hyper Text Markup Language. The core language of the world wide web (WWW.) that
is used to define the structure and layout of web pages by using various tags and attributes.
Although a fundamental language of the web, HTML is static - content created with it does not
change. HTML is used to specify the content a webpage will contain, not how the page functions.
 XML: - Extensible Markup Language. A language developed by the W3C which works like
HTML, but unlike HTML, allows for custom tags that are defined by programmers. XML allows
for the transmission of data between applications and organizations through the use of its custom
tags.
 JavaScript: - A language developed by Netscape used to provide dynamic and interactive content
on webpages. With JavaScript it is possible to communicate with HTML, create animations, create
calculators, validate forms, and more. JavaScript is often confused with Java, but they are two
different languages.
 PHP: - Hypertext Preprocessor. A powerful language used for many tasks such as data encryption,
database access, and form validation.
 Java: - A powerful and flexible language created by Sun Microsystems that can be used to create
applets (a program that is executed from within another program) that run inside webpages as well
as software applications. Things you can do with Java include interacting with the user, creating
graphical programs, reading from files, and more. Java is often confused with JavaScript, but they
are two different languages.

Software languages

Used for creating executable programs. Can create anything from simple console programs that print some
text to the screen to entire operating systems.

 C: - An advanced programming language used for software application development. Originally


developed by Dennis Ritchie at Bell Labs in the 1970's and designed to be a systems programming
language but since then has proven itself to be able to be used for various software applications
such as business programs, engineering programs, and even games.
 C++: - Descendant of the C language. The difference between the two languages is that C++ is
object-oriented. C++ was developed by Bjarne Stroustrup at Bell Labs and is a very popular
language for graphical applications.
 Visual Basic: - A language developed by Microsoft based on the BASIC language. Visual Basic
is used for creating Windows applications. The VBScript language (also developed by Microsoft)
is based on Visual Basic.
 Java: - A powerful and flexible language created by Sun Microsystems that can be used to create
applets (a program that is executed from within another program) that run inside webpages as well
as software applications. Things you can do with Java include interacting with the user, creating
graphical programs, reading from files, and more.

1.4 Programming paradigms


A programming paradigm is a style or “way” of programming. Some languages make it easy to write in
some paradigms but not others. Programming is a creative process carried out by programmers to instruct
a computer on how to do a task. A program is a set of instructions that tells a computer what to do in order
to come up with a solution to a particular problem. There are a number of alternative approaches to the
programming process, referred to as programming paradigms. Different paradigms represent
fundamentally different approaches to building solutions to specific types of problems using
programming. Most programming languages fall under one paradigm, but some languages have elements
of multiple paradigms. Three of the most important programming paradigms are the procedural paradigm,
functional paradigm, and the object-oriented paradigm. Let us look at each of these in a bit more detail.

1.4.1 Procedural programming

Procedural programming uses a list of instructions to tell the computer what to do step-by-step.
Procedural programming relies on - you guessed it - procedures, also known as routines or subroutines. A
procedure contains a series of computational steps to be carried out. Procedural programming languages
are also known as top-down languages.

Procedural programming is intuitive in the sense that it is very similar to how you would expect a program
to work. If you want a computer to do something, you should provide step-by-step instructions on how to
do it. It is, therefore, no surprise that most of the early programming languages are all procedural. Newer
paradigms (such as Object-Oriented programming) and modern businesses programming languages (such
as C++, Java and C#) are built on the principles of procedural programming. Examples of procedural
languages include FORTRAN, COBOL and C, which have been around since the 1960s and 70s.

1.4.2 Functional programming


The Functional Programming paradigm views all subprograms as functions in the mathematical sense-informally,
they take in arguments and return a single solution. The solution returned is based entirely on the input, and the
time at which a function is called has no relevance. The computational model is therefore one of function application
and reduction. Functional languages include Lisp/Scheme, Haskell, OCaml, Joy, etc

1.4.3 Object-oriented programming

Object-oriented programming, or OOP, is an approach to problem-solving where all computations are


carried out using objects. An object is a component of a program that knows how to perform certain
actions and how to interact with other elements of the program. Objects are the basic units of object-
oriented programming. A simple example of an object would be a person. Logically, you would expect a
person to have a name. This would be considered a property of the person. You would also expect a person
to be able to do something, such as walking. This would be considered a method of the person.

A method in object-oriented programming is like a procedure in procedural programming. The key


difference here is that the method is part of an object. In object-oriented programming, you organize your
code by creating objects, and then you can give those objects properties and you can make them do certain
things.

A key aspect of object-oriented programming is the use of classes. A class is a blueprint of an object. You
can think of a class as a concept, and the object as the embodiment of that concept. So let's say you want
to use a person in your program. You want to be able to describe the person and have the person do
something. A class called 'person' would provide a blueprint for what a person looks like and what a person
can do. Examples of object-oriented languages include C#, Java, Perl and Python.

1.5 Compilers and interpreters

 Any program written in a languages other than machine languages needs to be translated to
machine language. The set of instructions that do this task are known as translators.
 There are different kinds of translator software, among the compilers and interpreters are of
interest for most programmers.
 Compilers: a compiler is a computer program that translate a serous of statements written in source
code (a collection of statements in a specific programming language) into a resulting object code
(translated instructions of the statements in a programming language). A compiler changes or
translates the whole source code into executable machine code (also called object code) which is
output to a file for latter execution. E.g. C++, Pascal, FORTRAN, etc.
 Interpreters: is a computer program that translate a single high-level statement and executes it and
then goes to the next high level language line etc. E.g. QBASIC, Lisp etc.

1.6 Problem solving techniques


Problem Solving
 Problem solving is the process of transforming the description of a problem into the solution
by using our knowledge of the problem domain and by relying on our ability to select and
use appropriate problem-solving strategies, techniques, and tools.
 A problem is an undesirable situation that prevents the organization from fully achieving its
purpose, goals and objectives. Or problem can also be defined as the gap between the existing
and the desired situation where problem solving will try to fill this gap.
There are two approaches of problem solving:
 Top down design: is a systematic approach based on the concept that the structure of the
problem should determine the structure of the solution and what should be done in lower
level. This approach will try to disintegrate a larger problem into more smaller and
manageable problems to narrow the problem domain.
 Bottom up design: is the reverse process where the lowest level component are built first and
the system builds up from the bottom until the whole process is finally completed.

1.6.1 Basic Program development tips


The program we design in any programming language need to be:
 Reliable: the program should always do what it is expected to do and handle all
types of exception.
 Maintainable: the program should be in a way that it could be modified and
upgraded when the need arises.
 Portable: It needs to be possible to adapt the software written for one type of
computer to another with minimum modification.
 Efficient: the program should be designed to make optimal use of time, space and
other resources of the computer.

1.7 Algorithm
An algorithm is procedure consisting of a finite set of unambiguous rules (instructions) which specify a
finite sequence of operations that provides the solution to a problem, or to a specific class of problems
for any allowable set of input quantities (if there are inputs). In other word, an algorithm is a step-by-
step procedure to solve a given problem.
Properties of algorithm:-
• Finiteness: Algorithm must complete after a finite number of steps.
• Definiteness: Each step must be clearly defined, having one and only one interpretation. At each point
in computation, one should be able to tell exactly what happens next.
• Sequence: Each step must have a unique defined preceding and succeeding step. The first step (start
step) and last step (halt step) must be clearly noted.
• Correctness: It must compute correct answer all possible legal inputs.
• Language Independence: It must not depend on any one programming language.
• Completeness: It must solve the problem completely.
• Effectiveness: It must be possible to perform each step exactly and in a finite amount of time.
• Efficiency: It must solve with the least amount of computational resources such as time and space.
• Input/Output: There must be a specified number of input values, and one or more result values.
E.g., Find the average of three numbers.
We might usually specify the procedure of solving this problem as “add the three numbers and divide by
three”. Here, Read (or Ask) and Write (or Say) are implied. However, in an algorithm, these steps have
to be made explicit. Thus a possible algorithm is:
Step 1: start
Step 2: read values of x, y, z
Step 3: s = x + y+ z
Step 4: A = s/3
Step 5: write value of A
Step 6: stop
E.g2. write an algorithm to find the largest among three different numbers entered by user.
Step 1: start
Step 2: declare variables a, b, and c
Step 3: read variables a, b, and c
Step 4: if a > b
Display a is the largest
Else
Display b is the largest
If a > c
Display a is the largest
Else
Display c is the largest
Else
If b > c
Display b is the largest
Else
Display c is the largest
Step 5: stop
Note: pseudocode and flow charts are the two forms or representation methods of algorithms. We will
see each of them in a bit detail in the following sub topics.

1.8 Introduction to pseudo code and flow chart


1.8.1 Pseudocode
Pseudocode is a simple way of writing programming code in English. Pseudocode is not an actual programming
language. It uses short phrases to write code for programs before you actually create it in a specific language. Once
you know what the program is about and how it will function, then you can use pseudocode to create statements to
achieve the required results for your program. It allows the designer to focus on the logic of the algorithm without
being distracted by details of language syntax. At the same time, the pseudocode needs to be complete. It describe
the entire logic of the algorithm so that implementation becomes a rote mechanical task of translating line by line
into source code.

In the other hand pseudocode (which means fake code, because it’s not really programming code) specifies the steps
required to accomplish the task. Pseudocode is a type of structured English that is used to specify an algorithm.
Pseudocode cannot be compiled nor executed, and there are no real formatting or syntax rules. Using pseudo code
have many advantages to the programmer, some of this are reduced complexity, increased flexibility, and ease of
understanding.

Why is pseudocode necessary?


 The programming process is a complicated one.
 You must first understand the program specifications.
 Then you need to organize your thoughts and create the program.
 You must break the main tasks that must be accomplished into smaller ones in order to be able to eventually
write fully developed code.
 Writing Pseudocode will save you time later during the construction & testing phase of a program's
development.

Rules used to write pseudocode


1. Write only one statement per line
Each statement in your pseudocode should express just one action for the computer. If the task list is
properly drawn, then in most cases each task will correspond to one line of pseudocode.
E.g., task list:
Read name, hourly rate, hours worked, deduction rate
Perform calculations
gross = hourlyRate * hoursWorked
deduction = grossPay * deductionRate
net pay = grossPay – deduction
Write name, gross, deduction, net pay
PSEUDOCODE:
READ name, hourlyRate, hoursWorked, deductionRate
grossPay = hourlyRate * hoursWorked
deduction = grossPay * deductionRate
netPay = grossPay – deduction
WRITE name, grossPay, deduction, netPay
2. Capitalize initial keyword
In the example above, READ and WRITE are in caps. We will use just a few keywords:
READ, WRITE, IF, ELSE, ENDIF, WHILE, ENDWHILE, REPEAT, UNTIL
3. Indent to show hierarchy
We will use a particular indentation pattern in each of the design structures:
SEQUENCE: keep statements that are “stacked” in sequence all starting in the same column.
SELECTION: indent the statements that fall inside the selection structure, but not the keywords that
form the selection
LOOPING: indent the statements that fall inside the loop, but not the keywords that form the loop
E.g. In the example above, employees whose grossPay is less than 100 do not have any deduction.
TASK LIST:
Read name, hourly rate, hours worked, deduction rate
Compute gross, deduction, net pay
Is gross >= 100?
YES: calculate deduction
NO: no deduction
Write name, gross, deduction, net pay
PSEUDOCODE:
READ name, hourlyRate, hoursWorked
grossPay = hourlyRate * hoursWorked
IF grossPay >= 100
deduction = grossPay * deductionRate
ELSE
deduction = 0
ENDIF
netPay = grossPay – deduction
WRITE name, grossPay, deduction, netPay
4. End multiline structures
See how the IF/ELSE/ENDIF is constructed above. The ENDIF (or END whatever) always is in line
with the IF (or whatever starts the structure).
5. Keep statements language independent
There may be special features available in the language you plan to eventually write the program in; if
you are SURE it will be written in that language, then you can use the features. If not, then avoid using
the special features.
Advantages and disadvantages of pseudocode
Disadvantages
 There is no accepted standard, so it varies widely from company to company
Advantages
 Can be done easily on a word processor
 Easily modified
 Implements structured concepts well
Algorithm vs Pseudocode
An algorithm is simply a solution to a problem. An algorithm presents the solution to a problem as a well-
defined set of steps or instructions. Pseudo-code is a general way of describing an algorithm.

1.8.2 Flow chart


A flowchart is a graphical representation of an algorithm. These flow charts plays vital role in the
programming of a problem and are quite helpful in understanding the logic of complicated and lengthy
problems. Once the flow chart is drawn, it becomes easy to write the program in any high level
language.

Some of commonly used flow chart symbols and their corresponding name and purpose:
General Rules for flowcharting

1. All boxes of the flowchart are connected with Arrows. (Not lines)
2. Flowchart symbols have an entry point on the top of the symbol with no other entry points.
The exit point for all flowchart symbols is on the bottom except for the Decision symbol.
3. The Decision symbol has two exit points; these can be on the sides or the bottom and one side.
4. Generally, a flowchart will flow from top to bottom. However, an upward flow can be shown
as long as it does not exceed 3 symbols.
5. Connectors are used to connect breaks in the flowchart. Examples are:
 From one page to another page.
 From the bottom of the page to the top of the same page.
 An upward flow of more than 3 symbols
Flow-charts for basic control structures

SEQUENCE

 Steps that execute in sequence are represented by symbols that follow each other top to bottom
or left to right.
 Top to bottom is the standard.

SELECTION

 Once the condition is evaluated, the control flows in to one of two paths.
 Once the conditional execution is finished, the flows rejoin before leaving the structure.
LOOP

 Either the processing repeats or the control leaves the structure.


 Notice that the return line joins the entry line before the question.

E.g. Draw a flowchart: a program which accepts two numbers from user and find the average.
First write the algorithm
Input X
Input Y
Sum = X + Y
Average = sum/2
Output the average
E.g., draw a flowchart: Algorithm for find the greater number between two numbers.

Q: Draw a flow chart for a program that accepts three numbers from user which are A, B, and C
and find the largest number?

1.9 How to write pseudo code and draw flow chart for a given algorithm
How to write pseudocode statement
We have to consider the following basic computer operations while writing pseudo code statement.
1. Input: A computer can receive information Read (information from a file) Get (information from the
keyboard).
2. Output: A computer can put out information Write (information to a file) Display (information
to the screen).
3. A computer can perform arithmetic operations.
Use actual mathematical symbols or the words for the symbols.
Example:
Add number to total
Total = total + number
+, -, *, / Calculate, Compute also used
4. A computer can assign a value to a piece of data. To give data an initial value, to assign a value as
a result of some process, and to store a value for later use (save).
5. Decision: A computer can compare two piece of information and select one of the alternative
actions.
IF condition THEN
Some action
ELSE
Alternative action
ENDIF
6. Repetition: A computer can repeat a group of actions
WHILE condition (is true)
Some action
ENDWHILE

FOR a number of times
Some action
ENDFOR
Example: - Write a program that obtains two integer numbers from the user. It will print out the sum of
those numbers.
Pseudo code: -
1. Prompt the user to enter the first integer
2. Prompt the user to enter a second integer
3. Compute the sum of the two user inputs
4. Display an output prompt that explains the answer as the sum
5. Display the result
Flow chart
1.10 Advantages of using Flowcharts
As we discussed flow chart is used for representing algorithm in pictorial form. This pictorial
representation of a solution/system is having many advantages. These advantages are as follows:
 Communication: A Flowchart can be used as a better way of communication of the logic of a
system and steps involve in the solution, to all concerned particularly to the client of system.
 Effective analysis: A flowchart of a problem can be used for effective analysis of the problem.
 Documentation of Program/System: Program flowcharts are a vital part of a good program
documentation. Program document is used for various purposes like knowing the components in
the program, complexity of the program etc.
 Efficient Program Maintenance: Once a program is developed and becomes operational it needs
time to time maintenance. With help of flowchart maintenance become easier.
 Coding of the Program: Any design of solution of a problem is finally converted into computer
program. Writing code referring the flowchart of the solution become easy.
CHAPTER TWO

Basics of C++ programming

2.1. Introduction
Imagine a language that makes your computer perform to your personal specifications! Maybe you have
looked for a program that keeps track of your household budget, exactly as you prefer but haven’t found
one. Perhaps you want to track the records of a small (or large) business with your computer, but you
haven’t found a program that prints reports exactly as you’d like them. Possibly you have thought of a
new and innovative use for a computer and you would like to implement your idea. C++ gives you the
power to develop all these uses for your computer.
If your computer could understand English, you would not have to learn a programming language. But
because it does not understand English, you must learn to write instructions in a language your computer
recognizes. C++ is a powerful programming language. Even if you’ve never programmed a computer
before, you will soon understand that programming in C++ is rewarding. Becoming an expert programmer
in C++ or in any other computer language takes time and dedication. Nevertheless, you can start writing
simple programs with little effort. After you learn the fundamentals of C++ programming, you can build
on what you learn and hone your skills as you write more powerful programs. You also might see new
uses for your computer and develop programs others can use. This chapter and the next chapters all deals
about programming constructs like elements of programming, control statements, functions and so on.

2.2. C++ IDEs

It’s hard to keep track of all the great IDEs (Integrated Development Environments) and IDE-like tools
available to developers. These tools enhance developer’s workflows, reduce debugging time, and make
them more productive. IDEs go beyond typical text editors by integrating compiling, code completion,
syntax highlighting, debugging, profiling, and testing and much more in one comprehensive user interface.
Without the power of an IDE, you must use all these components separately in your development
workflow. While some developers may prefer that, an IDE can significantly speed your programming and
provide an overall better experience. There is a wealth of choices in IDEs, so focusing on the best C++
IDEs helped narrow down the list of excellent options. In the end, personal preference will outweigh many
of the pros and cons of each environment. There are a number of IDEs and some of the examples are as
follows.
Visual Studio: Visual Studio is the most popular choice for good reasons: this mature tool is cross-
platform, supports many programming languages, and is packed with an incredible array of features.
Visual Studio’s code compilation technology (named IntelliSense) is widely praised and relied on daily
by many developers. It has excellent syntax highlighting, easy to use UI designer, CMake support, and a
powerful debugger and profiler system. In addition, it has a huge community so there’s no shortage of
know-hows, samples and more.

Code Blocks: is a cross-platform, free, and open-source IDE for C/C++ development that includes
compiling, auto code compilation, code coverage, profiling, debugging, code analysis, and more. It’s
known for its outstanding performance and intuitive interface (drag and drop, tabs) and for allowing full
breakpoints. It features a healthy ecosystem of plugins by the community and the Code::Blocks
development team.

CLion: it is a commercial cross-platform IDE for C/C++. JetBrains enjoys a loyal following of developers
that love their excellent code editors featuring superb code refactoring tools. CLion includes code analysis,
CMake support, project modeling with intelligent code assistance. CLion is one of the few IDEs to have
local and remote (via SSH) support, allowing you to code on your local machine but compile on remote
servers. While CLion is focused exclusively on C/C++, it is based on the JetBrains IDE framework with
versions for the most popular programming languages.

Eclipse: it is a free and open-source cross-platform IDE written in Java and originally constructed to
replace IBM’s now-discontinued VisualAge IDE. Eclipse is more of a framework than a complete IDE,
relying on a wide array of plugins to provide language-specific functionality. Eclipse supports nearly thirty
programming languages, and the C/C++ flavor is named Eclipse CDT (Eclipse C/C++ Development
Tooling). Eclipse is well known for its simplicity and broad community support. It offers all the standard
features one would expect in a C/C++ IDE, like code completion, compilation and debugging support,
static code analysis, profiling, and refactoring.

CodeLite: it is another free and open-source IDE. It supports C/C++, PHP, and JavaScript and is built
with the wxWidgets cross-platform toolkit, allowing it to run on Windows, macOS, Linux, and FreeBSD.
The editor is based on the open-source Scintilla project.
CodeLite provides a simple but comprehensive user interface and includes support for project
management, refactoring, code completion, syntax highlighting, debugging via GNU’s gdb, and
integration with source code management systems like Git and Subversion. The IDE also includes a
wxWidgets creation tool that allows developers to design cross-platform graphical user interfaces easily.

Dev C++: is a fully-featured open-source IDE for C++. While Dev C++ boasts an impressive feature set,
it only supports the Windows operating system. Despite this limitation, it includes support for GCC-based
compilers like Cygwin and MinGW. In addition, it has an integrated debugger (via gdb), international
language support, code compilation, syntax-highlighting editor, a tool manager, find and replace options,
CVS support, and code printing.

2.3. Process of compiling and running programs


There are six major types of programming process:
1. Editing process
2. Preprocessing
3. Compiling
4. Linking
5. Loading, and
6. Executing or running

Consider the following example:


#include<iostream>
using namespace std;
int main()
{
cout<<”hello world”;
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:
Hello world
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. Editing: - 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 lab1, then its complete name is lab1.cpp. Source program: A program written in a
high-level language.
2. Preprocessing: - The C++ program given in the preceding section contains the statement
#include <iostream>. In a C++ program, statements that begin with the symbol # are called
preprocessor directives. These statements are processed by a program called preprocessor.
3. Compiling: - 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. Linking: - The programs that you write in a high-level language are developed using an integrated
development environment (IDE). The IDE contains many programs that are useful in creating your
program. For example, it contains the necessary code (program) to display the results of the program
and several mathematical functions to make the programmer’s job somewhat easier. Therefore, if
certain code is already available, you can use this code rather than writing your own code. 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: A program that combines the object
program with other programs in the library and is used in the program to create the executable code.
5. Loading: - You must next load the executable program into main memory for execution. A program
called a loader accomplishes this task. Loader: A program that loads an executable program into
main memory.
6. Execution or run: -The final step is to execute the program.

Process on a diagram
2.4. Structure of C++ program
A C++ program

//include headers; these are modules that include functions that you may use in your

//program; we will almost always need to include the header that

// defines cin and cout; the header is called iostream

When learning a new language, the first program people usually write is one that salutes the world :)

Here is the Hello world program in C++.

A C++ program is a collection of one or more subprograms, called functions.

Every C++ program has a function called main.

The smallest individual unit of a program written in any language is called a token.

Let us look at a simple code that would print the words Hello World.

// my first program in C++

#include <iostream>

Using namespace std;

// main () is where program execution begins.

int main ()
{

Cout<< "Hello World! "; // prints Hello World!

return 0;

The previous program is the typical program that programmer apprentices write for the first time, and its
result is the printing on screen of the "Hello World!" sentence. It is one of the simplest programs that can
be written in C++, but it already contains the fundamental components that every C++ program has. We
are going to look line by line at the code we have just written:

// my first program in C++

This is a comment line. All lines beginning with two slash signs (//) are considered comments and do not
have any effect on the behavior of the program. The programmer can use them to include short
explanations or observations within the source code itself. In this case, the line is a brief description of
what our program is.

#include <iostream>

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. In this case the directive #include
<iostream>tells the preprocessor to include the iostream standard file. This specific file (iostream)
includes the declarations of the basic standard input-output library in C++, and it is included because its
functionality is going to be used later in the program.

Using namespace std;

All the elements of the standard C++ library are declared within what is called a namespace, the namespace
with the name std. So in order to access its functionality we declare with this expression that we will be
using these entities. This line is very frequent in C++ programs that use the standard library, and in fact it
will be included in most of the source codes included in these tutorials.

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 ones 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 are these
parentheses that follow its name. Optionally, these parentheses may enclose a list of parameters within
them. Right after these parentheses we can find the body of the main function enclosed in braces ({}).
What is contained within these braces is what the function does when it is executed.

cout << "Hello World!";

This line is a C++ statement. A statement is a simple or compound expression that can actually produce
some effect. In fact, this statement performs the only action that generates a visible effect in our first
program. 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). cout is declared in the iostream standard file within the
stdnamespace, so that's why we needed to include that specific file and to declare that we were going to
use this specific namespace earlier in our code. Notice that the statement ends with a semicolon character
(;). This character is used to mark the end of the statement and in fact it must be included at the end of all
expression statements in all C++ programs (one of the most common syntax errors is indeed to forget to
include some semicolon after a statement).

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.

2.5. Basic syntax and semantics of high-level languages


Syntax is the rule of the programming language (like grammar in English language). We will see the
syntax of C++ program in structure of C++ program section at the end of this chapter. Semantics is the
business logic of the program. What the program is written to do. The objective of the program.
2.6. Basic elements of programming
There are several elements which programming languages, and programs written in them, typically
contain. These elements are found in all languages, not just in C++. If you understand these elements and
what they're for, not only will you understand C++ better, but you will also find learning other
programming languages, and moving between different programming languages, much easier. We will
see some of the basic elements of programming in detail. Some of the basic elements of C++ programming
are Identifiers, variables, literals (constants), keywords (reserved words), comments, data types,
expressions, operators, and statements.

2.6.1. Identifier
Various data items with symbolic names in C++ is called as Identifiers. Following data items are called
as Identifier in C++. Names of functions, names of arrays, names of variables, and names of classes.
The rules of naming identifiers in C++:
 C++ is case-sensitive so that Uppercase Letters and Lower Case letters are different.
 The name of identifier cannot begin with a digit. However, Underscore (_) can be used as first
character while declaring the identifier.
 Only alphabetic characters, digits and underscore (_) are permitted in C++ language for declaring
identifier.
 Other special characters are not allowed for naming a identifier
 Keywords cannot be used as Identifier.

Some examples of invalid identifiers:


Identifier Validity Reason
1digit Invalid Digit at first location is not allowed
digit-1 Invalid Special characters other than underscore is not allowed
num 1 Invalid Space not allowed
Num Valid Obeys the rule of identifiers
_num Valid Obeys the rule of identifiers
Num1 Valid Obeys the rule of identifiers
A Valid Obeys the rule of identifiers

2.6.2. Keywords (reservedwords)


A reserved word is a special word in a programming language that cannot be used as a name. A
programmer cannot usually change the meaning of these words without losing the original meaning of the
word. The syntax rules (or grammar) of C++ define certain symbols to have a unique meaning within a
C++ program. These symbols, the reserved words, must not be used for any other purposes. All reserved
words are in lower-case letters. Some of the reserved words in C++ are:
Auto enum private This
Break extern protected Throw
Case float public Try
catch For register typedef
Char friend return union
class goto short unsigned
const If signed virtual
continue inline sizeof void
default Int static volatile
delete Long struct while
double New switch static_cast

2.6.3. Variables
The usefulness of the "Hello World" programs shown in the previous section is quite questionable. We
had to write several lines of code, compile them, and then execute the resulting program just to obtain a
simple sentence written on the screen as result. It certainly would have been much faster to type the output
sentence by ourselves. However, programming is not limited only to printing simple texts on the screen.
In order to go a little further on and to become able to write programs that perform useful tasks that really
save us work we need to introduce the concept of variable.

Let us think that I ask you to retain the number 5 in your mental memory, and then I ask you to memorize
also the number 2 at the same time. You have just stored two different values in your memory. Now, if I
ask you to add 1 to the first number I said, you should be retaining the numbers 6 (that is 5+1) and 2 in
your memory. Values that we could now for example subtract and obtain 4 as result. The whole process
that you have just done with your mental memory is a simile of what a computer can do with two variables.
The same process can be expressed in C++ with the following instruction set:

a = 5;
b = 2;
a = a + 1;
result = a - b;
Obviously, this is a very simple example since we have only used two small integer values, but consider
that your computer can store millions of numbers like these at the same time and conduct sophisticated
mathematical operations with them.
Therefore, we can define a variable as a portion of memory to store a determined value. Or in simple
definition variables are reserved memory location to store a value.
Each variable needs an identifier that distinguishes it from the others, for example, in the previous code
the variable identifiers were a, b and result, but we could have called the variables any names we
wanted to invent, as long as they were valid identifiers. The name of a variable can be composed of letters,
digits, and the underscore character. It must begin with either a letter or an underscore. Upper and
lowercase letters are distinct because C++ is case-sensitive.
2.6.4. Data types
Why we need to learn data types? Every variable used in program hold data, and every data must have
their own type. It is the way how we can ‘measure’ the variable’s data value as exist in the real world.
Furthermore by knowing the data range, we can use data efficiently in our program in term of memory
management (storage allocation) aspects. While doing programming in any programming language, you
need to use various variables to store various information. Variables are nothing but reserved memory
locations to store values. This means that when you create a variable you reserve some space in memory.
You may like to store information of various data types like character, integer, floating point, double
floating point, Boolean etc. Based on the data type of a variable, the operating system allocates memory
and decides what can be stored in the reserved memory.
C++ categorizes data types in to three parts
1. Simple data types (store only one value at a time and building blocks of structured data
types)
 Integrals (which are integers or numbers without decimal point)
 Floating point (which are numbers with decimal points)
 Enumerators (which are user defined data types)
2. Structured data types (in contrast with simple data types which stores more than one
value with the same data type)
 Arrays-the same data types
 Structures- different data types
3. Pointers (is the memory address of your computer)

Primitive Built-in Types:


C++ offer the programmer a rich assortment of built-in as well as user defined data types. Following
table lists down basic C++ data types:

Type Keyword
Boolean bool
Character Char
Integer Int
Floating point float
Double floating point double
Several of the basic types can be modified using one or more of these type modifiers:
 signed
 unsigned
 short
 long

The following table shows the variable type, how much memory it takes to store the value in memory,
and what is maximum and minimum value, which can be stored in such type of variables.
Type Typical Bit Width Typical Range

bool 1 byte True or false

Char 1byte -127 to 127 or 0 to 255

unsigned char 1byte 0 to 255

signed char 1byte -127 to 127

Int 4bytes -2147483648 to 2147483647

unsigned int 4bytes 0 to 4294967295

signed int 4bytes -2147483648 to 2147483647

short int 2bytes -32768 to 32767

unsigned short int 2bytes 0 to 65,535

signed short int 2bytes -32768 to 32767

long int 4bytes -2,147,483,648 to 2,147,483,647

signed long int 4bytes same as long int

unsigned long int 4bytes 0 to 4,294,967,295

Float 4bytes +/- 3.4e +/- 38 (~7 digits)

Double 8bytes +/- 1.7e +/- 308 (~15 digits)

long double 8bytes +/- 1.7e +/- 308 (~15 digits)

Wchar_t (wild charactor) 2 or 4 bytes 1 wise charactor

N:B: The sizes of variables might be different from those shown in the above table, depending on the
compiler and the computer you are using.

Bool (Boolean):- true, & false


Before bool became part of Standard C++, everyone tended to use different techniques in order to
produce Boolean-like behavior. These produced portability problems and could introduce subtle errors.
The Standard C++ bool type can have two states expressed by the built-in constants true (which
converts to an integral one) and false (which converts to an integral zero). All three names are
keywords. In addition, some language elements have been adapted:

Element Usage with bool


&& || ! Take bool arguments and produce bool results.
< > <= >= == != Produce bool results.
if, for, while, do(u will learn on next chapter) Conditional expressions convert
to bool values. ? : First operand converts to bool value. Because there’s a lot of existing code that uses
an int to represent a flag, the compiler will implicitly convert from an int to a bool (nonzero values will
produce true while zero values produce false). Ideally, the compiler will give you a warning as a
suggestion to correct the situation.
Integer (int). Represent the set of integer numbers.
 In practice, computers have a limitation representing integer numbers.
 For a 32-bit machine, int can represent the numbers in the interval [-(231-1), 231-1].[-2147483648,
2147483647]
 Arithmetic operators: +, -, *, /, %Integer division and remainder: 13 / 3 = 4, 13 % 3 = 1
Note: 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.

wchar_t / Wide character Data Type


The "wchar_t" data type is used to display wide characters that will occupy 16 bits. This datatype
occupies "2 or 4" bytes. Mostly the wchar_t datatype is used when international languages like japanese
are used. If any character begins with L (uppercase only), it is a wide character (e.g., L'x') and should be
stored in wchar_t type of variable. Otherwise, it is a narrow character literal (e.g., 'x') and can be stored
in a simple variable of char type.

Example:
#include <iostream>
Using namespace std;
int main()
{
wchar_t w;
w = L'A';
cout << "Wide character value::" << w << '\n';
cout << "Size of the wide char is::" << sizeof(w);
return 0;
}
Output
Wide character value::65 // if you enter A
Size of the wide char is::2
Enumeration type: is a user defined data type or a data type which are note primitive. Data type is a set
of values together with a set of operations on those values.
To define a new simple data type or a user defined data type, called enumeration type, we need
three things:
 A name for the data type
 A set of values for the data type
 A set of operations on the values

A new simple data type can be defined by specifying its name and the values, but not the operations and
the values must be identifiers.
Syntax: enum typeName {value1, value2, value3,…,valuen};
value1, value2,… are identifiers called enumerators
value1 < value2 < value3 <...
Enumeration type is an ordered set of values if a value has been used in one enumeration type it can’t be
used by another in same block and also the same rules apply to enumeration types declared outside of any
blocks.
E.g. enum daysOfWeek {Monday, Tuesday, Wednesday, Thursday, Friday, Saturday,
Sunday}; this example defines a new datatype called daysOfWeek and the values belonging to this data type are
Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, and Sunday.
Consider the following additional examples.
E.g1. enum grade {‘A’, ‘B’, ‘C’, ‘D’, ‘F’}; //illegal because ‘ and ’ is not identifier
E.g2. enum places{1st, 2nd, 3rd, 4th}; //illegal because values are not valid identifiers

Variable definition/variable definition in C++


A variable definition means to tell the compiler where and how much to create the storage for the variable.
A variable definition specifies a data type, and contains a list of one or more variables of that type as
follows:
The syntax for variable declaration is:
data_type variable_list;
Here, data_type must be a valid C++ data type including char, int, float, double, bool or any user-defined
object, etc., and variable_list may consist of one or more identifier names separated by commas.
Some valid declarations are shown here:
int a, num1, _xy;
char c, ch;
float f, salary;
double d;

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. For example:
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;
This declares three variables (a, b and c), all of them of type int, and has exactly the same meaning
as:
int a;
int b;
int c;

The integer data types char, short, long and int can be either signed or unsigned depending on
the range of numbers needed to be represented. Signed types can represent both positive and negative
values, whereas unsigned types can only represent positive values (and zero). This can be specified by
using either the specifier signed or the specifier unsigned before the type name. For example:
unsigned short int NumberOfSisters;
signed int MyAccountBalance;
NB: By default, if we do not specify either signed or unsigned most compiler settings will assume the
type to be signed, therefore instead of the second declaration above we could have written:
int MyAccountBalance;

Initialization of variables
When declaring a variable, its value is undetermined by default. But you may want that a variable stores
a concrete value since the moment in which it is declared. In other word variable initialization is called
giving or assigning a value to a variable. In order to do that, you have to append an equal sign followed
by the value wanted to the variable declaration. The syntax of variable initialization is written as
follows.
datatype variableName = initial_value ;
E.g. int x = 1;
Int num1 = 3;
For example, if we want to declare an int variable called num1 that contains the value 0 since the
moment in which it is declared, we could write:
int num1 = 0;
Additionally to this way of initializing variables (known as c-like), C++ has added a new way to
initialize a variable: by enclosing the initial value between parenthesis ():
datatype variableName (initial_value) ;
E.g. int num1 (0);
Both ways are valid and equivalent in C++.
Variable declaration for enumerator data type:
For example, given the following definition
enum sports{BASKETBALL, FOOTBALL, HOCKEY, BASEBALL, SOCCER};
we can declare the following variable
sports popularSport, mySport; // in this example sports is the data type and
popularSport and mySport are variables with the type sports
The statement:
popularSport = FOOTBALL;// FOOTBALL is value of the variable popularSport
stores FOOTBALL into popularSport varibale
The statement:
mySport = popularSport;
copies the value of the popularSport into mySport
Operators in enumerator’s data type
 No arithmetic operations are allowed on enumeration types

• ++ and -- are illegal too:

• Solution: use a static cast:

• An enumeration type is an ordered set of values:

Scope of variables
The scope of variables declared within a function or any other inner block is only their own function or
their own block and cannot be used outside of them. For example, if you declare a variable inside the
function main it would have been impossible to use the variables directly in other functions since they
are variables local to function main.

Therefore, the scope of local variables is limited to the same block level in which they are declared.
Nevertheless, we also have the possibility to declare global variables; these are visible from any point of
the code, inside and outside all functions. In order to declare global variables you simply have to declare
the variable outside any function or block; that means, directly in the body of the program.

2.6.5. Operators
An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations.
C++ is rich in built-in operators and provides the following types of operators. Operators in C++ are
mostly made of signs that are not part of the alphabet but are available in all keyboards. This makes C++
code shorter and more international, since it relies less on English words, but requires a little of learning
effort in the beginning. In C++ there the basic operators are the following:
 Arithmetic operators
 Relational operators
 Logical operators
 Bitwise operators
 Assignment operators
 Other operators

Arithmetic operators: - the following arithmetic operators are supported by C++ programming language.
Assume A is equal to 21, and B is equal to 10.
Operator Description Example
+ Adds two operands A + B will give 31
- Subtracts second operand from the first A - B will give 11
* Multiplies both operands A * B will give 210
/ Divides number by de-numerator A / B will give 2
% Modules operator and remainder of after an integer A % B will give 1
division
++ Increment operator, increases integer value by one A ++ will give 22
-- Decrement operator, decreases integer value by one A -- will give 20

Try the following example to understand all the arithmetic operators available in C++.
#include <iostream>
using namespace std;
main()
{
int a = 21;
int b = 10;
int c;
c = a + b;
cout << "Value of c is:" << c << endl ; output
c = a - b;
Value of c is :31
cout << "Value of c is :" << c << endl ;
c = a * b; Value of c is :11
cout << "Value of c is :" << c << endl ; Value of c is :210
c = a / b;
Value of c is :2
cout << "Value of c is :" << c << endl ;
c = a % b; Value of c is :1
cout << "Value of c is :" << c << endl ; Value of c is :22
c = a++;
Value of c is :21
cout << "Value of c is :" << c << endl ;
c = a--;
cout << "Value of c is :" << c << endl ;
return 0;
}
Both the increment and decrement operators can either precede (prefix) or follow (postfix) the operand.
For example:
x = x + 1;
Can be written as
++x; // prefix form
X++; //postfix form
When an increment or decrement is used as part of an expression, there is an important difference in prefix
and postfix forms. If you are using prefix form then increment or decrement will be done before rest of
the expression, and if you are using postfix form, then increment or decrement will be done after the
complete expression is evaluated.

E.g., the following example will help you to understand this difference.

Output
Line 1 - Value of a++ is :21

Line 2 - Value of a is :22

Line 3 - Value of ++a is :23

Relational operators: - Each comparison in C++ is a bool type expression with a value of true or
false, where true means that the comparison is correct and false means that the comparison is
incorrect.
E.g: length == circuit // false or true
If the variables var1 and var2 contain the same number, the comparison is true and the value of the
relational expression is true. But if the expressions contain different values, the value of the expression
will be false. When individual characters are compared, the character codes are compared. The result
therefore depends on the character set you are using. The following expression results in the value true
when ASCII code is used.
E.g: 'A' < 'a' // true, since 65 < 97
The following relational operators are supported by C++ programming language.
Assume variable A holds 10 and variable B holds 20.
Operator Description Example
== Checks if the values of two operands are equal or not, if yes then (A == B) is not
condition becomes true. true.
!= Checks if the values of two operands are equal or not, if values (A != B) is true.
are not equal then condition becomes true.
> Checks if the value of left operand is greater than the value of (A > B) is not
right operand, if yes then condition becomes true. true.
< Checks if the value of left operand is less than the value of right (A < B) is true.
operand, if yes then condition becomes true.
>= Checks if the value of left operand is greater than or equal to the (A >= B) is not
value of right operand, if yes then condition becomes true. true.
<= Checks if the value of left operand is less than or equal to the (A <= B) is true.
value of right operand, if yes then condition becomes true.

Logical operators: - The logical operators comprise the Boolean operators && (AND), || (OR), and !
(NOT). They can be used to create compound conditions and perform conditional execution of a program
depending on multiple conditions. A logical expression results in a value false or true, depending on
whether the logical expression is correct or incorrect, just like a relational expression. The following are
logical operators supported by C++ programming language.
Assume a variable A holds 1and variable B holds 0.
Operator Description Example
&& Called Logical AND operator. If both the operands are non- (A && B) is false.
zero, then condition becomes true.
|| Called Logical OR Operator. If any of the two operands is non- (A || B) is true.
zero, then condition becomes true.
! Called Logical NOT Operator. Use to reverses the logical state !(A && B) is true.
of its operand. If a condition is true, then Logical NOT operator
will make false.

Bitwise Operators: - the bitwise operator works on bits and perform bit by bit operation. The truth tables
for &, |, and ^ are as follows.
P q p&q p|q p^q ~p
0 0 0 0 0 1
0 1 0 1 1 1
1 1 1 1 0 0
1 0 0 1 1 0

Assume if A = 60; and B = 13; now in binary format they will as follows
A = 60, then change this number to binary. The binary equivalent of 60 is 0011 1100, B = 13 and the
binary equivalent of 13 is 0000 1101
A = 0011 1100
B = 0000 1101
-----------------
A&B = 0000 1100
A|B = 0011 1101
A^B = 0011 0001
~A = 1100 0011
The Bitwise operators supported by C++ language are listed in the following table. Assume variable A
holds 60 and variable B holds 13, then:
Operator Description Example
& Binary AND Operator copies a bit to the result if it exists (A & B) will give 12
in both operands. which is 0000 1100
| Binary OR Operator copies a bit if it exists in either (A | B) will give 61
operand. which is 0011 1101
^ Binary XOR Operator copies the bit if it is set in one (A ^ B) will give 49
operand but not both. which is 0011 0001
~ Binary Ones Complement Operator is unary and has the (~A ) will give -61
effect of 'flipping' bits. which is 1100 0011
in 2's complement
form due to a signed
binary number.
<< Binary Left Shift Operator. The left operands value is A << 2 will give 240
moved left by the number of bits specified by the right which is 1111 0000
operand.
>> Binary Right Shift Operator. The left operands value is A >> 2 will give 15
moved right by the number of bits specified by the right which is 0000 1111
operand.

Assignment operators: - The assignment operator is used to copy the values from one object to
another already existing object. In C++ programming assignment operators are divided in to two parts
which are simple assignment and compound assignment operators.
Simple assignment operators uses the assignment operator = to assign the value of a variable to an
expression. In expressions of this type the variable must be placed on the left and the assigned value on
the right of the assignment operator.
Compound assignment operators that simultaneously perform an arithmetic operation and an
assignment, for example.
E.g. i += 3; is equivalent to i = i + 3;
i *= j + 2; is equivalent to i = i * (j+2);
The following are C++ programming language assignment operators.
Operator Description Example
= Simple assignment operator, Assigns values from right C = A + B will assign
side operands to left side operand value of A + B into C
+= Add AND assignment operator, It adds right operand C += A is equivalent to
to the left operand and assign the result to left operand C = C + A
-= Subtract AND assignment operator, It subtracts right C -= A is equivalent to
operand from the left operand and assign the result to C=C-A
left operand
*= Multiply AND assignment operator, It multiplies right C *= A is equivalent to
operand with the left operand and assign the result to C=C*A
left operand
/= Divide AND assignment operator, It divides left C /= A is equivalent to
operand with the right operand and assign the result to C = C / A
left operand
%= Modulus AND assignment operator, It takes modulus C %= A is equivalent
using two operands and assign the result to left operand to C = C % A
<<= Left shift AND assignment operator C <<= 2 is same as C =
C << 2
>>= Right shift AND assignment operator C >>= 2 is same as C =
C >> 2
&= Bitwise AND assignment operator C &= 2 is same as C =
C&2
^= bitwise exclusive OR and assignment operator C ^= 2 is same as C =
C^2
|= bitwise inclusive OR and assignment operator C |= 2 is same as C = C
|2

The following example will help you to understand all the assignment operators supported by C++
programming language.
#include <iostream>
using namespace std;
main()
{
int a = 21;
int c ;
c = a;
cout << "Line 1 - = Operator, Value of c = : " <<c<< endl ;
c += a;
cout << "Line 2 - += Operator, Value of c = : " <<c<< endl ;
c -= a;
cout << "Line 3 - -= Operator, Value of c = : " <<c<< endl ;
c *= a;
cout << "Line 4 - *= Operator, Value of c = : " <<c<< endl ;
c /= a;
cout << "Line 5 - /= Operator, Value of c = : " <<c<< endl ;
c = 200;
c %= a;
cout << "Line 6 - %= Operator, Value of c = : " <<c<< endl;
c <<= 2;
cout << "Line 7 - <<= Operator, Value of c = : " <<c<< endl;
c >>= 2;
cout << "Line 8 - >>= Operator, Value of c = : " <<c<< endl;
c &= 2;
cout << "Line 9 - &= Operator, Value of c = : " <<c<< endl;
c ^= 2;
cout << "Line 10 - ^= Operator, Value of c = : " <<c<< endl ;
c |= 2;
cout << "Line 11 - |= Operator, Value of c = : " <<c<< endl ;
return 0;
}
Output
Line 1 - = Operator, Value of c = : 21
Line 2 - += Operator, Value of c = : 42
Line 3 - -= Operator, Value of c = : 21
Line 4 - *= Operator, Value of c = : 441
Line 5 - /= Operator, Value of c = : 21
Line 6 - %= Operator, Value of c = : 11
Line 7 - <<= Operator, Value of c = : 44
Line 8 - >>= Operator, Value of c = : 11
Line 9 - &= Operator, Value of c = : 2
Line 10 - ^= Operator, Value of c = : 0
Line 11 - |= Operator, Value of c = : 2

Other additional operators:- there are few other operators supported by C++.
Operator Description
sizeof sizeof operator returns the size of a variable. For example, sizeof(a),
where a is integer, will return 4.
condition ? X : Y Conditional operator. If Condition is true? then it returns value X :
otherwise value Y
, Comma operator causes a sequence of operations to be performed. The
value of the entire comma expression is the value of the last expression
of the comma-separated list.
cast Casting operators convert one data type to another. For example,
int(2.2000) would return 2.
& Pointer operator & returns the address of an variable. For example &a;
will give actual address of the variable.
* Pointer operator * is pointer to a variable. For example *var; will
pointer to a variable var.

Some examples of this operators are as follows:


The syntax of using sizeof is as follows:
sizeof(dataType)

Try the following example to understand all the sizeof operator available in C++.
Output
Size of char : 1
Size of int : 4
Size of short int : 2
Size of long int : 4
Size of float : 4
Size of double : 8

Cast operators: - A cast is a special operator that forces one data type to be converted into another. As an
operator, a cast is unary and has the same precedence as any other unary operator. The most general cast
supported by most of the C++ compilers is:
Syntax1: (datatype) expression;
E.g. if we want to cast from floating point number 2.5 to integer.
(int) 2.5; //it will change to 2

There is another syntax of casting. The flowing casting operators will be used while working with
classes.
Syntax2: static_cast<dataType>(expression)
E.g. static_cast<int> 2.5; // it will change to 2
For now try the following example to understand a simple cast operator available in C++
#include <iostream>
using namespace std;
main()
{
double a = 21.09399;
float b = 10.20;
int c ;
c = (int) a;
cout << "Line 1 - Value of (int)a is :" << c << endl ;
c = (int) b;
cout << "Line 2 - Value of (int)b is :" << c << endl ;
return 0;
}
Output
Line 1 - Value of (int)a is :21
Line 2 - Value of (int)b is :10

Pointer operators: C++ provides two pointer operators, which are;


(a) Address of Operator &,
(b) Indirection Operator *.

A pointer is a variable that contains the address of another variable or you can say that a variable that
contains the address of another variable is said to "point to" the other variable. A variable can be any
data type including an object, structure or again pointer itself.
The Address of Operator &: The & is a unary operator that returns the memory address of its operand.
For example, if var is an integer variable, then &var is its address. This operator has the same
precedence and right-to-left associativity as the other unary operators. You should read the & operator
as "the address of" which means &var will be read as "the address of var".
The Indirection Operator *: The second operator is indirection Operator *, and it is the complement of
&. It is a unary operator that returns the value of the variable located at the address specified by its
operand.
Let’s try the following example.

Output
Value of var :3000

Value of ptr :0xbff64494

Value of val :3000

Operator precedence in C++


Operator precedence determines the grouping of terms in an expression. This affects how an expression
is evaluated. Certain operators have higher precedence than others; for example, the multiplication
operator has higher precedence than the addition operator:
For example x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher precedence than
+, so it first gets multiplied with 3*2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the table, those with the lowest appear at
the bottom. Within an expression, higher precedence operators will be evaluated first.
Category Operator Associativity
Postfix () [] -> . ++ - - Left to right
Unary + - ! ~ ++ - - (type)* & sizeof Right to left
Multiplicative */% Left to right
Additive +- Left to right
Shift << >> Left to right
Relational < <= > >= Left to right
Equality == != Left to right
Bitwise AND & Left to right
Bitwise XOR ^ Left to right
Bitwise OR | Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left
Comma , Left to right

2.6.6. Constants/literals
Constants refer to fixed values that the program may not alter and they are called literals. Constants can
be of any of the basic data types and can be divided into Integer Numerals, Floating-Point Numerals,
Characters, Strings and Boolean Values. Again, constants are treated just like regular variables except that
their values cannot be modified after their definition.
Integer literals:
An integer literal can be a decimal, octal, or hexadecimal constant. A prefix specifies: 0x or 0X for
hexadecimal, 0 for octal, and nothing for decimal.
An integer literal can also have a suffix that is a combination of U and L, for unsigned and long,
respectively. The suffix can be uppercase or lowercase and can be in any order.
The following are examples of integer literals.
212 // Legal

215u // Legal

0xFeeL // Legal

078 // Illegal: 8 is not an octal digit

032UU // Illegal: cannot repeat a suffix

85 // decimal

0213 // octal

0x4b // hexadecimal

30 // int

30u // unsigned int


30l // long

30ul // unsigned long


Floating-point literals:
A floating-point literal has an integer part, a decimal point, a fractional part, and an exponent part. You
can represent floating point literals either in decimal form or exponential form. While representing using
decimal form, you must include the decimal point, the exponent, or both and while representing using
exponential form, you must include the integer part, the fractional part, or both. The signed exponent is
introduced by e or E.

The following are some examples of floating point literals:


3.14159 // Legal
314159E-5L // Legal
510E // Illegal: incomplete exponent
210f // Illegal: no decimal or exponent
.e55 // Illegal: missing integer or fraction
Boolean literals:
There are two Boolean literals and they are part of standard C++ keywords:
A. A value of true representing true.
B. A value of false representing false.
Character literals:
Character literals are enclosed in single quotes. If the literal begins with L (uppercase only), it is a wide
character literal (e.g., L'x') and should be stored in wchar_t type of variable. Otherwise, it is a narrow
character literal (e.g., 'x') and can be stored in a simple variable of char type. A character literal can be a
plain character (e.g., 'x'), an escape sequence (e.g., '\t'), or a universal character (e.g., '\u02C0'). There are
certain characters in C++ when they are preceded by a backslash they will have special meaning and they
are used to represent like newline (\n) or tab (\t). Here, you have a list of some of such escape sequence
codes:
Escape sequence Meaning

\\ \ character

\' ' character

\" " character

\? ? character

\a Alert or bell
\b Backspace

\f Form feed

\n Newline

\r Carriage return

\t Horizontal tab

\v Vertical tab

String literals:
String literals are enclosed in double quotes. A string contains characters that are similar to character
literals: plain characters, escape sequences, and universal characters. You can break a long line into
multiple lines using string literals and separate them using whitespaces. Here are some examples of string
literals. All the three forms are identical strings.
"hello, dear"
"hello, \
dear"
"hello, " "d" "ear"

Defining/declaring Constants:
There are two simple ways in C++ to define constants:
• Using #define preprocessor.
• Using const keyword.
The #define Preprocessor:
Following is the syntax is used to #define preprocessor to define a constant:
#define identifier value

Following example explains it in detail:


#include <iostream>
using namespace std;
#define LENGTH 10
#define WIDTH 5
#define NEWLINE '\n
int main()
{
int area;
area = LENGTH * WIDTH;
cout << area;
cout << NEWLINE;
return 0;
}
The output will be 50
The const Keyword:
You can use const prefix to declare constants with a specific type as follows:
const type variable = value;
Following example explains it in detail:
#include <iostream>
using namespace std;
int main()
{
const int LENGTH = 10;
const int WIDTH = 5;
const char NEWLINE = '\n';
int area;
area = LENGTH * WIDTH;
cout << area;
cout << NEWLINE;
return 0;
}
The output of the program will be 50
Note that it is a good programming practice to define constants in CAPITALS.

2.6.7. Comments
Program comments are explanatory statements that you can include in the C++ code that you write and
helps anyone reading it's source code. All programming languages allow for some form of comments.
C++ supports single-line and multi-line comments. All characters available inside any comment are
ignored by C++ compiler. C++ comments start with /* and end with */ are called multiline comments.

For example:

/* This is a comment */

/* C++ comments can also


span multiple lines
*/
A comment can also start with //, extending to the end of the line, they are called single line comments
or inline comments in C++. For example:

/*
This is multiline
Comment in C++
*/
#include <iostream>
using namespace std;
main()
{
cout << "Hello World"; // prints Hello World
return 0;
}

2.6.8. Expressions and Statements


Statements: In C++, a statement controls the sequence of execution, evaluates an expression, or does
nothing (the null statement).
Expressions: an expression is a computation which yields a value. It can also be viewed as any
statement that evaluates to a value (returns a value).
E.g. The statement 3+2; returns the value 5 and thus is an expression.
Some examples of an expression:
E.g.1
3.2:- returns the value 3.2
PI: - float constant that returns the value 3.14 if the constant is defined.
secondsPerMinute:- integer constant that returns 60 if the constant is declared
E.g.2: complicated expressions:
x = a + b;
y = x = a + b;
The second line is evaluated in the following order:
1. Add a and b.
2. Assign the result of the expression a + b to x.
3. Assign the result of the assignment expression x = a + b to y.
All C++ statements end with a semicolon.
E.g. x = a + b;
The meaning is: assign the value of the sum of a and b to x.
White spaces: white spaces characters (spaces, tabs, new lines) can’t be seen and generally ignored in
statements. White spaces should be used to make programs more readable and easier to maintain.
Blocks: a block begins with an opening French brace ({) and ends with a closing French brace (}).

2.7. Structure (Anatomy) of c++ program.


As C++ is a programming language so it follows a predefined structure. The program is divided into many
sections, it is important to know the need of every section. The easiest way to understand the basic
structure of C++ program is by writing a program. The basic C++ program is as follows:
The basic structure of C++ program mentioned above can be divided into following sections:
 Documentation Section: This section comprises of comments. As the name suggests, this section
is used to improve the readability and understanding of the program.// (Double Slash)
represents comments in C++ program. Comments can be of single line or multiple lines. Double
Slash comments are used to represent single line comments. For multiple line comment, you can
begin with /* and end with */. For example :

 Linking and Directives Section: The program written above begins with
#include<iostream>. <iostream> represents header file which includes the
functionalities of predefined functions. In linking section, the compiler in-built functions such as
cout<<, cin>> etc are linked with INCLUDE subdirectory’s header file <iostream>. The ‘#’
symbols tells about “address to” or “link to”. Iostream is input/output stream which includes
declarations of standard input-output library in C++.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. In this case the directive #include<iostream> tells the
preprocessor to include the iostream standard file. This specific file (iostream) includes the
declarations of the basic standard input-output library in C++, and it is included because its
functionality is going to be used later in the program.
 using namespace std; All the elements of the standard C++ library are declared within what
is called a namespace, the namespace with the name std. So in order to access its functionality we
declare with this expression that we will be using these entities. This line is very frequent in C++
programs that use the standard library, and in fact it will be included in most of the source codes
included in these tutorials. using namespace std means that you are going to use classes or
functions (if any) from "std" namespace, so you don't have to explicitly call the namespace to
access them.
Example with using namespace std;

Example without using namespace std. you can write your code like this without using namespace
std, but the preferable way is the first one.

 main() Section : This is the section in which the program coding is written. Basically, it acts as
a container for C++ program. The execution of the C++ program begins with main() function
and it is independent of the location of main() function in the program. main() is a function as
represented by parenthesis “()”. This is because it is a function declaration. The body of the main()
function can be found right after these parenthesis, the body is enclosed in braces “{ }”.

 Body of main() Section : The body of the main() function begins with “{“.

 Local Variable Declaration: In this the variables which are used in the body of the main()
functions are declared. These are called the local variables as their scope is limited within
the main() function only, unless they are declared globally outside the main() function.
” int a=10, b=3;” in the above program represents local variables
 Statements to Execute: This section includes statements for reading, writing and executing
data using Input/Output functions, library functions, formulas, conditional statements etc.
Above written program has many executable statements like cout<<“simple c++
program \n”;
 return 0; in the above program causes the function to finish and 0 represents that
function has been executed with zero errors. This is considered as most usual way to end a
C++ program.
 Finally the body of the main() function ends with “}”.
 Global Declaration Section: There are certain programs which requires variables that can be
used in more than one function, so then the variables can be declared outside the main()
function or respective functions. Then those variables become accessible in any of the functions,
hence named as Global Variables as their scope becomes global to the program.
 User Defined Functions: There are certain functions that are called by calling statements from
the main() function. Every function includes local variable declaration section and executable
statement section similar to main program.
3. CHAPTER THREE: CONTROL STATEMENTS

3.1. Introduction:
A running program spends all of its time executing statements. The order in which statements are executed
is called flow control (or control flow). This term reflect the fact that the currently executing statement
has the control of the CPU (Central Processing Unit), which when completed will be handed over (flow)
to another statement. Flow control in a program is typically sequential, from one statement to the next,
but may be diverted to other paths by branch statements.

Sequential Statements
Sequential statements are statements that are executed one after the other in the order they are written in
the source code. In these kinds of statements the flow of control is said to be sequential. In sequential
statements, the order will be determined during program development and cannot be changed.
E.g1
#include<iostream>
using namespace std;
int main(){
cout<<"Hello student \n";
return 0;
}
E.g2
#include<iostream>
using namespace std;
int main()
{
int length, width;
cout<<"Enter width and length\n";
cin>>length>>width;
int area;
area = length * width;
cout<<"Area = "<<area<<endl;
int per;
per = 2 * (length + width);
cout<<"peremetr = "<<per;
return 0;
}
The above both examples are called sequential because they are executed line by line.

Control Structures
A program is usually not limited to a linear sequence of instructions. During its process it may bifurcate,
repeat code or take decisions. For that purpose, C++ provides control structures that serve to specify what
has to be done by our program, when and under which circumstances.
With the introduction of control structures we are going to have to introduce a new concept: the compound
statement or block. A block is a group of statements which are separated by semicolons (;) like all C++
statements, but grouped together in a block enclosed in braces: {}:
{
statement1;
statement2;
statement3;
}
Most of the control structures that we will see in this section require a generic statement as part of its
syntax. A statement can be either a simple statement (a simple instruction ending with a semicolon) or a
compound statement (several instructions grouped in a block), like the one just described. In the case that
we want the statement to be a simple statement, we do not need to enclose it in braces ({}). But in the
case that we want the statement to be a compound statement it must be enclosed between braces ({}),
forming a block.

3.2. Decision making statements


Decision making structures require that the programmer specify one or more conditions to be evaluated
or tested by the program, along with a statement or statements to be executed if the condition is
determined to be true, and optionally, other statements to be executed if the condition is determined to
be false.
Following flow chart shows the general form of a typical decision making structure found in most of the
programming languages:

Programming helps to make a computer a little intelligent or enable to make decisions. The basis of
decision in computing lies ultimately in testing whether an expression is true or false. The tools
available in C++ for making decision are called selection statements.
Note: In C++, zero is considered as a false, and all other values are considered true, although
true is usually represented by 1. Thus, if an expression is false, it is equal to zero, and if an
expression is equal to zero, it is false. If a statement is true, all you know is that it is nonzero, and
any nonzero statement is true.
3.3.Selection statements
Selection statements are statements in a program where there are points at which the program will decide
at runtime whether some part of the code should or should not be executed. There are two types of selection
statements in C++, which are the “if statement” and the “switch statement”.

3.3.1. The if statements


A. The simple if statement.

The if statement consists of a Boolean expression followed by one or more statements.


Syntax:
if(boolean_expression)
{
// statement(s) will execute if the boolean expression is true
}
If the Boolean expression evaluates to true, then the block of code inside the if statement will be executed.
If Boolean expression evaluates to false, then the first set of code after the end of the if statement (after
the closing curly brace) will be executed.
The if keyword is used to execute a statement or block only if a condition is fulfilled. Its form is: if
(condition) statement Where condition is the expression that is being evaluated. If this condition is true,
statement is executed. If it is false, statement is ignored (not executed) and the program continues right
after this conditional structure.
The following flow chart shows the simple if statement.

Let’s look the following example


#include <iostream>
using namespace std;
int main ()
{
int a = 10;
// check the boolean condition
if( a < 20 )
{
// if condition is true then print the following
cout << "a is less than 20;" << endl;
}
cout << "value of a is : " << a << endl;
return 0;
}
When the above code is compiled and executed, it produces the following result:
a is less than 20;
value of a is : 10
For example, the following code fragment prints x is 100 only if the value stored in the x variable is indeed
100:
if (x == 100)
cout<< "x is 100";
If we want more than a single statement to be executed in case that the condition is true we can specify a
block using braces { }:
if (x == 100)
{
cout << "x is ";
cout << x;
}

B. The if else statement.

We can additionally specify what we want to happen if the condition is not fulfilled by using the
keyword else. An if statement can be followed by an optional else statement, which executes when
the Boolean expression is false.
Syntax:
if(boolean_expression)
{
// statement(s); will execute if the boolean expression is true
}
else
{
// statement(s); will execute if the boolean expression is false
}
If the Boolean expression evaluates to true, then the if block of code will be executed, otherwise
else block of code will be executed.
The following flow chart shows the if else statement:

Let’s try to consider the following example:


#include <iostream>
using namespace std;
int main ()
{
int a = 100;
// check the boolean condition
if( a < 20 )
{
// if condition is true then print the following
cout << "a is less than 20;" << endl;
}
else
{
// if condition is false then print the following
cout << "a is not less than 20;" << endl;
}
cout << "value of a is : " << a << endl;
return 0;
}

When the above code is compiled and executed, it produces the following result:
a is not less than 20;
value of a is : 100
C. The if else if statement.

An if statement can be followed by an optional else if...else statement, which is very useful to
test various conditions using single if...else if statement.
When using if, else if, else statements there are few points to keep in mind.

a. An if can have zero or one else's and it must come after any else if's.
b. An if can have zero to many else if's and they must come before the else.
c. Once an else if succeeds, none of he remaining else if's or else's will be tested.

Syntax:
if(boolean_expression 1)
{
// Executes when the boolean expression 1 is true
}
else if( boolean_expression 2)
{
// Executes when the boolean expression 2 is true
}
else if( boolean_expression 3)
{
// Executes when the boolean expression 3 is true
}
else
{
// executes when the none of the above condition is true.
}
Consider the following example:
#include <iostream>
using namespace std;
int main ()
{
int a = 100;
// check the boolean condition
if( a == 10 )
{
// if condition is true then print the following
cout << "Value of a is 10" << endl;
}
else if( a == 20 )
{
// if else if condition is true
cout << "Value of a is 20" << endl;
}
else if( a == 30 )
{
// if else if condition is true
cout << "Value of a is 30" << endl;
}
else
{
// if none of the conditions is true
cout << "Value of a is not matching" << endl;
}
cout << "Exact value of a is : " << a << endl;
return 0;
}

When the above code is compiled and executed, it produces the following result:
Value of a is not matching
Exact value of a is : 100

Let’s look the following example which a number from keyboard and checks weather the number is
negative or positive.
#include<iostream>
using namespace std;
int main(){
int x;
cout<<”enter the number”;
cin>>x;
if (x > 0)
cout << "x is positive";
else if (x < 0)
cout << "x is negative";
else
cout << "x is 0";
return 0;
}

N: B: in case that we want more than a single statement to be executed, we must group them in a
block by enclosing them in braces { }, otherwise using braces for single statement is optional.

D. The nested if statement.

It is always legal to nest if-else statements, which means you can use one if or else if statement inside
another if or else if statement(s). One or more if statements can be nested with in another if statement.
The nesting will be used to test multiple conditions to perform a task. It is always recommended to
indent nested if statements to enhance readability of a program.
Syntax:
if (expression1)
{
if (expression2)
statementsN;
else
statementsM;
}
else
{
if (expression3)
statementsR;
else
statementsT;
}
 StatementsN will be executed if and only if “expression1” and “expression2” are
evaluated and if the outcome of both is none zero (TRUE).
 StatementsM will be executed if and only if “expression1” is TRUE and “expression2” is
FALSE.
 StatementsR will be executed if and only if “expression1” is FALSE and “expression3”
is TRUE.
 StatementsT will be executed if and only if “expression1” is FLASE and “expression3”
is FALSE.

Try to consider the following example:


#include <iostream>
using namespace std;
int main ()
{
int a = 100;
int b = 200;
if( a == 100 )
{
// if condition is true then check the following
if( b == 200 )
{
// if condition is true then print the following
cout << "Value of a is 100 and b is 200" << endl;
}
}
cout << "Exact value of a is : " << a << endl;
cout << "Exact value of b is : " << b << endl;
return 0;
}
When the above code is compiled and executed, it produces the following result:
Value of a is 100 and b is 200
Exact value of a is : 100
Exact value of b is : 200

3.3.2. The switch statement


A switch statement allows a variable to be tested for equality against a list of values. Each value is
called a case, and the variable being switched on is checked for each case.
Syntax:
switch(expression){
case case_value:
statement(s);
break; //optional
case case_value :
statement(s);
break; //optional
// you can have any number of case statements.
default : //Optional
statement(s);

The following rules apply to a switch statement:


 The expression and case_value used in a switch statement must have an integral or
enumerated type.
 You can have any number of case statements within a switch. Each case is followed by the
value to be compared to and a colon.
 The case_value for a case must be the same data type as the variable in the switch.
 When the variable being switched on is equal to a case, the statements following that case will
execute until a break statement is reached.
 When a break statement is reached, the switch terminates, and the flow of control jumps to
the next line following the switch statement.
 Not every case needs to contain a break. If no break appears, the flow of control will fall
through to subsequent cases until a break is reached.
 A switch statement can have an optional default case, which must appear at the end of the
switch. The default case can be used for performing a task when none of the cases is true. No
break is needed in the default case.
Note: It is almost always a good idea to have a default case in switch statements. If you have no
other need for the default, use it to test for the supposedly impossible case, and print out an error
message; this can be a tremendous aid in debugging.
Consider the following example:
#include <iostream>
using namespace std;
int main()
{
int number;
cout << "Enter a number between 1 and 5: ";
cin >> number;
switch (number)
{
case 0: cout << "Too small, sorry!";
break;
case 5: cout << "Good job!\n"; // fall through
case 4: cout << "Nice Pick!\n"; // fall through
case 3: cout << "Excellent!\n"; // fall through
case 2: cout << "Masterful!\n"; // fall through
case 1: cout << "Incredible!\n";
break;
default: cout << "Too large!\n";
break;
}
cout << "\n\n";
return 0;
}
When the above code is executed the output looks like this.
Output 1
Enter a number between 1 and 5: 3
Excellent!
Masterful!
Incredible!

Output 2
Enter a number between 1 and 5: 8
Too large!

Now let us see the effect of including a break statement in the switch statement.
Scenario One Scenario Two
switch (N){ switch(N){
case 1: x=10; case 1: x=10; break;
case 2: x=20; case 2: x=20; break;
case 3: x=30; case 3: x=30; break;
} }
Even if N is 1 or 2 x X will have 10, 20 or 30 based on the
will have 30 value of N
The above scenario can be expressed diagrammatically as follows:

true N==1? true x = 10


N==1? x = 10
false false
break
true true

N==2? x =20 N==2? x = 20

false false
break
true true
false
N==3? x = 30 false N==3? x = 30

break

The break terminates the switch statement by jumping to the very end of it.
There are, however, situations in which it makes sense to have a case without a break. For instance:
#include<iostream>
using namespace std;
int main()
{
int operand1,operand2;
float result;
char operatr;
cout<<"enter two numbers";
cin>>operand1>>operand2;
cout<<"enter operator";
cin>>operatr;
switch(operatr)
{
case '+': result = operand1 + operand2;
cout<<result;
break;
case '-': result = operand1 - operand2;
cout<<result;
break;
case 'x':
case '*': result = operand1 * operand2;
cout<<result;
break;
case '/': result = operand1 / operand2;
cout<<result;
break;
default:
cout<<" unknown operator:"<<operatr<<"\n";
}
return 0;
}
Because case ‘x’ has no break statement (in fact no statement at all!), when this case satisfied, execution
proceeds to the statements of the next case and the multiplication is performed.
Switch evaluates expression and compares the result to each of the case values.
Relational and Boolean operators can be used in switch tag if and only if the expected output is either 0
to represent False or 1 to represent true as that is the only possible output from such operators.

3.4.Repetition or Iterationn/Looping statements


The great power of computers is their ability to perform a task over and over again. With a phenomenal
speed, accuracy and reliability. There may be a situation, when you need to execute a block of code several
number of times. In general statements are executed sequentially: The first statement in a function is
executed first, followed by the second, and so on.
Programming languages provide various control structures that allow for more complicated execution
paths.
A loop statement allows us to execute a statement or group of statements multiple times and following is
the general from of a loop statement in most of the programming languages: The following flow chart
shows the general flow of loop statements:

Three facilities offered by C++ for performing repetition are: the while loop, the do-while loop, and
the for loop.

3.4.1. The while loop


A while loop statement repeatedly executes a target statement as long as a given condition is true. The
while statement (also called while loop) provides a way of repeating a statement or a block as long as a
condition holds / is true.
Syntax:
while(condition)
{
statement(s);
}
Here, statement(s) may be a single statement or a block of statements. The condition may be
any expression, and true is any non-zero value. The loop iterates while the condition is true. When the
condition becomes false, program control passes to the line immediately following the loop.
Flow diagram shows the while loop:

Here, key point of the while loop is that the loop might not ever run. When the condition is tested and
the result is false, the loop body will be skipped and the first statement after the while loop will be
executed.
Let’s look the following example: which adds numbers from 1 to 10:
#include<iostream>
using namespace std;
int main(){
int i = 1;
int sum = 0;
while(i <= 10){
sum = sum + i;
i++;
}
cout<<sum;
return 0;
}
After execution of the following program will display 55
3.4.2. The do…while loop

Unlike the while loop, which test the loop condition at the top of the loop, the do...while loop
checks its condition at the bottom of the loop. A do...while loop is similar to a while loop, except
that a do...while loop is guaranteed to execute at least one time.

Syntax:

do
{
statement(s);
}while( condition );
Notice that the conditional expression appears at the end of the loop, so the statement(s) in the loop
execute once before the condition is tested. If the condition is true, the flow of control jumps back up to
do, and the statement(s) in the loop execute again. This process repeats until the given condition
becomes false.
Flow diagram which shows the do while loop:

Consider the following example:

#include <iostream>
using namespace std;
int main ()
{
int a = 15;
do // do loop execution
{
cout << "value of a: " << a << endl;
a = a + 1;
}while( a < 20 );
return 0;
}

When the above code is compiled and executed, it produces the following result:
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
value of a: 15

3.4.3. The for loop


A for loop is a repetition control structure that allows you to efficiently write a loop that needs to
execute a specific number of times.
Syntax:
for ( initialization; condition; increment/decrement )
{
statement(s);
}
Here is the flow of control in a for loop:
 The initialization step is executed first, and only once. This step allows you to declare and
initialize any loop control variables. You are not required to put a statement here, as long as a
semicolon appears.
 Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the
body of the loop does not execute and flow of control jumps to the next statement just after the
for loop.
 After the body of the for loop executes, the flow of control jumps back up to
the increment/decrement statement. This statement allows you to update any loop control
variables. This statement can be left blank, as long as a semicolon appears after the condition.
 The condition is now evaluated again. If it is true, the loop executes and the process repeats itself
(body of loop, then increment/decrement step, and then again condition). After the
condition becomes false, the for loop terminates.
The general flow diagram for the for loop is like this:
Let’s try to consider the following example:
#include <iostream>
using namespace std;
int main ()
{
for( int a = 15; a < 20; a = a + 1 )
{
cout << "value of a: " << a << endl;
}
return 0;
}

When the above code is compiled and executed, it produces the following result:
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19

3.5. Nested loop statements


A loop can be nested inside of another loop. C++ allows at least 256 levels of nesting.
Syntax:
The syntax for a nested for loop statement in C++ is as follows:
for ( initialization; condition; increment/decrement )
{
for ( initialization; condition; increment/decrement )
{
statement(s);
}
statement(s); // you can put more statements.
}
The syntax for a nested while loop statement in C++ is as follows:
while(condition)
{
while(condition)
{
statement(s);
}
statement(s); // you can put more statements.
}
The syntax for a nested do...while loop statement in C++ is as follows:
do
{
statement(s); // you can put more statements.
do
{
statement(s);
}while( condition );

}while( condition );

3.6.Flow control statements


Loop control statements change execution from its normal sequence. When execution leaves a scope, all
automatic objects that were created in that scope are destroyed. C++ supports the following control
statements.

 The break statement


 The continue statement
 The goto statement

3.6.1. The break statement


The break statement ends execution of the nearest enclosing loop or conditional statement in which it
appears. Control passes to the statement that follows the end of the statement, if any.
Syntax:
break;

The break statement is used with the conditional switch statement and with the do, for, and while
loop statements. In a switch statement, the break statement causes the program to execute the next
statement outside the switch statement. Without a break statement, every statement from the matched
case label to the end of the switch statement, including the default clause, is executed.
In loops, the break statement ends execution of the nearest enclosing do, for, or while statement.
Control passes to the statement that follows the ended statement, if any.
Within nested statements, the break statement ends only the do, for, switch, or while statement
that immediately encloses it. You can use a return or goto statement to transfer control from more
deeply nested structures. Consider the following
Example

The following code shows how to use the break statement in a for loop.
#include <iostream>
using namespace std;
int main()
{
// an example of a standard for loop
for (int i = 1; i < 10; i++)
{
cout << i << '\n';
if (i == 4)
break;
}
return 0;
}
The output of the above program is
1
2
3
4
The following code shows how to use break in a while loop and a do loop.
#include <iostream>
using namespace std;
int main() {
int i = 0;

while (i < 10) {


if (i == 4) {
break;
}
cout << i << '\n';
i++;
}
i = 0; Output
do { 0
if (i == 4) { 1
break; 2
} 3
cout << i << '\n'; 0
i++; 1
} while (i < 10); 2
} 3
3.6.2. The continue statement
Forces transfer of control to the controlling expression of the smallest enclosing do, for, or while loop.
Syntax
continue;

Any remaining statements in the current iteration are not executed. The next iteration of the loop is
determined as follows:
 In a do or while loop, the next iteration starts by reevaluating the controlling expression of the
do or while statement.
 In a for loop (using the syntax for(initialization; condition;
increment/decrement)), the increment/decrement clause is executed. Then the
condition clause is reevaluated and, depending on the result, the loop either ends or another
iteration occurs.
Consider the following:

Example: C++ program to display integer from 1 to 10 except 6 and 9.


#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 10; ++i) {
if ( i == 6 || i == 9) {
continue;
}
cout<<i<<"\t";
}
return 0;
}
Output
1 2 3 4 5 7 8 10

In above program, when i is 6 or 9, execution of statement cout<<i<<"\t"; is skipped


inside the loop using continue; statement.

3.6.3. The goto statement


In C++ programming, goto statement is used for altering the normal sequence of program execution by
transferring control to some other part of the program. A goto statement provides an unconditional
jump from the goto to a labeled statement in the same function.
Syntax:
goto label;
... .. ...
... .. ...
... .. ...
label:
statement;
... .. ...
Where label is an identifier that identifies a labeled statement. A labeled statement is any statement
that is preceded by an identifier followed by a colon (:).
The labeled statement designated by identifier must be in the current function. Labels must be written as
a valid identifiers. A statement label is meaningful only to a goto statement; otherwise, statement
labels are ignored. Labels cannot be re declared.
Note: It is good programming style to use the break, continue, and return statements instead of
the goto statement whenever possible. However, because the break statement exits from only one
level of a loop, you might have to use a goto statement to exit a deeply nested loop.
Consider the following.
Example:
#include <iostream>
using namespace std;
int main ()
{
int a = 10;
loop:
do
{
if( a == 15)
{
// skip the iteration.
a = a + 1;
goto loop;
}
cout << "value of a: " << a << endl;
a = a + 1;
}while( a < 20 );

return 0;
}
When the above code is compiled and executed, it produces the following result:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 16
value of a: 17
value of a: 18
value of a: 19
4. CHAPTER FOUR: FUNCTIONS

4.1. What is function


A function is a group of statements that together perform a task. Every C++ program has at least one
function, which is main(), and all the most trivial programs can define additional functions. For large
programs, it is not practical (although it is possible) to put the entire programming instructions into one
function, as we will soon discover. we must learn to break the problem into manageable pieces.
Let us imagine an automobile factory. When an automobile is manufactured, it is not made from basic
raw materials; it is put together from previously manufactured parts. Some parts are made by the company
itself; others, by different companies.
Functions are like building blocks. They let us divide complicated programs into manageable pieces. They
have other advantages, too:
• While working on one function, we can focus on just that part of the program and construct it,
debug it, and perfect it.
• Different people can work on different functions simultaneously.
• If a function is needed in more than one place in a program or in different programs, you can
write it once and use it many times.
• Using functions greatly enhances the program’s readability because it reduces the complexity of
the function main

4.2.Types of Functions
Depending on whether a function is predefined or created by programmer, there are two types of
function:
 Library functions(Predefined functions):
 User defined functions:

4.2.1. Library functions:


Usually called system defined functions. These are available to anyone who writes a C++ program. This
saves the programmer’s time from writing own functions. They are completely debugged, efficient and
always produce a precise output. The important contribution of the system-defined functions is that they
provide clarity to the program because they do not have to be redefined. It reduces the source code,
which saves time of the programmer.
In C++, the concept of a function, either predefined or user-defined, is similar to that of a function in
algebra. For example, every function has a name and, depending on the values specified by the user, it
does some computation. This section discusses various predefined functions.
In algebra, a function can be considered a rule or correspondence between values, called the function’s
arguments, and the unique values of the function associated with the arguments. Thus, if f(x) = 2x +
5, then f(1) = 7, f(2) = 9, and f(3) = 11, where 1, 2, and 3 are the arguments of f, and
7, 9, and 11 are the corresponding values of the function f.

For example this are some of the predefined mathematical functions pow(x, y), sqrt(x), and
floor(x). The power function, pow(x, y), calculates xy; that is, the value of pow(x, y)= xy.
For example, pow(2, 3)= 23 = 8.0 and pow(2.5, 3)= 2.53 = 15.625. Because the value
of pow(x, y) is of type double, we say that the function pow is of type double or that the function
pow returns a value of type double. Moreover, x and y are called the parameters (or arguments) of
the function pow. Function pow has two parameters.
The square root function, sqrt(x), calculates the nonnegative square root of x for x >= 0.0. For
example, sqrt(2.25) is 1.5. The function sqrt is of type double and has only one parameter.
In C++, predefined functions are organized into separate libraries. For example, the header file
iostream contains I/O functions, and the header file cmath contains math functions.

The following table shows some of the commonly used built in functions

Example 1: library function


#include <iostream>
#include <cmath>
Output
Enter a number: 9
Square root of 9 = 3
using namespace std;
int main() {
double number, squareRoot;
cout<<"Enter a number: ";
cin>>number;
//sqrt() is a library function to calculate square root
squareRoot = sqrt(number);
cout<<"Square root of "<<number<<" = "<<squareRoot;
return 0;
}
In example above, sqrt() library function is invoked to calculate the square root of a number. Notice
code #include <cmath> in the above program. Here, cmath is a header file. The function definition
of sqrt()(body of that function) is written in that file. You can use all functions defined in cmath when
you include the content of file cmath in this program using #include <cmath>

Individual Assignment #1:- Write at least three predefined functions with example (the example
should be C++ Program). N:B Your function should be deferent from those described in this
student material.

4.2.2. User defined functions:


Because of C++ does not provide every function that you will ever need and designers cannot possibly
know a user’s specific needs, we must learn to write our own functions. In this chapter we discuss in detail
about user defined functions.

4.2.3. Declaration and defining functions


A function declaration tells the compiler about a function's name, return type, and parameters. A
function definition provides the actual body of the function.
A function is knows as with various names like a method or a sub-routine or a procedure etc.
User-defined functions in C++ are classified into two categories:
• Value-returning functions—functions that have a return type. These functions return a value of
a specific data type using the return statement, which we will explain shortly.
• Void functions—functions that do not have a return type. These functions do not use a return
statement to return a value.
The general form of a C++ function definition is as follows:
return_type function_name( parameter list )
{
body of the function
}
A C++ function definition consists of a function header and a function body. Here are all the parts of a
function:
 Return Type: A function may return a value. The return_type is the data type of the value the
function returns. Some functions perform the desired operations without returning a value. In this
case, the return_type is the keyword void.
 Function Name: This is the actual name of the function. The function name and the parameter
list together constitute the function signature.
 Parameters: A parameter is like a placeholder. When a function is invoked (called), you pass a
value to the parameter. This value is referred to as actual parameter. The parameter list refers to
the type, order, and number of the parameters of a function. Parameters are optional; that is, a
function may contain no parameters.
 Function Body: The function body contains a collection of statements that define what the
function does.

4.2.4. How user-defined function works in C++ Programming


Consider the figure below. When a program begins running, the system calls
the main() function, that is, the system starts executing codes from main() function. When
control of program reaches to function_name() inside main(), the control of program
moves to void function_name(), all codes inside void function_name() is
executed and control of program moves to code right
after function_name() inside main() as shown in figure bellow.

Example: C++ program to add two integers. Make a function add() to add integers and display sum in
main() function.
# include <iostream>
using namespace std;

int add(int, int); //Function prototype(declaration)

int main() {
int num1, num2, sum;
cout<<"Enter two numbers to add: "; Output
cin>>num1>>num2; Enter two integers: 8
sum = add(num1,num2); //Function call -4
cout<<"Sum = "<<sum;
return 0; Sum = 4
}

int add(int a,int b) { //Function declarator


int add;
add = a+b;
return add; //Return statement
}

4.2.5. Function prototype(declaration)


A function declaration tells the compiler about a function name and how to call the function. The actual
body of the function can be defined separately.
If an user-defined function is defined after main() function, compiler will show error. It is
because compiler is unaware of user-defined function, types of argument passed to function and
return type.
A function declaration has the following parts:
return_type function_name( parameter list );
In C++, function prototype is a declaration of function without function body to give compiler information
about user-defined function. Function prototype in above example:
int add(int, int);

You can see that, there is no body of function in prototype. Also there are only return type of arguments
but no arguments. You can also declare function prototype as below but it's not necessary to write
arguments.
int add(int a, int b);

Note: It is not necessary to define prototype if user-defined function exists before main() function.

4.2.6. Function calling


While creating a C++ function, you give a definition of what the function has to do. To use a function,
you will have to call or invoke that function. When a program calls a function, program control is
transferred to the called function. A called function performs defined task and when its return statement
is executed or when its function-ending closing brace is reached, it returns program control back to the
main program.
To execute the codes of function body, the user-defined function needs to be invoked (called).
In the above program, add(num1,num2); inside main() function calls the user-defined
function. In the above program, user-defined function returns an integer which is stored in
variable add.

To call a function, you simply need to pass the required parameters along with function name,
and if function returns a value, then you can store returned value. Let’s look at the following
example:

#include <iostream>
using namespace std;
// function declaration
int max(int num1, int num2);
int main ()
{
// local variable declaration:
int a = 100;
int b = 200;
int ret;
// calling a function to get max value.
ret = max(a, b);
cout << "Max value is : " << ret << endl;
return 0;
}
// function returning the max between two numbers
int max(int num1, int num2)
{
// local variable declaration
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}

4.2.7. Passing Arguments to Function


If a function is to use arguments, it must declare variables that accept the values of the arguments. These
variables are called the formal parameters of the function.

The formal parameters behave like other local variables inside the function and are created upon entry
into the function and destroyed upon exit.

In programming, argument refers to data this is passed to function (function definition) while
calling function.

In above example, two variables, num1 and num2 are passed to function during function call.
These arguments are known as actual arguments. The value of num1 and num2 are initialized
to variables a and b respectively. These arguments a and b are called formal arguments. This
is demonstrated below:

Notes on passing arguments

 The numbers of actual arguments and formals argument should be same. (Exception: Function
Overloading)
 The type of first actual argument should match the type of first formal argument. Similarly, type
of second actual argument should match the type of second formal argument and so on.
 You may call function without passing any argument. The number(s) of argument passed to a
function depends on how programmer want to solve the problem.
 In above program, both arguments are of int type. But it's not necessary to have both arguments
of same type.
Return Statement
A function can return single value to the calling program using return statement. In the above program,
the value of add is returned from user-defined function to the calling program using statement below:

return add;

The figure below demonstrates the working of return statement.

In the above program, the value of add inside user-defined function is returned to the calling
function. The value is then stored to a variable sum. Notice that, the variable returned, that
is, add is of type int and also sum is of int type. Also notice that, the return type of a function
is defined in function declarator int add(int a,int b). The int before add(int a,int
b) means that function should return a value of type int. If no value is returned to the calling
function then, void should be used.

4.2.8. Calling/invoking functions by value and by reference parameters


While calling a function, there are two ways that arguments can be passed to a function: Call by value
and call by reference.
Call by value: The call by value method of passing arguments to a function copies the actual value of
an argument into the formal parameter of the function. In this case, changes made to the parameter inside
the function have no effect on the argument.

By default, C++ uses call by value to pass arguments. In general, this means that code within a function
cannot alter the arguments used to call the function. Consider the function swap() definition as follows.

#include <iostream>
using namespace std; Output
// function declaration Before swap, value of a :100
void swap(int x, int y); Before swap, value of b :200
int main () After swap, value of a :100
{ After swap, value of b :200
// local variable declaration:
int a = 100;
int b = 200;
cout << "Before swap, value of a :" << a << endl;
cout << "Before swap, value of b :" << b << endl;
// calling a function to swap the values.
swap(a, b);
cout << "After swap, value of a :" << a << endl;
cout << "After swap, value of b :" << b << endl;
return 0;
}

// function definition to swap the values.


void swap(int x, int y)
{
int temp;
temp = x; /* save the value of x */
x = y; /* put y into x */
y = temp; /* put x into y */

Which shows that there is no change in the values though they had been changed inside the function.
Call by reference: The call by reference method of passing arguments to a function copies the reference
of an argument into the formal parameter. Inside the function, the reference is used to access the actual
argument used in the call. This means that changes made to the parameter affect the passed argument.

To pass the value by reference, argument reference is passed to the functions just like any other value.
So accordingly you need to declare the function parameters as reference types as in the following
function swap(), which exchanges the values of the two integer variables pointed to by its arguments.

#include <iostream>
using namespace std;
Output
Before swap, value of a :100
// function declaration Before swap, value of b :200
After swap, value of a :200
void swap(int &x, int &y); After swap, value of b :100
int main ()
{
// local variable declaration:
int a = 100;
int b = 200;
cout << "Before swap, value of a :" << a << endl;
cout << "Before swap, value of b :" << b << endl;
/* calling a function to swap the values using variable reference.*/
swap(a, b);
cout << "After swap, value of a :" << a << endl;
cout << "After swap, value of b :" << b << endl;
return 0;
}
// function definition to swap the values.
void swap(int &x, int &y)
{
int temp;
temp = x; /* save the value at address x */
x = y; /* put y into x */
y = temp; /* put x into y */
}

By default, C++ uses call by value to pass arguments. In general, this means that code within a function
cannot alter the arguments used to call the function and above mentioned example while calling max()
function used the same method.

4.2.9. C++ User-defined function types


For better understanding of arguments and return in functions, user-defined functions can be categorised
as:
1. Function with no argument and no return value
2. Function with no argument but return value
3. Function with argument but no return value
4. Function with argument and return value

Consider a situation in which you have to check prime number. This problem is solved below by making
user-defined function in 4 different ways as mentioned above.
1. Functions with no arguments and no return value:

# include <iostream>
using namespace std;
void prime();
int main() {
prime();// No argument is passed to prime().
return 0;
}
// Return type of function is void because value is not returned.
void prime() {
int num, i, flag = 0;
printf("Enter a positive integer enter to check: ");
cin>>num;
for(i = 2; i <= num/2; ++i){
if(num%i == 0) {
flag=1;
break;
}
}
if (flag == 1) {
cout<<num<<" is not a prime number.";
}
else {
cout<<num<<" is a prime number.";
}
}

2. Function with no arguments but return value:

#include <iostream>
using namespace std;
int prime();
int main() {
int num, i, flag = 0;
num = prime(); /* No argument is passed to prime() */
for (i = 2; i <= num/2; ++i) {
if (num%i == 0) {
flag = 1;
break;
}
}
if (flag == 1) {
cout<<num<<" is not a prime number.";
}
else {
cout<<num<<" is a prime number.";
}
return 0;
}
// Return type of function is int
int prime() {
int n;
printf("Enter a positive integer to check: ");
cin>>n;
return n;
}

3. Function with argument but no return value:

#include <iostream>
using namespace std;
void prime(int n);
int main() {
int num;
cout<<"Enter a positive integer to check: ";
cin>>num;
prime(num); // Argument num is passed to function.
return 0;
}
// There is no return value to calling function. Hence, return type of
function is void. */
void prime(int n) {
int i, flag = 0;
for (i = 2; i <= n/2; ++i) {
if (n%i == 0) {
flag = 1;
break;
}
}
if (flag == 1) {
cout<<n<<" is not a prime number.";
}
else {
cout<<n<<" is a prime number.";
}
}

4. Function with arguments and return value.

#include <iostream>
using namespace std;
int prime(int n);
int main() {
int num, flag = 0;
cout<<"Enter positive enter to check: ";
cin>>num;
flag = prime(num); /* Argument num is passed to check() function. */
if(flag == 1)
cout<<num<<" is not a prime number.";
else
cout<<num<<" is a prime number.";
return 0;
}
/* This function returns integer value. */
int prime(int n){
int i;
for(i = 2; i <= n/2; ++i){
if(n%i == 0)
return 1;
}
return 0;
}

NOTE: All four programs above gives the same output and all are technically correct program. There is
no hard and fast rule on which method should be chosen. The particular method is chosen depending
upon the situation and how a programmer want to solve that problem.

4.3. Function overloading


In C++ programming, two functions can have same identifier(name) if either number of
arguments or type of arguments passed to functions are different. These types of functions
having similar name are called overloaded functions.
Example of function overloading
int test() { }
int test(int a){ }
int test(double a){ }
int test(int a, double b){ }

All 4 functions mentioned above are overloaded function. It should be noticed that, the return
type of all 4 functions is same,i.e, int. Overloaded function may or may not have different
return type but it should have different argument(either type of argument or numbers of
argument passed). Two functions shown below are not overloaded functions because they only
have same number of arguments and arguments in both functions are of type int.
 Both functions has same number of argument and same type of argument

 Hence, functions mentioned below are not overloaded functions.

 Compiler shows error in this case.

int test(int a){ }


double test(int b){ }

Example 1: Function Overloading:


/*Calling overloaded function test() with different argument/s.*/
#include <iostream>
using namespace std;
void test(int);
void test(float);
void test(int, float);
int main() {
int a = 5;
float b = 5.5;
test(a); Output
test(b); Integer number: 5
Float number: 5.5
test(a, b); Integer number: 5 And float number: 5.5
return 0;
}
void test(int var) {
cout<<"Integer number: "<<var<<endl;
}
void test(float var){
cout<<"Float number: "<<var<<endl;
}
void test(int var1, float var2) {
cout<<"Integer number: "<<var1;
cout<<" And float number:"<<var2;
}

In above example, function test() is called with integer argument at first. Then,
function test() is called with floating point argument and finally it is called using two
arguments of type int and float. Although the return type of all these functions is same, that
is, void, it's not mandatory to have same return type for all overloaded functions. This can be
demonstrated by example below.

Example 2: Function Overloading: C++ Program to return absolute value of variable types integer and
float using function overloading
#include <iostream>
using namespace std;
int absolute(int);
float absolute(float);
int main() {
int a = -5;
float b = 5.5;
cout<<"Absolute value of "<<a<<" = "<<absolute(a)<<endl;
cout<<"Absolute value of "<<b<<" = "<<absolute(b);
return 0;
} Output
int absolute(int var) { Absolute value of -5 = 5
Absolute value of 5.5 = 5.5
if (var < 0)
var = -var;
return var;
}
float absolute(float var){
if (var < 0.0)
var = -var;
return var;
}

In above example, two functions absolute() are overloaded. Both take single argument but one
takes integer type argument and other takes floating point type argument.
Function absolute() calculates the absolute value of argument passed and returns it.

4.4. Default Argument


In C++ programming, you can provide default values for function parameters. The idea behind
default argument is very simple. If a function is called by passing argument/s, those arguments
are used by the function. But if all argument/s are not passed while invoking a function then, the
default value passed to arguments are used. Default value/s are passed to argumen t/s in function
prototype. Working of default argument is demonstrated in the figure below:
Example: Default Argument: C++ Program to demonstrate working of default argument
#include <iostream>
using namespace std;
void display(char = '*', int = 1); Output
int main() { No argument passed:
*
cout<<"No argument passed:\n"; First argument passed:
#
display(); Both argument passed:
$$$$$
cout<<"\n\nFirst argument passed:\n";
display('#');
cout<<"\n\nBoth argument passed:\n";
display('$', 5);
return 0;
}
void display(char c, int n){
for(int i = 1; i <=n; ++i) {
cout<<c;
}
cout<<endl;
}

In the above program, you can see default value passed to arguments(in function prototype). At
first, display() function is called without passing any arguments. In this
case, default() function used both default arguments. Then, the function is called using only
first argument. In this case, function does not use first default value passed. Function uses the
actual parameter passed as first argument and takes default value(second value in function
prototype) as it's second argument. When display() is invoked passing both arguments, default
arguments are not used.

Note: The missing argument must be the last argument of the list, that is, if you are passing
only one argument in the above function, it should be the first argument.
4.5. Function recursion
In many programming languages including C++, it is possible to call a function from a same function.
This function is known as recursive function and this programming technique is known as recursion.

To understand recursion, you should have knowledge of two important aspects:


 In recursion, a function calls itself but you shouldn't assume these two functions are same
function. They are different functions although they have same name.
 Local variables are variables defined inside a function and has scope only inside that function. In
recursion, a function call itself but these two functions are different functions (You can imagine
these functions are function1 and function 2. The local variables inside function1 and function2
are also different and can only be accessed within that function.
The C++ programming language supports recursion, i.e., a function to call itself. But while using
recursion, programmers need to be careful to define an exit condition from the function, otherwise it will
go into an infinite loop.
Example 1: Consider this example to find factorial of a number using recursion.
#include <iostream>
using namespace std;
int factorial(int);
int main() {
int n;
cout<<"Enter a number to find factorial: ";
cin>>n;
cout<<"Factorial of "<<n<<" = "<<factorial(n);
return 0;
}
int factorial(int n) { Output
if (n>1) { Enter a number to find factorial: 4
Factorial of 4 = 24
return n*factorial(n-1);
}
else {
return 1;
}
}

Explanation: How recursion works

Suppose user enters 4 which is passed to function factorial(). Here are the steps involved:

 In first factorial() function, test expression inside if statement is true. The


statement return num*factorial(num-1); is executed, which calls
second factorial() function and argument passed is num-1 which is 3.
 In second factorial() function, test expression inside if statement is true. The
statement return num*factorial(num-1); is executed, which calls
third factorial() function and argument passed is num-1 which is 2.
 In third factorial() function, test expression inside if statement is true. The
statement return num*factorial(num-1); is executed, which calls
fourth factorial() function and argument passed is num-1 which is 1.
 The fourth factorial() function, test expression inside if statement is false. The
statement return 1; is executed, which returns 1 to third factorial() function.
 The third factorial() function returns 2 to second factorial() function.
 The second factorial() function returns 6 to first factorial() function.
 Finally, first factorial() function returns 24 to the main() function and is
displayed.
Example 2: The following example generates the Fibonacci series for a given number using a recursive
function:
#include <iostream>
using namespace std;
int fibonacci(int i) {
Output
if(i == 0) {
0 1 1 2 3 5 8 13 21 34
return 0;
}
if(i == 1) {
return 1;
}
return fibonacci(i-1) + fibonacci(i-2);
}
int main() {
for (int i = 0; i < 10; i++) {
cout<<"\n"<<fibonacci(i);
}
return 0;
}
5. CHAPTER FIVE: ARRAY POINTERS & STRINGS

In previous chapters, you worked with simple data types. In Chapter 2, you learned that C++ data types
fall into three categories. One of these categories is the structured data type. Recall that a data type is
called simple if variables of that type can store only one value at a time. In contrast, in a structured data
type, each data item is a collection of other data items. Simple data types are building blocks of structured
data types. The first structured data type that we will discuss is an array and structure.

Before formally defining an array, let us consider the following problem. We want to write a C++ program
that reads five numbers, finds their sum, and prints the numbers in reverse order.
In Chapter 4, you learned how to read numbers, print them, and find the sum. The difference here is that
we want to print the numbers in reverse order. This means we cannot print the first four numbers until we
have printed the fifth, and so on. To do this, we need to store all of the numbers before we start printing
them in reverse order. From what we have learned so far, the following program accomplishes this task.
#include <iostream>
using namespace std;
int main()
{
int item0, item1, item2, item3, item4, sum;
cout << "Enter five integers: ";
cin >> item0 >> item1 >> item2 >> item3 >> item4;
sum = item0 + item1 + item2 + item3 + item4;
cout << "The sum of the numbers = " << sum << endl;
cout << "The numbers in the reverse order are: ";
cout <<item4<<" "<<item3<<" "<<item2<<" "<<item1<<"
"<<item0<<endl;
return 0;
}

This program works fine. However, if you need to read 100 (or more) numbers and print them in reverse
order, you would have to declare 100 variables and write many cin and cout statements. Thus, for
large amounts of data, this type of program is not desirable.

5.1. Arrays
An array is a collection of a fixed number of components all of the same data type. C++ provides a data
structure, the array, which stores a fixed-size sequential collection of elements of the same type. An array
is used to store a collection of data, but it is often more useful to think of an array as a collection of
variables of the same type.
Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare
one array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to
represent individual variables. A specific element in an array is accessed by an index.
All arrays consist of contiguous memory locations. The lowest address corresponds to the first element
and the highest address to the last element.

5.1.1. Array declaration


The general form for declaring a one-dimensional array is:

datatype arayname[intexpr];

In which intExp is any constant expression that evaluates to a positive integer. Also,
intExp specifies the number of components in the array.
Example:

int num[5];

The above statement declares an array num of five components. Each component is of type int. The
components are num[0], num[1], num[2], num[3], and num[4]. The following figure
illustrates the array num.

5.1.2. Array initialization

we can initialize C++ array elements either one by one or using a single statement as follows:

double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};

The number of values between braces { } cannot be larger than the number of elements that we declare
for the array between square brackets [ ]. Following is an example to assign a single element of the array:
If you omit the size of the array, an array just big enough to hold the initialization is created. Therefore,
if you write:

double balance[] = {1000.0, 2.0, 3.4, 17.0, 50.0};

You will create exactly the same array as you did in the previous example.

balance[4] = 50.0;

The above statement assigns element number 5th in the array a value of 50.0. Array with 4th index will be
5th, i.e., last element because all arrays have 0 as the index of their first element which is also called base
index. Following is the pictorial representation of the same array we discussed above:

5.1.3. Accessing array elements


An element is accessed by indexing the array name. This is done by placing the index of the element
within square brackets after the name of the array. For example:

double salary = balance[9];

The above statement will take 10th element from the array and assign the value to salary variable.

5.1.4. Multidimensional array


In the above sections you learned about one dimensional array, that is, single variables specify array.
C++ allows programmer to create array of an array known as multidimensional arrays. Here is the general
form of a multidimensional array declaration:

type name[size1][size2]...[sizeN];

For example, the following declaration creates a three dimensional 5 . 10 . 4 integer array:

int threedim[5][10][4];
5.1.4.1. Two-Dimensional Arrays:
The simplest form of the multidimensional array is the two-dimensional array. A two-dimensional array
is, in essence, a list of one-dimensional arrays. To declare a two-dimensional integer array of size x,y,
you would write something as follows:

type arrayName [ x ][ y ];

Where type can be any valid C++ data type and arrayName will be a valid C++ identifier. A two-
dimensional array can be think as a table, which will have x number of rows and y number of columns.
A 2-dimensional array a, which contains three rows and four columns can be shown as below:

Thus, every element in array a is identified by an element name of the form a[i][j], where a is the
name of the array, and i and j are the subscripts that uniquely identify each element in a.

Initializing Two-Dimensional Arrays:

Multidimensional arrays may be initialized by specifying bracketed values for each row. Following is an
array with 3 rows and each row have 4 columns.

int a[3][4] = {
{0, 1, 2, 3} , /* initializers for row indexed by 0 */
{4, 5, 6, 7} , /* initializers for row indexed by 1 */
{8, 9, 10, 11} /* initializers for row indexed by 2 */
};

The nested braces, which indicate the intended row, are optional. The following initialization is
equivalent to previous example:

int a[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11};

5.1.5. Accessing Two-Dimensional Array Elements:


An element in 2-dimensional array is accessed by using the subscripts, i.e., row index and column index
of the array. For example:
int val = a[2][3];

The above statement will take 4th element from the 3rd row of the array. You can verify it in the above
diagram.

#include <iostream>
using namespace std;
int main ()
{
// an array with 5 rows and 2 columns.
int a[5][2] = { {0,0}, {1,2}, {2,4}, {3,6},{4,8}};
// output each array element's value
for ( int i = 0; i < 5; i++ )
for ( int j = 0; j < 2; j++ )
{
cout << "a[" << i << "][" << j << "]: ";
cout << a[i][j]<< endl;
}
return 0;
}
When the above code is compiled and executed, it produces the following result:

a[0][0]: 0
a[0][1]: 0
a[1][0]: 1
a[1][1]: 2
a[2][0]: 2
a[2][1]: 4
a[3][0]: 3
a[3][1]: 6
a[4][0]: 4
a[4][1]: 8
As explained above, you can have arrays with any number of dimensions, although it is likely that most
of the arrays you create will be of one or two dimensions.
5.2. String manipulation using arrays
There are two types of strings commonly use in C++ programming language:
 Strings that are objects of string class (The Standard C++ Library string class)
 C-strings (C-style Strings) usually called character Arrays.

In this chapter we only discus about the second string type which is the C-string. In C programming,
only one type of string is available and this is also supported in C++ programming. Hence it's called C-
strings. C-strings are the arrays of type char terminated with null character, that is, ‘\0’ (ASCII value
of null character is 0).
The statement:
ch = '\0';
Stores the null character in ch, wherein ch is a char variable.
The null character plays an important role in processing character arrays. Because the collating sequence
of the null character is 0, the null character is less than any other character in the char data set.
The most commonly used term for character arrays is C-strings. However, there is a subtle difference
between character arrays and C-strings. Recall that a string is a sequence of zero or more characters, and
strings are enclosed in double quotation marks. In C++, C-strings are null terminated; that is, the last
character in a C-string is always the null character. A character array might not contain the null character,
but the last character in a C-string is always the null character. As you will see, the null character should
not appear anywhere in the C-string except the last position. In addition, C-strings are stored in (one-
dimensional) character arrays.

The following are examples of C-strings:


"John L. Johnson"
"Hello there."
From the definition of C-strings, it is clear that there is a difference between 'A' and "A". The first one is
character A; the second is C-string A. Because C-strings are null terminated, "A" represents two
characters: 'A' and '\0'. Similarly, the C-string "Hello" represents six characters: 'H', 'e', 'l', 'l', 'o', and '\0'.
To store 'A', we need only one memory cell of type char; to store "A", we need two memory cells of
type char—one for 'A' and one for '\0'. Similarly, to store the C-string "Hello" in computer memory, we
need six memory cells of type char.

Consider the following example


char str[] = "C++";
In the above code, str is a string and it holds 4 character. Although, "C++" has 3 character, the
null character \0 is added to the end of the string automatically.
Other ways of defining the string:
char str[4] = "C++";
char str[] = {'C','+','+','\0'};
char str[4] = {'C','+','+','\0'};

Like arrays, it is not necessary to use all the space allocated for the string. For example:
char str[100] = "C++";
The following declaration and initialization create a string consisting of the word "Hello". To hold the
null character at the end of the array, the size of the character array containing the string is one more
than the number of characters in the word "Hello."

char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};

If you follow the rule of array initialization, then you can write the above statement as follows:
char greeting[] = "Hello";
Following is the memory presentation of above defined string in C++:

Actually, you do not place the null character at the end of a string constant. The C++ compiler
automatically places the '\0' at the end of the string when it initializes the array. Let us try to print above-
mentioned string:
#include <iostream>
Output
using namespace std;
Greeting message: Hello
int main ()
{
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
cout << "Greeting message: ";
cout << greeting << endl;
return 0;
}

C++ supports a wide range of functions that manipulate null-terminated strings: C++ provides a set of
functions that can be used for C-string manipulation. The header file cstring describes these functions.
To use these functions, the program must include the header file cstring via the include statement.
That is, the following statement must be included in the program:
#include <cstring>

5.2.1. String Comparison


In C++, C-strings are compared character by character using the system’s collating sequence. Let us
assume that you use the ASCII character set.
1. The C-string "Air" is less than the C-string "Boat" because the first character of "Air" is
less than the first character of "Boat".
2. The C-string "Air" is less than the C-string "An" because the first characters of both strings
are the same, but the second character 'i' of "Air" is less than the second character 'n' of
"An".
3. The C-string "Bill" is less than the C-string "Billy" because the first four characters of
"Bill" and "Billy" are the same, but the fifth character of "Bill", which is '\0' (the null
character), is less than the fifth character of "Billy", which is 'y'. (Recall that C-strings in
C++ are null terminated.)
4. The C-string "Hello" is less than "hello" because the first character 'H' of the C-string
"Hello" is less than the first character 'h' of the C-string "hello".
Example: C++ program to display a string entered by user.
#include <iostream>
using namespace std;
int main() {
char str[100]; Output
cout<<"Enter a string: "; Enter a string: C++
cin>>str; You entered: C++
cout<<"You entered: "<<str<<endl; Enter another string: Programming is fun.
cout<<"\nEnter another string: "; You entered: Programming
cin>>str;
cout<<"You entered: "<<str<<endl;
return 0;
}

Notice that, in second example only "programming" is displayed instead of "Programming is fun". It is
because The extraction operator >> considers a space has a terminating character.

Consider the following example: which read and display an entire line entered by user.
#include <iostream>
using namespace std;
int main() {
Output
char str[100]; Enter a string: Programming is fun.
cout<<"Enter a string: "; You entered: Programming is fun.
cin.get(str, 100);
cout<<"You entered: "<<str<<endl;
return 0;
}

To read the text containing blank space, cin.get function can be used. This function takes two
arguments. First argument is the name of the string (address of first element of string) and second argument
is the maximum size of the array.

5.3. Passing Array to a Function in C++ Programming


Arrays can be passed to a function as an argument. Consider this example to pass one-dimensional array
to a function:
Example: C++ Program to display marks of 5 students by passing one-dimensional array to a function.

#include <iostream>
using namespace std;
void display(int marks[5]); Output
int main() { Displaying marks:
int marks[5] = {88, 76, 90, 61, 69};
Student 1: 88
display(marks);
Student 2: 76
return 0;
} Student 3: 90
void display(int m[5]) { Student 4: 61
cout<<"Displaying marks: "<<endl; Student 5: 69
for (int i = 0; i <5; ++i) {
cout<<"Student "<<i+1<<": "<<m[i]<<endl;
}
}

When an array is passed as an argument to a function, only the name of an array is used as argument.
The argument used marks in the above code represents the memory address of first element of array
marks[5]. And the formal argument int m[5] in function declaration decays to int* m;. That's
why, although the function is manipulated in the user-defined function with different array name m[5],
the original array is manipulated. The C++ programming language handles passing array to a function in
this way to save memory and time.
Passing Multidimensional Array to a Function: Multidimensional array can be passed in similar way as
one-dimensional array. Consider this example to pass two dimensional array to a function:
Example: C++ Program to display the elements of two dimensional array by passing it to a function.

#include <iostream>
using namespace std;
void display(int n[3][2]);
int main() {
int num[3][2] = {
{3, 4},
{9, 5}, Output
{7, 1}
}; Displaying Values:
display(num); 3 4 9 5 7 1
return 0;
}
void display(int n[3][2]) {
cout<<"Displaying Values: "<<endl;
for(int i = 0; i < 3; ++ i) {
for(int j = 0; j < 2; ++j) {
cout<<n[i][j]<<" ";
}
}
}
Multidimensional array with dimension more than 2 can be passed in similar way as two dimensional
array.
5.4. POINTERS
In the later chapters, you learned that C++’s data types are classified into three categories: simple,
structured, and pointers. Until now, you have studied only the first two data types. This chapter discusses
the third data type called the pointer data type. You will first learn how to declare pointer variables (or
pointers, for short) and manipulate the data to which they point.

5.4.1. Basic concept of pointers


In earlier chapters, variables have been explained as locations in the computer's memory which can be
accessed by their identifier (their name). This way, the program does not need to care about the physical
address of the data in memory; it simply uses the identifier whenever it needs to refer to the variable.

For a C++ program, the memory of a computer is like a succession of memory cells, each one byte in
size, and each with a unique address. These single-byte memory cells are ordered in a way that allows
data representations larger than one byte to occupy memory cells that have consecutive addresses.
When a variable is declared, the memory needed to store its value is assigned a specific location in memory
(its memory address). Generally, C++ programs do not actively decide the exact memory addresses where
its variables are stored. Fortunately, that task is left to the environment where the program is run -
generally, an operating system that decides the particular memory locations on runtime. However, it may
be useful for a program to be able to obtain the address of a variable during runtime in order to access data
cells that are at a certain position relative to it.
When you declare a variable, the computer associates the variable name with a particular
location in memory and stores a value there.

5.4.2. Pointer variables and declaration


Pointers are the powerful feature of C++ programming, which differs it from other popular programming
languages like Java, Visual Basic etc. To understand pointers, you should have the knowledge of address
in computer memory. Computer memory is broken down into bytes and each byte has its own address.
For example: In 1KB memory, there are 1024 bytes and each byte is given an address (0 - 1023).
As you know every variable is a memory location and every memory location has its address defined
which can be accessed using ampersand (&) operator which denotes an address in memory. Consider the
following, which will print the address of the variables defined:
#include <iostream>
using namespace std;
int main () Output
{ Address of var1 variable: 0xbfebd5c0
int var1; Address of var2 variable: 0xbfebd5b6
char var2[10];
cout << "Address of var1 variable: ";
cout << &var1 << endl;
cout << "Address of var2 variable: ";
cout << &var2 << endl;
return 0;
}
The 0x in the beginning represents the address is in hexadecimal form. (You may not get the same result
on your system.).
What is pointer? Now you know about address in computer memory, it is time to learn about pointers.
Consider a normal variable as in above example, these variables holds data. But pointer variables or simply
pointers are the special types of variable that holds memory address instead of data.
A pointer is a variable whose value is the address of another variable. Like any variable or constant, you
must declare a pointer before you can work with it. The general syntax of a pointer variable declaration
is:
type *var-name;
Here, type is the pointer's base type; it must be a valid C++ type and var-name is the name of the
pointer variable. The asterisk you used to declare a pointer is the same asterisk that you use for
multiplication. However, in this statement the asterisk is being used to designate a variable as a pointer.
Following are the valid pointer declaration:
int *p;
OR,
int* p;
The statement above defines a pointer variable p. The pointer p holds the memory address. The asterisk
is a dereference operator which means pointer to. Here pointer p is a pointer to int, that is, it is
pointing an integer.

Note: In above statement p is a pointer variable that holds address not *p. The *p is an expression. The
content (value) of the memory address pointer p holds is given by expression *p.
Example: C++ Program to demonstrate the working of pointer.
#include <iostream>
using namespace std;
int main() {
int *pc, c;
c = 5;
cout<< "Address of c (&c): " << &c << endl;
cout<< "Value of c (c): " << c << endl << endl;
pc = &c; // Pointer pc holds the memory address of variable c
cout<< "Address that pointer pc holds (pc): "<< pc << endl;
cout<< "Content of the address pointer pc (*pc):" << *pc << endl;
c = 11; // The content memory address &c is changed from 5 to 11.
cout << "Address pointer pc holds (pc): " << pc << endl;
cout << "Content of the address pointer pc (*pc):" << *pc<< endl;
*pc = 2;
cout<< "Address of c (&c): "<< &c <<endl;
cout<<"Value of c (c): "<< c<<endl<< endl;
return 0;
}
The output of the above program is

Address of c (&c): 0x7fff5fbff80c


Value of c (c): 5
Address that pointer pc holds (pc): 0x7fff5fbff80c
Content of the address pointer pc holds (*pc): 5
Address pointer pc holds (pc): 0x7fff5fbff80c
Content of the address pointer pc holds (*pc): 11
Address of c (&c): 0x7fff5fbff80c
Value of c (c): 2

Explanation of program
 When c = 5; the value 5 is stored in the address of variable c.
 When pc = &c; the pointer pc holds the address of c and the expression *pc contains
the value of that address which is 5 in this case.
 When c = 11; the address that pointer pc holds is unchanged. But the
expression *pc is changed because now the address &c (which is same as pc) contains
11.
 When *pc = 2; the content in the address pc(which is equal to &c) is changed from 11
to 2. Since the pointer pc and variable c has address, value of c is changed to 2.

5.4.3. Pointer expression, operation and arithmetic


As you understood pointer is an address which is a numeric value; therefore, you can perform arithmetic
operations on a pointer just as you can a numeric value. There are four arithmetic operators that can be
used on pointers: ++, --, +, and -
To understand pointer arithmetic, let us consider that ptr is an integer pointer which points to the address
1000. Assuming 32-bit integers, let us perform the following arithmetic operation on the pointer:

ptr++

The ptr will point to the location 1004 because each time ptr is incremented, it will point to the next
integer. This operation will move the pointer to next memory location without impacting actual value at
the memory location. If ptr points to a character whose address is 1000, then above operation will point
to the location 1001 because next character will be available at 1001.
Pointers may be compared by using relational operators, such as ==, <, and >. If p1 and p2 point to
variables that are related to each other, such as elements of the same array, then p1 and p2 can be
meaningfully compared.

5.5. Relationship between pointers and arrays


Before we understand the concept of array of pointers, let us consider the following example, which
makes use of an array of 3 integers:
#include <iostream>
using namespace std;
Output
Value of var[0] = 10
Value of var[1] = 100
Value of var[2] = 200
int main ()
{
int var[3] = {10, 100, 200};
for (int i = 0; i < 3; i++)
{
cout << "Value of var[" << i << "] = ";
cout << var[i] << endl;
}
return 0;
}

Pointers are the variables that hold address. Pointers can point at cells of an array not only single
variable. Consider this example:
Int *ptr;
int a[5];
ptr = &a[2]; // &a[2] is the address of third element of a[5].
Suppose, pointer needs to point to the fourth element of an array, that is, hold address of fourth array
element in above case. Since ptr points to the third element in the above example, ptr + 1 points to
the fourth element. You may think that, ptr + 1 may hold the address of byte next to ptr. But it's not
correct. It is because pointer ptr is a pointer to int and size of int is fixed for a operating system (size
of int is 4 byte of 64-bit operating system). Hence, the address between ptr and ptr + 1 differs by
4 bytes. If pointer ptr was pointer to char then, the address between ptr and ptr + 1 would have
differed by 1 byte since size of a character is 1 byte.
Example: C++ Program to display address of elements of an array using both array and pointers
#include <iostream>
using namespace std;
int main() {
float a[3];
float *ptr;
cout << "Displaying address using arrays: "<<endl;
for (int i = 0; i < 3; ++i) {
cout << "&a[" << i << "] = " << &a[i] <<endl;
}
ptr = a; // ptr = &a[0]
cout<<"\nDisplaying address using pointers: "<< endl;
for (int i = 0; i < 3; ++i) {
cout << "ptr + " << i << " = "<<ptr+i <<endl;
}
return 0;
}
Output
Displaying address using arrays:
&a[0] = 0x7fff5fbff880
&a[1] = 0x7fff5fbff884
&a[2] = 0x7fff5fbff888

Displaying address using pointers:


ptr + 0 = 0x7fff5fbff880
ptr + 1 = 0x7fff5fbff884
ptr + 2 = 0x7fff5fbff888
In the above program, different pointer is used for displaying the address of array elements. But, array
elements can be accessed using pointer notation (by using same array name). For example:
int p[3];
&p[0] is equivalent to p
&p[1] is equivalent to p+1
&p[2] is equivalent to p+2
Example: C++ Program to display address of array elements using pointer notation.
#include <iostream>
using namespace std;
int main() {
float a[3];
cout<<"Displaying address using pointers notation: "<< endl;
for (int i = 0; i < 3; ++i) {
Displaying address using pointers notation:
cout << a+i <<endl;
0x7fff5fbff8a0
} 0x7fff5fbff8a4
return 0; 0x7fff5fbff8a8
}
You know that, pointer ptr holds the address and expression *ptr gives the content in that address.
Similarly, *(ptr + 1) gives the content in address ptr + 1. Consider this code below:
int p[5] = {3, 4, 5, 5, 3};
 &p[0] is equal to p and *p is equal to p[0]
 &p[1] is equal to p+1 and *(p+1) is equal to p[1]
 &p[2] is equal to p+2 and *(p+2) is equal to p[2]
 &p[i] is equal to p+i and *(p+i) is equal to p[i]

Example: C++ Program to insert and display data entered by using pointer notation.
#include <iostream>
using namespace std; Output
int main() { Enter 3 numbers: 2.5
float a[3]; 3.5
// Inserting data using pointer notation 4.5
cout << "Enter 3 numbers: "; Displaying data:
for (int i = 0; i < 3; ++i) { 2.5
cin >> *(a+i) ; 3.5
}
4.5
// Displaying data using pointer notation
cout << "Displaying data: " << endl;
for (int i = 0; i < 3; ++i) {
cout << *(a+i) << endl ;
}
return 0;
}

5.6. Revisiting function calling by reference (using pointers)


In function chapter, you learned about passing arguments to a function. This is pass by value
because actual value is passed. There is another way of passing argument in which actual value
is not passed; only the reference to that value is passed. Consider this example .
#include <iostream>
using namespace std;
int main() {
void swap(int&, int&); // Function prototype
int a = 1, b = 2;
cout << "Before swapping" << endl;
cout << "a = " << a << endl;
cout << "b = " << b << endl; Output
swap(a, b); Before swapping
cout << "\nAfter swapping" << endl; a=1
cout << "a = " << a << endl; b=2
cout << "b = " << b << endl; After swapping
return 0; a=2
} b=1
void swap(int& n1, int& n2) {
int temp;
temp = n1;
n1 = n2;
n2 = temp;
}
In main(), two integer variables are defined. And those integers are passed to a function
swap() by reference. Compiler can identify this is pass by reference because function definition
is void swap(int& n1, int& n2) (notice the & sign after data type). Here, n1 and n2 are
the different names given to the argument passed, that is n1 and a is exact same variable (not
only their value is same but both name refer to one single variable). Similarly, n2 and b is exact
same variable.
There is another way of doing this same exact task using pointers. Consider this example:
#include <iostream>
using namespace std;
int main() {
void swap(int*, int*); // Function prototype
int a = 1, b = 2;
cout << "Before swaping" << endl;
cout << "a = " << a << endl;
cout << "b = " << b << endl;
swap(&a, &b);
cout << "\nAfter swaping" << endl;
cout << "a = " << a << endl;
cout << "b = " << b << endl;
return 0;
}
void swap(int* n1, int* n2) {
int temp;
temp = *n1;
*n1 = *n2;
*n2 = temp;
}
The output of this example is same as before. In this case, the address of variable is passed during
function call rather than variable itself.

swap(&a, &b); // &a is address of a and &b is address of b

Since the address is passed instead of value, dereference operator must be used to access the
value stored in that address.
void swap(int* n1, int* n2) {
... .. ...
}
The *n1 and *n2 gives the value stored at address n1 and n2 respectively.
Since n1 contains the address of a, anything done to *n1 changes the value of a in main()
function as well. Similarly, b will have same value as *n2.
6. CHAPTER SIX: STRUCTURE
C++ arrays allow you to define variables that combine several data items of the same kind
but structure is another user defined data type which allows you to combine data items of different kinds.
Structures are used to represent a record; suppose you want to keep track of your books in a library. You
might want to track the following attributes about each book:

 Title
 Author
 Subject
 Book ID

6.1. Structure definitin


Suppose that you want to write a program to process student data. A student record consists of, among
other things, the student’s name, student ID, GPA, courses taken, and course grades. Thus, various
components are associated with a student. However, these components are all of different types. For
example, the student’s name is a string, and the GPA is a floating-point number. Because these
components are of different types, you cannot use an array to group all of the items associated with a
student. C++ provides a structured data type called struct to group items of different types. Grouping
components that are related but of different types offers several advantages. For example, a single variable
can pass all the components as parameters to a function.
struct: A collection of a fixed number of components in which the components are accessed by name.
The components may be of different types.
The components of a struct are called the members of the struct. The general syntax of a struct
in C++ is:
struct structName
{
dataType1 identifier1;
dataType2 identifier2;
.
.
.
dataTypen identifiern;
};
In C++, struct is a reserved word. The members of a struct, even though they are enclosed in
braces (that is, they form a block), are not considered to form a compound statement. Thus, a semicolon
(after the right brace) is essential to end the struct statement. A semicolon at the end of the struct
definition is, therefore, a part of the syntax.
The statement:
struct employeeType
{
string firstName;
string lastName;
string address1;
string address2;
double salary;
string deptID;
};

defines a struct employeeType with six members. The members firstName, lastName,
address1, address2, and deptID are of type string, and the member salary is of type double. Like
any type definition, a struct is a definition, not a declaration. That is, it defines only a data type; no
memory is allocated.

6.1.1. Structure declaration


Once a data type is defined, you can declare variables of that type. Let us first define a struct type,
studentType, and then declare variables of that type.
struct studentType
{
string firstName;
string lastName;
char courseGrade;
int testScore;
int programmingScore;
double GPA;
};

Let’s declare the following variables with the type studentType


studentType newStudent;
studentType student;
These statements declare two struct variables, newStudent and student, of type studentType.
The memory allocated is large enough to store firstName, lastName, courseGrade,
testScore, programmingScore, and GPA

You can also declare struct variables when you define the struct. For example, consider the
following statements:
struct studentType
{
string firstName;
string lastName;
char courseGrade;
int testScore;
int programmingScore;
double GPA;
} tempStudent;

These statements define the struct studentType and also declare tempStudent to be a variable
of type studentType. Typically, in a program, a struct is defined before the definitions of all of the
functions in the program so that the struct can be used throughout the program. Therefore, if you define
a struct and also simultaneously declare a struct variable (as in the preceding statements), then that
struct variable becomes a global variable and thus can be accessed anywhere in the program. Keeping
in mind the side effects of global variables, you first should only define a struct and then declare the
struct variables.

6.1.2. Accessing members of struct.


In arrays, you access a component by using the array name together with the relative position (index) of
the component. The array name and index are separated using square brackets. To access a structure
member (component), you use the struct variable name together with the member name; these names
are separated by a dot (period). The syntax for accessing a struct member is:
structVariableName.memberName;
The structVariableName.memberName is just like any other variable. For example,
newStudent.courseGrade is a variable of type char, newStudent.firstName is a string
variable, and so on. As a result, you can do just about anything with struct members that you normally
do with variables. You can, for example, use them in assignment statements or input/output (where
permitted) statements.
In C++, the dot (.) is an operator called the member access operator.

6.1.3. Initialization of structure


Suppose you want to initialize the member GPA of newStudent to 0.0. The following statement
accomplishes this task:
newStudent.GPA = 0.0;
Similarly, the statements:
newStudent.firstName = "John";
newStudent.lastName = "Brown";
store "John" in the member firstName and "Brown" in the member lastName of
newStudent.
The statement:
cin >> newStudent.firstName;
reads the next string from the standard input device and stores it in: newStudent.firstName
The statement:
cin >> newStudent.testScore >> newStudent.programmingScore;
reads two integer values from the keyboard and stores them in newStudent.testScore and
newStudent.programmingScore, respectively.
Suppose that score is a variable of type int. The statement:
score = (newStudent.testScore + newStudent.programmingScore) / 2;
assigns the average of newStudent.testScore and newStudent.programmingScore
to score.
The following statement determines the course grade and stores it in newStudent.courseGrade:
if (score >= 90)
newStudent.courseGrade = 'A';
else if (score >= 80)
newStudent.courseGrade = 'B';
else if (score >= 70)
newStudent.courseGrade = 'C';
else if (score >= 60)
newStudent.courseGrade = 'D';
Else
newStudent.courseGrade = 'F';

We can assign the value of one struct variable to another struct variable of the same type
by using an assignment statement.
The statement:
student = newStudent; copies the contents of newStudent into student.
In fact, the assignment statement:
student = newStudent;
is equivalent to the following statements:
student.firstName = newStudent.firstName;
student.lastName = newStudent.lastName;
student.courseGrade = newStudent.courseGrade;
student.testScore = newStudent.testScore;
student.programmingScore = newStudent.programmingScore;
student.GPA = newStudent.GPA;
7. CHAPTER SEVEN: FILE OPERATIONS (FILE INPUT/OUTPUT)
7.1. Introduction
The data created by the user and assigned to variables with an assignment statement is sufficient for some
applications. With large volume of data most real-world applications use a better way of storing that data.
For this, disk files offer the solution.
When working with disk files, C++ does not have to access much RAM because C++ reads data from
your disk drive and processes the data only parts at a time.

So far, we have been using the iostream standard library, which provides cin and cout objects for
reading from standard input and writing to standard output respectively.

7.2. Stream classes


Stream is a general name given to flow of data. In C++, there are different types of streams. Each stream
is associated with a particular class, which contains member function and definition for dealing with file.
In Standard C++, you can do input output (I/O) to and from disk files very much like istream the
ordinary console I/O streams cin and cout. The object cin is a global object in the class (input stream),
and the global object cout is a member of the class ostream (output stream). File streams come in two
flavors also: the class ifstream (input file stream) inherits from istream, and the class ofstream
(output file stream) inherits from ostream. Thus, all of the member functions and operators that you can
apply to an istream or ostream object can also be applied to ifstream and ofstream objects.
However, file streams have some additional member functions and internal information reflecting how
they are connected to files on the disk.

Generally, two main header files are used iostream and fstream. The classes used for input and
output to the video display (screen) and keyboard are declared in the header file iostream and the
classes used for disk file input output are declared in fstream.

First, we will see how files are opened and closed. A file can be defined by following class ifstream,
ofstream, fstream, all these are defined in fstream header file.
• If a file object is declared by ifstream class, then that object can be used for reading from a
file.
• If a file object is declared by ofstream class, then that object can be used for writing onto a file.
• If a file object is declared by fstream class then, that object can be used for both reading from
and writing to a file

7.3. Opening and closing files


A file must be opened before you can read from it or write to it. Either the ofstream or fstream
object may be used to open a file for writing and ifstream object is used to open a file for reading
purpose only.
When you open a disk file, you only have to inform the file name and what you want to do with it. C++
and your operating system work together to make sure that the disk is ready, and they create an entry in
your file directory for the filename (if you are creating a file). When you close a file, C++ writes any
remaining data to the file, releases the file from the program, and updates the file directory to reflect the
file’s new size.
You can use either of the two methods to open a file in C++:
• using a Constructor or
• using the open function

The following C++ statement will create an object with the name fout of ofstream class and this
object will be associated with file name “hello.txt”.

ofstream fout (“hello.txt”);


This statement uses the constructor method.
The following C++ statement will create an object with the name fout of ofstream class and this
object will be associated with file name “hello.txt”.
ofstream fout;
fout.open(“hello.txt”);
If you open a file for writing (out access mode), C++ creates the file. If a file by that name already
exists, C++ overwrite the old file with no warning. You must be careful when opening files not to
overwrite existing data that you want.
If an error occurs during opening of a file, C++ does not create a valid file pointer (file object). Instead,
C++ creates a file pointer (object) equal to zero. For example if you open a file for output, but use an
invalid disk name, C++ can’t open the file and therefore makes the file object equal to zero.
You can also determine the file access mode when creating a file in C++. If you want to use the open
function to open a file then the syntax is:
fileobject.open(filename, accessmode);
Here, the first argument specifies the name and location of the file to be opened and the second
argument of the open() member function defines the mode in which the file should be opened (what
you want to do with the file). Access mode is the sought operation to be taken on the file and must be
one of the values in the following table.
ios::app Append mode. All output to that file to be appended to the
end.
ios::ate Open a file for output and move the read/write control to the
end of the file.
ios::in Open a file for reading.
ios::out Open a file for writing.
ios::trunc If the file already exists, its contents will be truncated before
opening the file.
You can combine two or more of these values by ORing them together. For example if you want to open
a file in write mode and want to truncate it in case it already exists, following will be the syntax:
ofstream outfile;
outfile.open("hello.txt", ios::out | ios::trunc );
Similar way, you can open a file for reading and writing purpose as follows:
fstream afile;
afile.open("hello.txt", ios::out | ios::in );
You should always check for the successful opening of a file before starting file manipulation on it. You
can use is_open() function to do the task:
Example:
ifstream indata;
indata.open(“hello.txt”,ios::in);
if(indata.is_open())
{
//error description here
cout<<”Can’t open the file”;
}
In this case, the open operation will is_open (i.e the is_open function will return true), if there is
no file named hello.txt in the folder the program displays error message.
After you are done with your file manipulations, you should use the close function to release any
resources that were consumed by the file operation. Here is an example
indata.close();
The above close() statement will terminate the relationship between the ifstream object indata
and the file name “hello.txt”, hence releasing any resource needed by the system.

7.4. Writing to and reading from files


7.4.1. Writing to a file
While doing C++ programming, you write information to a file from your program using the stream
insertion operator (<<) just as you use that operator to output information to the screen. The only
difference is that you use an ofstream or fstream object instead of the cout object.
Example:- The following program creates a file called names.txt in C:\ and saves the name of five
persons in it:

#include<fstream>
using namespace std;
int main(){
ofstream fp;
fp.open(“c:\\names.txt” ,ios::out);
if(fp.fail())//fail checks successful opening of file
{
Perror(“\nError opening file”);
}
fp<< “Abebe Alemu”<<endl;
fp<< “Lemelem Berhanu”<<endl;
fp<< “Tesfaye Mulugeta”<<endl;
fp<< “Mahlet Kebede”<<endl;
fp<< “Assefa Bogale”<<endl;
fp.close();
}//end main
You can also write characters to a file. A character can be written onto a file using the put() function.
See the following code:

#include<fstream>
#include<iostream>
using namespace std;
int main()
{
char c; The above
ofstream outfile; program reads
outfile.open(“test.txt”,ios::out); 15 characters
if(outfile.fail()) and stores in
{ file test.txt.
Perror(“Error opening test.txt”); You can easily
}
add data to an
for(int i=1;i<=15;i++) {
cout<< “\nEnter a character : ”; existing file,
cin>>c; or create new
outfile.put(c);// or outfile>>c; files, by
} opening the
output.close(); file in append
}//end main access mode.
Files you open for append access mode (using ios::app) do not have to exist. If the file exists, C++
appends data to the end of the file (as is done when you open a file for write access).
The following program adds three more names to the names.txt file created in the earlier program.
#include<fstream>
using namespace std;
int main()
{
ofstream outdata;
outdata.open(“c:\\names.txt”,ios::app);
if(outdata.fail()){
cout<< “\nError opening names.txt”;
}
outdata<< “Berhanu Teka”<<endl;
outdata<< “Zelalem Assefa”<<endl;
outdata<< “Dagim Sheferaw”<<endl;
outdata.close();
}//end main

If the file names.txt does not exist, C++ creates it and stores the three names to the file.
Basically, you have to change only the open() function’s access mode to turn a file-creation program
into a file-appending program.

7.4.2. Reading from a file


You can read information from a file into your program using the stream extraction operator (>>) just as
you use that operator to input information from the keyboard. The only difference is that you use
an ifstream or fstream object instead of the cin object.
Files you open for read access (using ios::in) must exist already, or C++ gives you an error message.
You can’t read a file that does not exist. Open() returns zero if the file does not exist when you open it
for read access.
Another event happens when you read files. Eventually, you read all the data. Subsequently reading
produces error because there is no more data to read. C++ provides a solution to the end-of-file
occurrence.
If you attempt to read a file that you have completely read the data from, C++ returns the value zero. To
find the end-of-file condition, be sure to check for zero when reading information from files.
Example: the following program reads the content of a file called hello.txt
#include<fstream>
#include<iostream>
using namespace std;
int main()
{
char name[20];
ifstream indata;
indata.open("Hello.txt",ios::in);
if(indata.fail())
{
cout<<"\nError opening file : ";
}
while(!indata.eof())// checks for the end-of-file
{
indata>>name;
cout<<name<<endl;
}
indata.close();
}
You can read a characters from a file using get() function. The following program displays each
character of the file to the screen. NB. A space among characters is considered as a character and hence,
the exact replica of the file will be shown in the screen.
#include<fstream>
#include<iostream>
using namespace std;
int main()
{
char c;
ifstream indata;
indata.open("hello.txt",ios::in);
if(indata.fail())// check the fiel open succeeded
{
cout<<"\nError opening file : ";
}
while(!indata.eof())// check for end of file
{
//indata>>c;
indata.get(c);
cout<<c;
}
indata.close();
}

7.5. Types of files (Text and Binary)


The default access mode for file access is text mode. A text file is an ASCII file, compatible with most
other programming languages and applications. Programs that read ASCII files can read data you create
as C++ text files.
If you specify binary access (ios::binary), C++ creates or reads the file in binary format. Binary
data files are “squeezed”- that is, they take less space than text files. The disadvantage of using binary
files is that other programs can’t always read the data files. Only C++ programs written to access binary
files can read and write them. The advantage of binary files is that you save disk space because your
data files are more compact.
The binary format is a system-specific file format. In other words, not all computers can read a binary
file created on another computer.

7.6. File access methods (sequential and random access files)


Your program can access files either in sequential manner or random manner. The access mode of a file
determines how one can read, write, change, add and delete data from a file.
A sequential file has to be accessed in the same order as the file was written. This is analogues to cassette
tapes: you play music in the same order as it was recorded.
Unlike the sequential files, you can have random-access to files in any order you want. Think of data in a
random-access file as being similar to songs on compact disc (CD): you can go directly to any song you
want to play without having to play or fast-forward through the other songs.

You might also like