Basics of Computer Programming All in One
Basics of Computer Programming All in 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.
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.
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.
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.
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.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.
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.
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
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
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.
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.
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
When learning a new language, the first program people usually write is one that salutes the world :)
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.
#include <iostream>
int main ()
{
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:
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.
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.
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.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.
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)
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
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.
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
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
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
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.
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
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
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
85 // decimal
0213 // octal
0x4b // hexadecimal
30 // int
\\ \ 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
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 */
/*
This is multiline
Comment in C++
*/
#include <iostream>
using namespace std;
main()
{
cout << "Hello World"; // prints Hello World
return 0;
}
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.
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”.
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:
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.
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.
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:
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.
Three facilities offered by C++ for performing repetition are: the while loop, the do-while loop, and
the for 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:
#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
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
}while( condition );
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;
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:
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.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:
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
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.
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 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
}
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.
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;
}
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:
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;
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.
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;
}
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.
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.";
}
}
#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;
}
#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.";
}
}
#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.
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
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.
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.
Suppose user enters 4 which is passed to function factorial(). Here are the steps involved:
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.
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.
we can initialize C++ array elements either one by one or using a single statement as follows:
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:
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:
The above statement will take 10th element from the array and assign the value to salary variable.
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.
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:
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.
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."
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>
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.
#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.
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.
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
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.
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.
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
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;
}
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
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.
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.
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.
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
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”.
#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.