Unit1 OOPs
Unit1 OOPs
Prepared By
JAVID AHMAD PARRAY
Assistant Professor
Department of Computer Science
IQBAL INSTITUTE OF TECHNOLOGY AND MANAGEMENT
Laloo Sheshgaribagh Hyderpora Srinagar – 190014
UNIT – I
Procedure Oriented Programming Language
In the procedure oriented approach, the problem is viewed as sequence of things to be
done such as reading, calculating and printing.
Main program
Data Data
Communication
Functions Functions
Object C
Functions
Data
Benefits of OOP
Reusability: In OOP’s programs, functions and modules that are written by a user
can be reused by other users without any modification.
Inheritance: Through this we can eliminate redundant code and extend the use of
existing classes.
Data Hiding: The programmer can hide the data and functions in a class from other
classes. It helps the programmer to build the secure programs.
Easy to Maintain and Upgrade: OOP makes it easy to maintain and modify existing
code as new objects can be created with small differences to existing ones. Software
complexity can be easily managed.
Message Passing: The technique of message passing between objects makes the
interface with external systems easier.
Class
The building block of C++ that leads to Object-Oriented programming is a Class. It is a
user-defined data type, which holds its own data members and member functions, which
can be accessed and used by creating an instance of that class. A class is like a blueprint for
an object. For Example: Consider the Class of Cars. There may be many cars with different
names and brands but all of them will share some common properties like all of them will
have 4 wheels, Speed Limit, Mileage range, etc. So here, the Car is the class, and wheels,
speed limits, and mileage are their properties.
A Class is a user-defined data type that has data members and member functions.
Data members are the data variables and member functions are the functions used to
manipulate these variables together these data members and member functions define
the properties and behavior of the objects in a Class.
In the above example of class Car, the data member will be speed limit, mileage, etc and
member functions can apply brakes, increase speed, etc.
We can say that a Class in C++ is a blueprint representing a group of objects which shares
some common properties and behaviors.
Object
An Object is an identifiable entity with some characteristics and behavior. An Object is an
instance of a Class. When a class is defined, no memory is allocated but when it is
instantiated (i.e. an object is created) memory is allocated.
Objects take up space in memory and have an associated address like a record in pascal or
structure or union. When a program is executed the objects interact by sending messages to
one another. Each object contains data and code to manipulate the data. Objects can interact
without having to know details of each other’s data or code, it is sufficient to know the type
of message accepted and the type of response returned by the objects.
6 JAVID AHMAD PARRAY Assistant Professor Computer Science Department, IITM
OOPs With C++
Encapsulation
Wrapping of data and functions together as a single unit is known as encapsulation. By default
data is not accessible to outside world and they are only accessible through the functions
which are wrapped in a class. prevention of data direct access by the program is called data
hiding or information hiding.
Consider a real-life example of encapsulation, in a company, there are different sections like
the accounts section, finance section, sales section, etc. The finance section handles all the
financial transactions and keeps records of all the data related to finance. Similarly, the sales
section handles all the sales-related activities and keeps records of all the sales. Now there
may arise a situation when for some reason an official from the finance section needs all the
data about sales in a particular month. In this case, he is not allowed to directly access the
data of the sales section. He will first have to contact some other officer in the sales section
and then request him to give the particular data. This is what encapsulation is. Here the data
of the sales section and the employees that can manipulate them are wrapped under a single
name “sales section”.
Encapsulation in C++
Abstraction
Abstraction refers to the act of representing essential features without including the back
ground details or explanation. Classes use the concept of abstraction and are defined as a list
of attributes such as size, weight, cost and functions to operate on these attributes. They
encapsulate all essential properties of the object that are to be created. The attributes are
called as data members as they hold data and the functions which operate on these data are
called as member functions.
Class use the concept of data abstraction so they are called abstract data type (ADT).
Consider a real-life example of a man driving a car. The man only knows that pressing the
accelerator will increase the speed of the car or applying brakes will stop the car but he does
not know how on pressing the accelerator the speed is actually increasing, he does not know
about the inner mechanism of the car or the implementation of an accelerator, brakes, etc.
in the car. This is what abstraction is.
Abstraction using Classes: We can implement Abstraction in C++ using classes. The
class helps us to group data members and member functions using available access
7 JAVID AHMAD PARRAY Assistant Professor Computer Science Department, IITM
OOPs With C++
specifiers. A Class can decide which data member will be visible to the outside world
and which is not.
Abstraction in Header files: One more type of abstraction in C++ can be header files.
For example, consider the pow() method present in math.h header file. Whenever we
need to calculate the power of a number, we simply call the function pow() present in
the math.h header file and pass the numbers as arguments without knowing the
underlying algorithm according to which the function is actually calculating the power
of numbers.
Polymorphism
The word polymorphism means having many forms. In simple words, we can define
polymorphism as the ability of a message to be displayed in more than one form. A person
at the same time can have different characteristics. A man at the same time is a father, a
husband, and an employee. So the same person possesses different behavior in different
situations. This is called polymorphism. An operation may exhibit different behaviors in
different instances. The behavior depends upon the type of data used in the operation.
Different ways to achieving polymorphism in C++ program.
Operator Overloading: The process of making an operator exhibit different behaviors in
different instances is known as operator overloading.
Function Overloading: Function overloading is using a single function name to perform
different types of tasks. Polymorphism is extensively used in implementing inheritance.
Inheritance
The capability of a class to derive properties and characteristics from another class is
called Inheritance. Inheritance is one of the most important features of Object-Oriented
Programming.
Sub Class: The class that inherits properties from another class is called Sub class or
Derived Class.
Super Class: The class whose properties are inherited by a sub-class is called Base Class
or Superclass.
Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to
create a new class and there is already a class that includes some of the code that we
want, we can derive our new class from the existing class. By doing this, we are reusing
the fields and methods of the existing class.
Example: Dog, Cat, Cow can be Derived Class of Animal Base Class.
Inheritance in C++
Dynamic Binding
In dynamic binding, the code to be executed in response to the function call is decided at
run time. C++ has virtual functions to support this. Because dynamic binding is flexible, it
avoids the drawbacks of static binding, which connected the function call and definition at
build time.
Message Passing
Objects communicate with one another by sending and receiving information. A message
for an object is a request for the execution of a procedure and therefore will invoke a
function in the receiving object that generates the desired results. Message passing involves
specifying the name of the object, the name of the function, and the information to be sent.
Employee . Salary (name)
Object Information
Message
C C++
C was developed in 1972 by Dennis Ritchie C++ was developed by Bjarne Stroustrup
at Bell Laboratories. at Bell Laboratories in the early 1980s.
It is a function-driven language. It is an object-driven language.
C++ is both a procedural and an object-
C is a Procedural Oriented language. It does
oriented programming language. It
not support object-oriented programming
supports OOP features such as
(OOP) features such as polymorphism,
polymorphism, encapsulation, and
encapsulation, and inheritance.
inheritance.
C is a subset of C++. C++ is a superset of C.
C++ Tokens
A token represents the smallest meaningful component recognized by the compiler in a
program. It corresponds to a specific element or idea within the programming language.
Tokens are fundamental building blocks for the language and are utilized for creating valid
expressions and statements.
Following are the C++ tokens : (most of c++ tokens are basically similar to the C tokens)
Keywords
Identifiers
Variables
Constants
Operators
Keywords
Keywords in C++ are the tokens that are the reserved words in programming language that
have their specific meaning and functionalities within a program. Keywords cannot be used
as an identifier to name any variables.
The following table shows the standard C++ keywords
Identifiers
Identifiers are the names given to various program elements such as variables, functions ,
arrays and other user-defined data types created by the programmer. These are user
defined names consisting of sequence of letters and digits.
Variables
Variable in C++ is a name given to a memory location. It is the basic unit of storage in a
program.
The value stored in a variable can be changed during program execution.
A variable is only a name given to a memory location, all the operations done on the
variable effects that memory location.
In C++, all the variables must be declared before use.
For example
Here, age is a variable of the int data type, and we have assigned an integer value 14 to it.
A variable name can only have alphabets, numbers, and the underscore _.
A variable name cannot be a keyword. For example, int is a keyword that is used to
denote integers.
A variable name can start with an underscore. However, it's not considered a good
practice.
Declaration of a Variable
A variable is introduced into a program by a declaration which states its type (i.e int, float,
bool or char) and its name, which you are free to choose.
C++ 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 the
base or radix: 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.
Here are some examples of integer literals
212 // Legal
215u // Legal
0xFeeL // Legal
078 // Illegal: 8 is not an octal digit
032UU // Illegal: cannot repeat a suffix
Following are other examples of various types of Integer literals
85 // decimal
0213 // octal
0x4b // hexadecimal
30 // int
30u // unsigned int
30l // long
30ul // unsigned long
Floating-point Literals
A floating-point literal has an integer part, a decimal point, a fractional part, and an exponent
part. You can represent floating point literals either in decimal form or exponential form.
While representing using decimal form, you must include the decimal point, the exponent,
or both and while representing using exponential form, you must include the integer part, the
fractional part, or both. The signed exponent is introduced by e or E.
Here are some examples of floating-point literals
3.14159 // Legal
314159E-5L // Legal
510E // Illegal: incomplete exponent
210f // Illegal: no decimal or exponent
.e55 // Illegal: missing integer or fraction
Boolean Literals
There are two Boolean literals and they are part of standard C++ keywords
Character Literals
Character literals are used to assign a fixed value to characters including alphabets and
digits or special symbols enclosed within single quotation marks( ‘ ’ ).
Each character is associated with its specific numerical value called the ASCII (American
Standard Code For Information Interchange) value.
\\ \ character
\? ? character
\a Alert or bell
\b Backspace
\f Form feed
\n Newline
\r Carriage return
\t Horizontal tab
\v Vertical tab
When the above code is compiled and executed, it produces the following result
Hello World
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"
Defining Constants
There are two simple ways in C++ to define constants
Using #define preprocessor.
Using const keyword.
When the above code is compiled and executed, it produces the following result
50
You can use const prefix to declare constants with a specific type as follows
const type variable = value;
When the above code is compiled and executed, it produces the following result
50
Note that it is a good programming practice to define constants in CAPITALS.
Reference variables
Reference variable is an alternative name of already existing variable. It cannot be changed
to refer another variable and should be initialized at the time of declaration and cannot be
NULL. The operator ‘&’ is used to declare reference variable.
int main() {
string city = "Paris";
// create a reference to the variable
string& ref_city = city;
// display the variable
cout << "Variable Value = " << city << endl;
cout << "Reference Value = " << ref_city << endl;
// modify the variable using reference
ref_city = "New York";
// display the variable
cout << endl << "After Modification: " << endl;
cout << "Variable Value = " << city << endl;
cout << "Reference Value = " << ref_city << endl;
return 0;
}
Output
Variable Value: Paris
Reference Value: Paris
After Modification:
Variable Value: = New York
Reference Value: New York
The character data type is used to store a single character. The keyword used to define a
character is char. Its size is 1 byte and it stores characters enclosed in single quotes (‘ ‘). It
can generally store upto 256 characters according to their ASCII codes.
Syntax
char name;
where name is the identifier assigned to the variable.
Example
#include <iostream>
using namespace std;
int main() {
// Character variable
char c = 'A';
cout << c;
return 0;
}
Output
A
2. Integer Data Type (int)
Integer data type denotes that the given variable can store the integer numbers. The keyword
used to define integers is int. Its size is 4-bytes (for 64-bit) systems and can store numbers
for binary, octal, decimal and hexadecimal base systems in the range from -2,147,483,648 to
2,147,483,647.
Syntax
int name;
where, name is the identifier assigned to the variable.
Example
#include <iostream>
using namespace std;
int main() {
// Creating an integer variable
int x = 25;
cout << x << endl;
// Using hexadecimal base value
x = 0x15;
cout << x;
return 0;
}
Output
25
21
double pi = 3.1415926535;
cout << pi;
return 0;
}
Output
3.14159
6. Void Data Type (void)
The void data type represents the absence of value. We cannot create a variable of void type.
It is used for pointer and functions that do not return any value using the keyword void.
Syntax
void functionName();
Example
#include <iostream>
using namespace std;
// Function with void return type
void hello() {
cout << "Hello, World!" << endl;
}
int main() {
hello();
return 0;
}
Output
Hello, World!
Size of Data Types in C++
The size of C++ data types can vary across different systems, depending on the architecture
of the computer (e.g., 32-bit vs. 64-bit systems) and the compiler being used. But if the
architecture of the computer is same, then the size across different computers remains same.
We can find the size of the data type using sizeof operator.
Example:
24 JAVID AHMAD PARRAY Assistant Professor Computer Science Department, IITM
OOPs With C++
#include <iostream>
using namespace std;
int main() {
// Printing the size of each data type
cout << "Size of int: " << sizeof(int) << " bytes" << endl;
cout << "Size of char: " << sizeof(char) << " byte" << endl;
cout << "Size of float: " << sizeof(float) << " bytes" << endl;
cout << "Size of double: " << sizeof(double) << " bytes";
return 0;
}
Output
Size of int: 4 bytes
Size of char: 1 byte
Size of float: 4 bytes
Size of double: 8 bytes
Size (in
Data Type Meaning
Bytes)
Streams in C++
A stream is a sequence of bytes. It acts either as a source from which the input data can be
obtained or as a destination to which the output data can be sent. The source stream that
provides data to the program is called Input Stream and the destination stream that receives
output from the program is called Output Stream.
In C++, the I/O system contains a hierarchy of classes that are used to define various streams
to deal with both the console and disk files. These classes are called stream classes. The
stream classes are used for input and output operations with the console unit. These classes
are declared in the header file iostream. This file should be included in all the programs that
communicate with the console unit.
The class ios is declared as the virtual base class so that only one copy of its members is
inherited by the iostream. The class ios provides the basic support for formatted and
unformatted I/O operations. The class istream provides the facilities for formatted and
unformatted input while the class ostream provides the facilities for formatted output.
The class iostream provides the facilities for handling both input and output streams. Three
classes namely, istream_withassign, ostream_withassign and iostream_withassign is used to
add assignment operators to these classes.
Overloaded Operators>>and<<
We have used the objects cin and cout for the input and output of data of various types.
The >> operator is overloaded in the istream class and << is overloaded in the ostream class.
It has the following syntax:
cin>>variable1>>variable2>>.....variablen
cout<<c;
cin.get(c); // get another character
}
The ios class contains a large number of member functions that would help us to format the
output in some ways.
Function Task
width() It specifies the required field size for displaying an output value.
It specifies the number of digits to be displayed after the decimal point of
precision()
a float value.
fill() It specifies a character that is used to fill the unused portion of a field.
setf() It specifies format flags that can control the form of the output display.
C++ Manipulators
Manipulators are special functions that can be included in the I/O statements to alter the
format parameters of a stream.
Manipulators Task
It is used to specify the required field size for displaying an output
setw()
value.
It is used to specify the number of digits to be displayed after the
setprecision()
decimal point of a float value.
C++ Operators
The C++ programming language provides a wide range of operators to perform mathematical,
logical, and other operations. An operator is a symbol used to perform mathematical and
logical operations. Every operator has a pre-defined functionality. However, C++ language
provides a concept operator overloading to assign user-defined functionality to most of the
operators.
In C++ language, the operators are classified as follows.
Arithmetic Operators
Relational Operators
Logical Operators
Increment and Decrement Operators
Assignment Operators
Bitwise Operators
Conditional Operators
Scope Resolution Operator
Other Operators
+ Addition 10 + 5 = 15
- Subtraction 10 - 5 = 5
* Multiplication 10 * 5 = 50
/ Division 10 / 5 = 2
< Returns TRUE if the first value is smaller than second 10 < 5 is FALSE
value otherwise returns FALSE
> Returns TRUE if the first value is larger than second value 10 > 5 is TRUE
otherwise returns FALSE
<= Returns TRUE if the first value is smaller than or equal to 10 <= 5 is
second value otherwise returns FALSE FALSE
>= Returns TRUE if the first value is larger than or equal to 10 >= 5 is TRUE
second value otherwise returns FALSE
&& Logical AND - Returns TRUE if all conditions 10 < 5 && 12 > 10 is
are TRUE otherwise returns FALSE FALSE
! Logical NOT - Returns TRUE if condition is !(10 < 5 && 12 > 10) is
FLASE and returns FALSE if it is TRUE TRUE
The increment and decrement operators are used infront of the operand (++a) or after the
operand (a++). If it is used infront of the operand, we call it as pre-increment or pre-
decrement and if it is used after the operand, we call it as post-increment or post-
decrement.
Pre-Increment or Pre-Decrement
In the case of pre-increment, the value of the variable is increased by one before the
expression evaluation. In the case of pre-decrement, the value of the variable is decreased by
one before the expression evaluation. That means, when we use pre-increment or pre-
decrement, first the value of the variable is incremented or decremented by one, then the
modified value is used in the expression evaluation.
Example
#include <iostream>
int main()
{
31 JAVID AHMAD PARRAY Assistant Professor Computer Science Department, IITM
OOPs With C++
int i = 5, j;
j = ++i; // Pre-Increment
cout << "i = " << i << ", j = " << j << endl;
return 0;
When we run the above example code, it produces the following output.
Post-Increment or Post-Decrement
In the case of post-increment, the value of the variable is increased by one after the expression
evaluation. In the case of post-decrement, the value of the variable is decreased by one after
the expression evaluation. That means, when we use post-increment or post-decrement, first
the expression is evaluated with existing value, then the value of the variable is incremented
or decremented by one.
Example
#include <iostream>
int main()
int i = 5, j;
j = i++; // Post-Increment
cout << "i = " << i << ", j = " << j << endl;
32 JAVID AHMAD PARRAY Assistant Professor Computer Science Department, IITM
OOPs With C++
return 0;
When we run the above example code, it produces the following output.
+= Add both left and right-hand side values and store the result A += 10
into left-hand side variable ⇒ A = A+10
& the result of Bitwise AND is 1 if all the bits are 1 otherwise A&B
it is 0 ⇒ 16 (10000)
^ the result of Bitwise XOR is 0 if all the bits are same A^B
otherwise it is 1 ⇒ 13 (01101)
<< the Bitwise left shift operator shifts all the bits to the left by A << 2
the specified number of positions ⇒ 100 (1100100)
>> the Bitwise right shift operator shifts all the bits to the right A >> 2
by the specified number of positions ⇒ 6 (00110)
sizeof operator
This operator is used to find the size of the memory (in bytes) allocated for a variable. This
operator is used with the following syntax.
sizeof(variableName);
Example
int data=5+10*10;
The "data" variable will contain 105 because * (multiplicative operator) is evaluated before
+ (additive operator).
Here, statement may be a single statement or a block of statements, or nothing (in case of
empty statement). The expression must be enclosed in parentheses. If the expression evaluates
to true i.e., a nonzero value, the statement is executed, otherwise ignored. For example, the
following code fragment :
Checks whether the character variable ch stores a space or not; if it does, the number of spaces
are incremented by 1. Consider another example illustrating the use of if statement:
char ch;
cin >> ch;
if(ch == ' ')
{
cout << "You entered a space" << "\n" ;
}
if(ch >= '0' && ch <= '9')
{
cout << "You entered a digit" << "\n";
}
The above example reads a character. If the character input is a space, if flashes a message
specifying it. If the character input is a digit, it flashes a message specifying it. Let's take an
example demonstrating the if statement of C++ practically.
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
char ch;
cout<<"Enter a character: ";
cin>>ch;
if(ch>='0' && ch<='9')
{
cout<<"You entered a digit.";
}
getch();
}
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int num;
cout<<"Enter a number: ";
cin>>num;
if(num%2==0)
{
cout<<"You entered an even number";
}
getch();
}
Following example programs also illustrates the syntax and working of the if statement:
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int x, y, z, max;
cout<<"Enter any three numbers: ";
cin>>x>>y>>z;
max = x;
if(y>max)
{
max = y;
}
if(z>max)
{
max = z;
}
cout<<"\n"<<"The largest of "<<x<<", "<<y<<" and "<<z<<" is "<<max;
getch();
}
When the above C++ program is compile and executed, it will produce the following
output. This is the output, if 3rd number is biggest.
There is another form of if that allows for this kind of either-or condition by providing an
else clause. The syntax of the if-else statement is the following:
if(expression)
{
statement 1;
}
else
{
statement 2;
}
If the expression evaluates to true i.e., a nonzero value, the statement 1 is executed, otherwise,
statement 2 is executed. The statement 1 and statement 2 can be a single statement, or a
compound statement, or a null statement.
Note - Remember, in an if-else statement, only the code associated with if (i.e., statement 1)
or the code associated with else (i.e., statement 2) executes, never both.
Let's take an example program, demonstrating the if-else statement of C++, practically.
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int num;
cout<<"Enter a number: ";
cin>>num;
if(num%2==0)
{
cout<<"You entered an even number";
}
else
41 JAVID AHMAD PARRAY Assistant Professor Computer Science Department, IITM
OOPs With C++
{
cout<<"You entered an odd number";
}
getch();
}
Below are the two sample run of the above C++ program:
Here is another program, also illustrating the use of if-else statement in a C++ program:
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int x, y ;
cout<<"Enter two numbers: ";
cin>>x>>y;
if(x>y)
{
cout<<x<<" is largest";
}
else
{
cout<<y<<" is largest";
}
getch();
}
When the above C++ program is compile and executed, it will produce the following
output:
if(expression 1)
{
body-of-if;
else
{
if(expression 2)
{
statement 1;
}
else
{
statement 2;
}
}
}
if(expression 1)
{
if(expression 2)
{
statement 1;
}
else
{
statement 2;
}
}
else
{
if(expression 3)
{
statement 3;
}
else
{
statement 4;
}
}
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int num;
cout<<"Enter a number: ";
cin>>num;
if(num>100)
{
if(num>500)
{
if(num>10000)
{
cout<<"Its too high..!!";
}
if(num<1000)
{
cout<<"Its medium..!!";
}
}
if(num<=500)
{
cout<<"Its low..!!";
}
}
if(num<=100)
{
cout<<"Its too low..!!";
}
getch();
}
The expression are evaluated from the top downward. As soon as an expression evaluates to
true, the statement associated with it is executed and the rest of the ladder is bypassed. If none
of the expression are true, the final else gets executed. If the final else is missing, no action
takes place if all the conditions are false. Following are some examples illustrates the use of
if-else-if ladder in a C++ program:
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
char ch;
float a, b, result;
cout<<"Enter any two number: ";
cin>>a>>b;
cout<<"\n"<<"Enter the operator(+, -, *, /) : ";
cin>>ch;
cout<<"\n";
if(ch=='+')
result=a+b;
else
if(ch=='-')
result=a-b;
else
if(ch=='*')
result=a*b;
else
if(ch=='/')
result=a/b;
cout<<"\n"<<"The calculated result is : "<<result<<"\n";
getch();
}
Here are the two sample runs of the above C++ program:
#include<iostream.h>
#include<stdlib.h>
#include<conio.h>
void main()
{
clrscr();
char ch;
float a, b, result;
cout<<"Enter any two number: ";
cin>>a>>b;
cout<<"\n"<<"Enter the operator(+, -, *, /) : ";
cin>>ch;
cout<<"\n";
if(ch=='+')
{
result=a+b;
}
else if(ch=='-')
{
result=a-b;
}
else if(ch=='*')
{
result=a*b;
}
else if(ch=='/')
{
result=a/b;
}
else
{
cout<<"Wrong Operator..!!.. exiting...press a key..";
getch();
exit(1);
}
cout<<"\n"<<"The calculated result is : "<<result<<"\n";
getch();
}
When the above C++ program is compile and run, it will produce the following outputs:
Let's take another C++ program, for the complete understanding on the if-else-if ladder in
C++. Before going to this program, let's see the following table to understand the ASCII code
for different character. Because the upcoming program print whether a given character is an
upper case or a lower case character or a digit or any other character. Use the ASCII codes
for it. The ASCII codes are given here in the following table:
'0' - '9' 48 – 57
'A' - 'Z' 65 – 90
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
char ch;
cout<<"Enter a character: ";
cin>>ch;
if(ch >= 48 && ch <= 57)
{
cout<<"\nYou entered a digit";
}
else if(ch >= 65 && ch <= 90)
{
cout<<"\nYou entered an uppercase character";
}
else if(ch >= 97 && ch <=122)
{
cout<<"\nYou entered a lowercase character";
}
else
{
cout<<"\nYou entered a special character";
}
getch();
}
When the above program is compile and executed, it will produce the following output:
It works in the same way as the above given form of if does i.e., expression1 is evaluated, if
it is true, expression2 gets executed (i.e., its value becomes the value of entire expression)
otherwise expression3 gets executed (i.e., its value now becomes the value of the entire
expression). For example, the following if statement:
int c;
if(a>b)
{
c=a;
}
else
{
c=b;
}
int c = a > b ? a : b ;
The expression is evaluated and its values are matched against the values of the constants
specified in the case statements. When a match is found, the statement sequence associated
with that case is executed until the break statement or the end of switch statement is reached.
If a case statement does not include a break statement, then the control continues right on the
next case statement(s) until either a break is encountered or end of switch is reached. This
situation (i.e., missing break in case statement) is called fall through. The default statement
gets executed when no match is found. The default statement is optional and, if it is missing
, no action takes place if all matches fail.
The ANSI standard specifies that a switch can have upto 257 case statements, however, you
must always limit the number of case statements to a smaller amount for the sake of
efficiency.
Following example illustrates the use of switch statement. This program ask to the user to
input number of week's day (1-7) and translate to its equivalent name of the day of the week
(e.g., 1 to Sunday, 2 to Monday, ...., 7 to Saturday).
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int dow;
cout<<"Enter number of week's day (1-7): ";
cin>>dow;
switch(dow)
{
case 1: cout<<"\nSunday";
break;
case 2: cout<<"\nMonday";
break;
case 3: cout<<"\nTuesday";
break;
case 4: cout<<"\nWednesday";
break;
case 5: cout<<"\nThursday";
break;
case 6: cout<<"\nFriday";
break;
case 7: cout<<"\nSaturday";
break;
default: cout<<"\nWrong number of day";
break;
}
getch();
}
When the above program is compile and executed, it will produce the following output:
switch Vs if-else
The switch and if-else both are selection statements and they both let you select an alternative
out of given many alternatives by testing an expression. However, there are some differences
in their operations. These are given below:
The switch statement differs from the if statement in that switch can only test for
equality whereas if can evaluate a relational or logical expression i.e., multiple
conditions.
The switch statement selects its branches by testing the value of same variable (against
a set of constants) whereas the if-else construction lets you use a series of expressions
that may involve unrelated variables and complex expressions.
The if-else is more versatile of the two statements. For example, if-else can handle
ranges whereas switch cannot. Each switch case label must be a single value.
The if-else statement can handle floating-point tests also apart from handling integer
and character tests whereas a switch cannot handle floating-point tests. The case labels
of switch must be an integer (which includes char also).
The switch case label value must be a constant. So, if two or more variables are to be
compared, use if-else.
The switch statement is more efficient choice in terms of code used in a situation that
supports the nature of switch operation (testing a value against a set of constants).
C++ Nested-Switch
Like if statements, a switch can also be nested. There can be a switch as part of the statement
sequence of another switch. For example, the following code fragment is perfectly all right in
C++.
switch(a)
{
case 1: switch(b)
{
case 0: cout << "Divide by zero-Error !!" ;
break;
case 1: res = a/b ;
}
break;
case 2:
:
}
Example: C++ program to check for zero or non-zero and odd or even using nested switch
statement
#include <iostream>
using namespace std;
56 JAVID AHMAD PARRAY Assistant Professor Computer Science Department, IITM
OOPs With C++
int main()
{
int a = 8;
cout<<"The Number is : " <<a <<endl;
switch (a)
{
case 0 :
cout<<"The number is zero" <<endl;
break;
default:
cout<<"The number is a non-zero integer" <<endl;
int b = a % 2;
switch (b)
{
case 0:
cout<<"The number is even" <<endl;
break;
case 1:
cout<<"The number is odd" <<endl;
break;
}
}
return 0;
}
Output
The Number is : 8
The number is a non-zero integer
The number is even
C++ loops
The iteration (for, while, and do-while loop) statements allows a set of instruction to be
performed repeatedly until a certain condition is fulfilled. The iteration statements are also
called loops or looping statements. C++ provides three kinds of loops:
for loop
while loop
do-while loop
All three loop constructs of C++ repeat a set of statements as long as a specified condition
remains true. This specified condition is generally referred to as a loop control. For all three
loop statements, a true condition is any nonzero value. A zero value indicates a false
condition.
Loop Parts
Every loop has its elements that control and govern its execution. Generally, a loop has four
elements that have different purposes. These elements are as:
Initialization Expression(s)
Test Expression
Update Expression(s)
Loop's Body
Initialization Expression(s)
Before entering in a loop, its control variable(s) must be initialized. The initialization of the
control variable(s) takes place under initialization expression(s). The initialization
expression(s) give(s) the loop variable(s) their first value(s). The initialization expression(s)
is executed only once, in the beginning of the loop.
Test Expression
The test expression is an expression whose truth value decides whether the loop-body will be
executed or not. If the test expression evaluates to true i.e., 1, the loop-body gets executed,
otherwise the loop is terminated.
In an entry-controlled loop, the test-expression is evaluated before exiting from the loop. In
C++, the for loop and while loop are entry-controlled loops and do-while loop is exit-
controlled loop.
Update Expression(s)
The update expression(s) change the value(s) of loop variable(s). The update expression(s) is
executed; at the end of the loop after the loop-body is executed.
Loop's Body
The statements that are executed repeatedly (as long as the test-expression is nonzero) form
the body of the loop. In an entry-controlled loop, first test-expression is evaluated and if it is
nonzero, the body-of-the-loop is executed; if the test-expression evaluates to be zero, the loop
is terminated. In an exit-controlled loop, the body-of-the-loop is executed first and then the
test-expression is evaluated. If it evaluates to be zero, the loop is terminated otherwise
repeated.
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int i;
for(i=1; i<=10; i++)
{
cout<<i<<" ";
}
getch();
}
When the above program is compile and executed, it will produce the following output:
The following lines explain the working of the above given for loop program:
Firstly, initialization expression is executed, i.e., i=1 which gives the first value 1 to
variable i.
Then, the test expression is evaluated i.e., i <= 10 which results into true i.e., 1.
Since, the test expression is true, the body-of-the-loop i.e., cout << i << " "; is executed
which prints the current value of i then a single space.
After executing the loop-body, the update expression i.e., i++ is executed which
increments the value of i. (After first execution of the loop, the value of i becomes 2
after the execution of i++, since initially i was 1).
After the update expression is executed, the test-expression is again evaluated. If it is
true the sequence is repeated from the step no 3, otherwise the loop terminates.
Note - Use for loop when you have to repeat a block of statements specific number of times.
for( ; ; )
{
cout << "I will not stop..!!" ;
}
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
for( ; ; )
{
cout<<"This loop will run forever..!!";
}
getch();
}
When the conditional expression is absent, it is assumed to be true. You may have an
initialization and increment expression, but C++ programmers more commonly use the for(;;)
construct to signify an infinite loop. If you try to run the above C++ program, then the output
window will come out like this, printing continuously.
NOTE - You can terminate an infinite loop by pressing Ctrl+C keys. Let's take another
program, prints stars infinite times.
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
for(;;)
{
cout<<"* ";
}
getch();
}
After running this C++ program, output window will look like this, printing stars infinite
times.
See, the body of the above for loop contains just (a null statement). It is an empty loop. An
empty for loop has its applications in pointer manipulations where you need to increment or
decrement pointer position without doing anything else.
Time delay loops are often used in programs. The following code shows how to create one
by using for:
That means if you put a semicolon after for's parenthesis it repeats only for counting the
control variable. And if put a block of statements after such a loop, then it is not part of for
loop. For example, consider the following:
The semicolon after the for loop ends the loop there only. And then, the below is not body of
the for loop.
Where the loop-body may contain a single statement, a compound statement or an empty
statement. The loop iterates while the expression evaluates to true. When the expression
becomes false, the program control passes to the line after the loop-body code.
In a while loop, a loop control variable should be initialized before the loop begins as an
uninitialized variable can not be used in the expression. The loop variable should be updated
inside the body-of-the-while.
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
When the above program compile and executed, it will produce the following output:
The above program inputs an integer num. Then as long as num is nonzero (according to
while (num)) the loop-body iterates i.e., fact is multiplied with num and the result is stored
back in fact, followed by the decrement of num. Again the test-expression (num) is evaluated;
if it is true, the loop repeated otherwise terminated.
In the other two loops for and while, the test-expression is evaluated at the beginning of the
loop i.e., before executing the loop-body. If the test-expression evaluates to false for the first
time itself, the loop is never executed. But in some situations, it is wanted that the loop-body
is executed at least once, no matter what the initial state of the test-expression is. In such
cases, the do-while loop is the obvious choice.
do
{
statement;
}while(test-expression);
The braces { } are not necessary when the loop-body contains a single statement. The
following do-while loop prints all upper-case letters :
char ch = 'A' ;
do
{
cout << "\n" << ch ;
ch++;
}while(ch <= 'Z');
The above code prints characters from 'A' onwards until the condition ch <= 'Z' becomes
false.
The most common use of the do-while loop is in menu selection routine, where the menu is
flashed at least once. Then depending upon the user's response it is either repeated or
terminated.
The following example program is a menu selection program. Following program display a
menu regarding rectangle operations and perform according to the user's response:
#include<iostream.h>
#include<conio.h>
#include<math.h>
#include<process.h>
void main()
{
clrscr();
char ch, ch1;
65 JAVID AHMAD PARRAY Assistant Professor Computer Science Department, IITM
OOPs With C++
When the above program is compile and executed, it will produce the following output:
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int i, j;
for(i=0; i<15; i++)
{
for(j=0; j<=i; j++)
{
cout<<"* ";
}
cout<<"\n";
}
getch();
}
When the above program is compile and executed it will produce the following output:
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int num, temp, i, j;
cout<<"Enter a number: ";
cin>>num;
for(i=0; i<10; i++)
{
num++;
temp=num;
for(j=0; j<=i; j++)
{
cout<<num<<" ";
num++;
}
cout<<"\n";
num=temp;
}
getch();
}
break;
#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 5; i++) {
// break condition
if (i == 3) {
break;
}
cout << i << endl;
}
return 0;
}
Output
1
2
In the above program, the for loop is used to print the value of i in each iteration. Here,
notice the code:
if (i == 3) {
break;
This means, when i is equal to 3, the break statement terminates the loop. Hence, the output
doesn't include values greater than or equal to 3.
#include <iostream>
using namespace std;
int main() {
int number;
int sum = 0;
while (true) {
// take input from the user
cout << "Enter a number: ";
cin >> number;
// break condition
if (number < 0) {
break;
}
// add all positive numbers
sum += number;
}
// display the sum
cout << "The sum is " << sum << endl;
return 0;
}
Output
Enter a number: 1
Enter a number: 2
Enter a number: 3
Enter a number: -5
The sum is 6.
In the above program, the user enters a number. The while loop is used to print the total sum
of numbers entered by the user. Here, notice the code,
if(number < 0) {
break;
This means, when the user enters a negative number, the break statement terminates the loop
and codes outside the loop are executed.
The while loop continues until the user enters a negative number.
i = 3, j = 1
i = 3, j = 2
i = 3, j = 3
In the above program, the break statement is executed when i == 2. It terminates the inner
loop, and the control flow of the program moves to the outer loop.
continue;
In a for loop, continue skips the current iteration and the control flow jumps to
the update expression.
#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 5; i++) {
// condition to continue
if (i == 3) {
continue;
}
cout << i << endl;
}
return 0;
}
Output
1
2
4
5
In the above program, we have used the for loop to print the value of i in each iteration.
Here, notice the code,
if (i == 3) {
continue;
This means
When i is equal to 3, the continue statement skips the current iteration and starts the
next iteration
Note: The continue statement is almost always used with decision-making statements.
In a while loop, continue skips the current iteration and control flow of the program jumps
back to the while condition.
#include <iostream>
using namespace std;
int main() {
int sum = 0;
int number = 0;
while (number >= 0) {
// add all positive numbers
sum += number;
// take input from the user
cout << "Enter a number: ";
cin >> number;
// continue condition
if (number > 50) {
cout << "The number is greater than 50 and won't be calculated." << endl;
number = 0; // the value of number is made 0 again
continue;
}
}
// display the sum
cout << "The sum is " << sum << endl;
return 0;
}
Output
Enter a number: 12
Enter a number: 0
Enter a number: 2
Enter a number: 30
Enter a number: 50
Enter a number: 56
The number is greater than 50 and won't be calculated.
Enter a number: 5
Enter a number: -3
The sum is 99
In the above program, the user enters a number. The while loop is used to print the total sum
of positive numbers entered by the user, as long as the numbers entered are not greater
than 50.
continue;
When the user enters a number greater than 50, the continue statement skips the current
iteration. Then the control flow of the program goes to the condition of while loop.
When the user enters a number less than 0, the loop terminates.
Note: The continue statement works in the same way for the do...while loops.
C++ Pointers
In C++, pointers are variables that store the memory addresses of other variables.
Address in C++
If we have a variable var in our program, &var will give us its address in the memory. For
example,
Example 1: Printing Variable Addresses in C++
#include <iostream>
using namespace std;
int main()
{
// declare variables
int var1 = 3;
int var2 = 24;
int var3 = 17;
// print address of var1
cout << "Address of var1: "<< &var1 << endl;
// print address of var2
cout << "Address of var2: " << &var2 << endl;
// print address of var3
cout << "Address of var3: " << &var3 << endl;
}
Output
Address of var1: 0x7fff5fbff8ac
Address of var2: 0x7fff5fbff8a8
Address of var3: 0x7fff5fbff8a4
Here, 0x at the beginning represents the address is in the hexadecimal form.
Notice that the first address differs from the second by 4 bytes and the second address
differs from the third by 4 bytes.
Declaration of Pointers
int *pointVar;
int* pointVar, p;
var = 5;
pointVar = &var;
Here, 5 is assigned to the variable var. And, the address of var is assigned to
the pointVar pointer with the code pointVar = &var.
To get the value pointed by a pointer, we use the * operator. For example:
int* pointVar, var;
var = 5;
// assign address of var to pointVar
pointVar = &var;
// access value pointed by pointVar
cout << *pointVar << endl; // Output: 5
In the above code, the address of var is assigned to pointVar. We have used
the *pointVar to get the value stored in that address.
When * is used with pointers, it's called the dereference operator. It operates on a pointer
and gives the value pointed by the address stored in the pointer. That is, *pointVar = var.
If pointVar points to the address of var, we can change the value of var by
using *pointVar.
For example,
int var = 5;
int* pointVar;
// assign address of var
pointVar = &var;
// change value at address pointVar
*pointVar = 1;
cout << var << endl; // Output: 1
81 JAVID AHMAD PARRAY Assistant Professor Computer Science Department, IITM
OOPs With C++
Here, pointVar and &var have the same address, the value of var will also be changed
when *pointVar is changed.
C++ Structures
Structure is a collection of variables of different data types under a single name. It is similar
to a class in that, both holds a collection of data of different data types.
For example: You want to store some information about a person: his/her name, citizenship
number and salary. You can easily create different variables name, citNo, salary to store
these information separately.
However, in the future, you would want to store information about multiple persons. Now,
you'd need to create different variables for each information per person: name1, citNo1,
salary1, name2, citNo2, salary2
You can easily visualize how big and messy the code would look. Also, since no relation
between the variables (information) would exist, it's going to be a daunting task.
A better approach will be to have a collection of all related information under a single
name Person, and use it for every person. Now, the code looks much cleaner, readable and
efficient as well.
This collection of all related information under a single name Person is a structure.
83 JAVID AHMAD PARRAY Assistant Professor Computer Science Department, IITM
OOPs With C++
The struct keyword defines a structure type followed by an identifier (name of the
structure).
Then inside the curly braces, you can declare one or more members (declare variables inside
curly braces) of that structure. For example:
struct Person
{
char name[50];
int age;
float salary;
};
Here a structure person is defined which has three members: name, age and salary.
When a structure is created, no memory is allocated.
The structure definition is only the blueprint for the creating of variables. You can imagine
it as a datatype. When you define an integer as below:
int foo;
The int specifies that, variable foo can hold integer element only. Similarly, structure
definition only specifies that, what property a structure variable holds when it is defined.
How to define a structure variable?
Once you declare a structure person as above. You can define a structure variable as:
Person bill;
When structure variable is defined, only then the required memory is allocated by the
compiler.
Considering you have either 32-bit or 64-bit system, the memory of float is 4 bytes,
memory of int is 4 bytes and memory of char is 1 byte.
Hence, 58 bytes of memory is allocated for structure variable bill.
How to access members of a structure?
bill.age = 50;
Output
Enter age: 27
Displaying Information.
Age: 27
Salary: 1024.4
Here a structure Person is declared which has three members name, age and salary.
Inside main() function, a structure variable p1 is defined. Then, the user is asked to enter
information and data entered by user is displayed.
Structure variables can be passed to a function and returned in a similar way as normal
arguments.
void displayData(Person p) {
cout << "\nDisplaying Information." << endl;
cout << "Name: " << p.name << endl;
cout <<"Age: " << p.age << endl;
87 JAVID AHMAD PARRAY Assistant Professor Computer Science Department, IITM
OOPs With C++
Output
Enter Full name: Bill Jobs
Enter age: 55
Enter salary: 34233.4
Displaying Information.
Name: Bill Jobs
Age: 55
Salary: 34233.4
In this program, user is asked to enter the name, age and salary of a Person
inside main() function.
Then, the structure variable p is to passed to a function using.
displayData(p);
The return type of displayData() is void and a single argument of type structure Person is
passed.
Then the members of structure p is displayed from this function.
void displayData(Person);
int main() {
Person p, temp;
temp = getData(p);
p = temp;
displayData(p);
return 0;
}
Person getData(Person p) {
cout << "Enter Full name: ";
cin.get(p.name, 50);
cout << "Enter age: ";
cin >> p.age;
cout << "Enter salary: ";
cin >> p.salary;
return p;
}
void displayData(Person p) {
cout << "\nDisplaying Information." << endl;
cout << "Name: " << p.name << endl;
cout <<"Age: " << p.age << endl;
cout << "Salary: " << p.salary;
}
In this program, we have created two structure variables p and temp of type Person under
the main() function.
The structure variable p is passed to getData() function which takes input from the user
which is then stored in the temp variable.
temp = getData(p);
p = temp;
Then the structure variable p is passed to displayData() function, which displays the
information.
A pointer variable can be created not only for native types like (int, float, double etc.) but
they can also be created for user defined types like structure.
Here is how you can create pointer for structures:
#include <iostream>
using namespace std;
struct temp {
int i;
float f;
};
int main() {
temp *ptr;
return 0;
}
struct Distance {
int feet;
float inch;
};
int main() {
Distance *ptr, d;
ptr = &d;
cout << "Distance = " << (*ptr).feet << " feet " << (*ptr).inch << " inches";
return 0;
Output
Enter feet: 4
Enter inch: 3.5
Displaying information.
Distance = 4 feet 3.5 inches
In this program, a pointer variable ptr and normal variable d of type structure Distance is
defined.
The address of variable d is stored to pointer variable, that is, ptr is pointing to variable d.
Then, the member function of variable d is accessed using pointer.
Notes:
Since pointer ptr is pointing to variable d in this program, (*ptr).inch and d.inch are
equivalent. Similarly, (*ptr).feet and d.feet are equivalent.
However, if we are using pointers, it is far more preferable to access struct members using
the -> operator, since the . operator has a higher precedence than the * operator.
Hence, we enclose *ptr in brackets when using (*ptr).inch. Because of this, it is easier to
make mistakes if both operators are used together in a single code.