0% found this document useful (0 votes)
9 views

OOPM Notes

The lecture notes cover Object-Oriented Programming (OOP) principles, including concepts like objects, classes, data abstraction, encapsulation, inheritance, and polymorphism. It contrasts OOP with procedural programming, highlighting advantages such as code reusability and easier maintenance, while also noting disadvantages like a steeper learning curve and larger program size. Additionally, it discusses variables, data types, and their definitions within programming languages, particularly C.

Uploaded by

sarvagya
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

OOPM Notes

The lecture notes cover Object-Oriented Programming (OOP) principles, including concepts like objects, classes, data abstraction, encapsulation, inheritance, and polymorphism. It contrasts OOP with procedural programming, highlighting advantages such as code reusability and easier maintenance, while also noting disadvantages like a steeper learning curve and larger program size. Additionally, it discusses variables, data types, and their definitions within programming languages, particularly C.

Uploaded by

sarvagya
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

Lecture Notes Prepared by Mr.

Sarvagya jain

Unit-1

❖ Object Oriented Thinking and Programming:


Object-oriented programming (OOP) is a programming system based on the concept of "objects", which
can contain data and code: data commonly known as attributes or properties and code commonly known
as methods.
A feature of objects is that processes (or methods) are attached to them and can access and modify
object data fields. In this type of OOP, there is usually a special word like this or self used to refer to the
current object.
Object-oriented languages include: Java, C++, C#, Python, R, PHP, Visual Basic.NET, JavaScript,
Ruby, Perl, Object Pascal, Objective-C, Dart, Swift, Scala, Kotlin, Common Lisp, MATLAB, and
Smalltalk.
The Strengths of the OO method are:
● OO programming languages ​support and encourage code reuse, increases editor productivity and
can lead to reduced development and testing costs.
● OO-designed systems are easy to replace.
● OO design can be viewed as a real world model for many in the same way as a computer
simulation model.
● The OO design method meas1ures well from simple to complex systems.
● OO facilitates rapid development by focusing on the early stages of the development process.
The OO paradigm is very close to how we think of problem solving in our everyday lives. We use a
familiar situation to illustrate some basic principles of OO.
Consider the scenario of ordering a pizza for home delivery.
Suppose a person named “xyz” decides he wants pizza for dinner. He has a certain type of pizza in mind
and the specific toppings he likes. Suppose further that he doesn’t want to prepare and cook the pizza
himself. He would like to delegate this responsibility to someone else who has the skills to do this. So
“xyz” makes a telephone call to the local pizza parlour and passes the owner, “abc”, the information
about the pizza he desires and his home address with the full confidence that “abc” will take
responsibility to accomplish the task requested. When the pizza is ready, “abc” passes it to “pqr”, the
delivery person, who then makes the delivery to the correct address.

Notice that the above problem of obtaining a pizza for dinner was solved by finding an appropriate agent
“abc” and passing a message to him containing the request. “abc” then has the responsibility to carry out
the request. Also notice that there is a set of operations or methods that “abc” will use to appropriately
prepare the pizza. These preparation and cooking details, that “xyz” need not know, are “hidden” from
him.
Similarly, when “abc” gives the pizza to “pqr” with the message to deliver, “abc” does not need to know
all the details of how to get the delivery accomplished. These are hidden from him. He has delegated this
task to “pqr” and “pqr” has the method for carrying out the delivery.

This scenario illustrates several aspects of OO:


● An object-oriented program can be viewed as a set of agents called objects which interact by
appropriate message passing. Each object provides a service that is used by other objects.
● The concept of information hiding, frequently called encapsulation, is an important aspect of OO
programs.
● All objects are instances of some class. The methods used by an object are defined in the class
associated with that object. Elements encapsulated inside a class are not accessible to code
outside the class. We sometimes say that classes have a public interface for message

1
Notes Prepared By: Prof. Sarvagya Jain
Lecture Notes Prepared by Mr. Sarvagya jain

communication and a private hidden implementation for method details and attributes. Classes
are also referred to as blueprints for objects.
● Class hierarchies can be constructed in which a subclass inherits attributes from the class above
it.

In the OO world view, The program design process begins with an analysis of system behaviour. Various
UML diagrams can be used to model the behaviour of a system. The three most commonly used graphic
tools are use case, sequence, and class diagrams.
A UML class diagram is shown in Figure.
Class Name

Attributes

Methods()

❖ Features of Object Oriented Programming:


● Object
● Class
● Data Abstraction
● Encapsulation
● Inheritance and Interface
● Polymorphism

Objects:
Any real time entity with state and behaviours known as a thing/object. For example, A dog is an object
because it has states like color, name, breed, etc. as well as behaviours like wagging the tail, barking,
eating, etc.
An object consists of:
Name - the variable name we give it
Member data - the data that describes the object
Member functions - behaviour aspects of the object (functions related to the object itself)

Class : it is a blueprint for objects.Collection of objects is called class. It is a logical entity. A class is a
user-defined type that describes what a certain type of object will look like. A class description consists
of a declaration and a definition. An object is a single instance of a class. You can create many objects
from the same class type.For example Animal , Student ,Employee,

Data Abstraction :
Abstraction is used to hide background details or any unnecessary implementation about the data so that
users only see the required information. It is one of the most important and essential features of
object-oriented programming.
For example, when you wash your clothes in a Washing machine, you put your clothes and detergent
inside the machine and wait for the machine to perform its task. But how does the machine handle your
clothes? What mechanism does it use?
A user is not required to know the engineering behind its workings. This process is similar to data
abstraction; it keeps all the unnecessary information hidden from the users.

Encapsulation :
Encapsulation refers to the bundling of data, along with the methods that operate on that data, into a
single unit. Many programming languages use encapsulation frequently in the form of classes.
Lecture Notes Prepared by Mr. Sarvagya jain

Encapsulation may also refer to a mechanism of restricting the direct access to some components of an
object, such that users cannot access state values for all of the variables of a particular object.
Encapsulation can be used to hide both data members and data functions or methods associated with an
instantiated class or object.
Encapsulation in programming has a few key benefits. These include:
Hiding Data: Users will have no idea how classes are being implemented or stored. All that users will
know is that values are being passed and initialized.
More Flexibility: Enables you to set variables as red or write-only. Examples include: setName(),
setAge() or to set variables as write-only then you only need to omit the get methods like getName(),
getAge() etc.
Easy to Reuse: With encapsulation it's easy to change and adapt to new requirements.

Inheritance :
Inheritance helps to reuse the attributes and methods of an existing class. The mechanism of deriving a
new class using the old class is called inheritance. The old class is known as parent class or super class.
The derived class is called child class or subclass.
There are different types of inheritance. They are single inheritance, multiple inheritance, multi-level
inheritance, and hierarchical inheritance.In single inheritance, there is one base class and one derived
class. In multi-level inheritance, there are three classes namely, base class, intermediate class and
derived class. The intermediate class inherits from the base class, and the derived class inherits from the
intermediate class. In hierarchical inheritance, there is one base class and many derived classes. There
is a special type known as Hybrid inheritance. It is a combination of two or more types of inheritance.

Polymorphism : Polymorphism describes situations in which something occurs in several different


forms. It describes the concept that you can access objects of different types through the same interface.
Each type can provide its own independent implementation of this interface.
There are 2 types of polymorphism:
● static or compile-time
● Dynamic or run time

❖ Comparison between Procedural Programming and Object Oriented Programming:

Procedural Oriented Programming Object Oriented Programming

In object oriented programming, a


In procedural programming, a program is
program is divided into small parts called
divided into small parts called functions.
objects.

Procedural programming follows a top Object oriented programming follows a


down approach. bottom up approach.

Object oriented programming has access


There is no access specifier in procedural
specifiers like private, public, protected
programming.
etc.

Adding new data and functions is not easy. Adding new data and functions is easy.
Lecture Notes Prepared by Mr. Sarvagya jain

Procedural programming does not have


Object oriented programming provides
any proper way for hiding data so it is less
data hiding so it is more secure.
secure.

In procedural programming, overloading is Overloading is possible in object oriented


not possible. programming.

In procedural programming, function is In object oriented programming, data is


more important than data. more important than function.

Procedural programming is based on Object oriented programming is based on


unreal world. real world.

Examples: C, FORTRAN, Pascal, Basic


Examples: C++, Java, Python, C# etc.
etc.

❖ Object Model
Object Model refers to a visual representation of software or systems’ objects, attributes, actions, and
relationships. The basic factors of an object model are classes and objects.
Elements of the Object model
Here are the significant features of the object model.
Abstraction
Abstraction reduces complexity. It comes from recognizing similarities between objects. Abstraction
takes place when the system stress details those that are important to the user. It focuses mostly on the
outside view of the object. Data is abstracted when protected by a set of methods, and only those
methods can access data in the object.
Encapsulation
Encapsulation is achieved through information hiding or data hiding to reduce complexity and increase
reusability. The user cannot see the inside of an object or a class, but the object can be accessed by
calling the object’s methods.
Encapsulation and Abstraction are complementary concepts. In Abstraction, the system focuses on
object behaviour and functionality. Encapsulation focuses on implementation that gives rise to action.
Hierarchy
The hierarchy shows the order in which objects in a system are put together. It also explains the
relationship between different parts of a system. Different properties and functions form a class of the
hierarchy.
A hierarchy class is composed of a base class (parent class) and derived classes (subclass). A derived
class inherits the properties of a parent class.
Through hierarchy, a class can be composed of interrelated subclasses that can have their subclasses
until the smallest level of components is reached.
Here is an example of a class of hierarchy:
Lecture Notes Prepared by Mr. Sarvagya jain

In the scenario above, the vehicle is the base class. The objects car, boat, and aircraft inherit properties
of the base class (vehicle). Objects like truck and van inherit properties from the car. Sailboat and yacht
inherit from the class boat, and helicopter and blimp inherit properties from class aircraft.
Modularity
Modularity refers to dividing a program into components or modules to reduce the problem’s
complexity. Modularity takes place on broad and powerful applications with multiple classes.
The modules help to manage complexity. Modularity focuses on implementation. Making modularity
and Encapsulation related.
Modularity can be viewed as a way of matching encapsulated abstraction into basic components. This
takes place after the partitioning of a system into modules.

❖ Advantages of Oop
● Productivity of software development increased: Object-arranged writing computer programs
are measured, as it gives detachment of obligations in object-based program advancement. It is
additionally extensible, as articles can be stretched out to incorporate new qualities and practices.
Items can likewise be reused inside and across applications. Due to these three variables –
particularity, extensibility, and reusability – object-situated programming gives further developed
programming advancement usefulness over conventional strategy based programming methods.
● Software maintenance improved: For the reasons referenced above, object-oriented
programming is likewise simpler to keep up with. Since the plan is secluded, a piece of the
framework can be refreshed if there should arise an occurrence of issues without a need to roll
out huge scope improvements.
● Quicker improvement: Reuse empowers quicker advancement. Object-situated programming
dialects accompany rich libraries and code created during projects is additionally reusable in
later ventures.
● Cost of development lowered: The reuse of programming likewise brings down the expense of
advancement.
● Good quality software: Faster improvement of programming and lower cost of advancement
permits additional time and assets to be utilised in the confirmation of the product.
object-situated programming will in general bring about greater programming.
❖ Disadvantages of Oop
● Steep expectation to learn and adapt: The perspective engaged with object-situated
programming may not be normal for certain individuals. It is complex to make programs . A
portion of the key programming procedures, like inheritance and polymorphism, can be tested to
appreciate at first.
● Bigger program size: Object-arranged programs commonly include more lines of code than
procedural projects.
● More slow projects: Object-arranged programs are normally slower than procedure-based
programs, as they ordinarily require more guidelines to be executed.
Lecture Notes Prepared by Mr. Sarvagya jain

● Not appropriate for a wide range of issues: There are issues that the programming style,
rational programming style, or strategy based programming style, and applying object-arranged
programming in those circumstances will not bring about effective projects.

Comparison Table for Advantages And Disadvantages of Oop

Advantages Disadvantages

We can reuse the code multiple times using class Size is larger than other programs

Inherit the class to subclass for data redundancy It required a lot of effort to create

It is easy to maintain and modify It is slower than other programs

It maintains the security of data It is not suitable for some sorts of problems

Low-cost development It takes time to get used to it.

❖ Variables and Data Types.


A variable is a name of the memory location. It is used to store data. Its value can be changed, and it can
be reused many times.
It is a way to represent memory location through symbols so that it can be easily identified.
Let's see the syntax to declare a variable:
1. type variable_list;
The example of declaring the variable is given below:
1. int a;
2. float b;
3. char c;
Here, a, b, c are variables. The int, float, char are the data types.
We can also provide values while declaring the variables as given below:
1. int a=10,b=20;//declaring 2 variable of integer type
2. float f=20.8;
3. char c='A';
Rules for defining variables
● A variable can have alphabets, digits, and underscore.
● A variable name can start with the alphabet, and underscore only. It can't start with a digit.
● No whitespace is allowed within the variable name.
● A variable name must not be any reserved word or keyword, e.g. int, float, etc.
Valid variable names:
1. int a;
2. int _ab;
3. int a30;
Invalid variable names:
1. int 2;
2. int a b;
3. int long;
Lecture Notes Prepared by Mr. Sarvagya jain

Data Types:
A data type specifies the type of data that a variable can store such as integer, floating, character, etc.
There are the following data types in C language.
Types Data Types

Basic Data Type int, char, float, double

Derived Data Type array, pointer

User Defined Data Type enum, structure, union, Class

Void Data Type void

Basic Data Types


The basic data types are integer-based and floating-point based. C language supports both signed and
unsigned literals.
The memory size of the basic data types may change according to the 32 or 64-bit operating system.
Let's see the basic data types. Its size is given according to 32-bit architecture.
Data Types Memory Size Range

char 1 byte −128 to 127

signed char 1 byte −128 to 127

unsigned char 1 byte 0 to 255

short 2 byte −32,768 to 32,767

signed short 2 byte −32,768 to 32,767

unsigned short 2 byte 0 to 65,535

int 2 byte −32,768 to 32,767

signed int 2 byte −32,768 to 32,767

unsigned int 2 byte 0 to 65,535

short int 2 byte −32,768 to 32,767

signed short int 2 byte −32,768 to 32,767

unsigned short int 2 byte 0 to 65,535


Lecture Notes Prepared by Mr. Sarvagya jain

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

signed long int 4 byte -2,147,483,648 to 2,147,483,647

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

float 4 byte

double 8 byte

long double 10 byte

❖ Basic Input and Output in C++


C++ comes with libraries that provide us with many ways for performing input and output. In C++ input
and output are performed in the form of a sequence of bytes or more commonly known as streams.
Input Stream: If the direction of flow of bytes is from the device(for example, Keyboard) to the main
memory then this process is called input.
std::cin(standard console input): reads the value from the console as per the type specified.
Syntax : cin>>Variable name;
Output Stream: If the direction of flow of bytes is opposite, i.e. from main memory to device( display
screen ) then this process is called output.
std::cout(standard console input): reads the value from the console as per the type specified.
Syntax : cout<<Variable name;
❖ Operators and Expressions
An operator is a symbol that tells the compiler to perform specific mathematical or logical functions. C
language is rich in built-in operators and provides the following types of operators −
Increment and Decrement Operators
C programming has two operators increment ++ and decrement -- to change the value of an operand
(constant or variable) by 1.
Increment ++ increases the value by 1 whereas decrement -- decreases the value by 1. These two
operators are unary operators, meaning they only operate on a single operand.
++ and -- operator as prefix and postfix
● If you use the ++ operator as a prefix like: ++var, the value of var is incremented by 1; then it
returns the value.
● If you use the ++ operator as a postfix like: var++, the original value of var is returned first; then
var is incremented by 1.
Example: // Working of increment and decrement operators
#include <iostream>
using namespace std;
int main() {
int var1 = 5, var2 = 5;
cout<<var1++<<endl;
cout<<++var2<<endl;
return 0;
}
Output:
5
Lecture Notes Prepared by Mr. Sarvagya jain

6
Arithmetic Operators
An arithmetic operator performs mathematical operations such as addition, subtraction, multiplication,
division etc on numerical values (constants and variables).

Operator Meaning of Operator

+ addition or unary plus

- subtraction or unary minus

* multiplication

/ division

% remainder after division (modulo division)

Example: // Working of arithmetic operators


#include <iostream>
using namespace std;
int main()
{
int a = 9,b = 4, c;
c = a+b;
cout<<c<<endl;
c = a-b;
cout<<c<<endl;
c = a*b;
cout<<c<<endl;
c = a/b;
cout<<c<<endl;
c = a%b;
cout<<”Remainder when a divided by b=”<<c<<endl;
return 0;
}
Output
a+b = 13
a-b = 5
a*b = 36
a/b = 2
Remainder when a divided by b=1
Relational Operators
A relational operator checks the relationship between two operands. If the relation is true, it returns 1; if
the relation is false, it returns value 0.
Relational operators are used in decision making and loops.
Operator Meaning of Operator Example
Lecture Notes Prepared by Mr. Sarvagya jain

== Equal to 5 == 3 is evaluated to 0

> Greater than 5 > 3 is evaluated to 1

< Less than 5 < 3 is evaluated to 0

!= Not equal to 5 != 3 is evaluated to 1

>= Greater than or equal to 5 >= 3 is evaluated to 1

<= Less than or equal to 5 <= 3 is evaluated to 0

Example: // Working of relational operators


#include <iostream>
using namespace std;
int main()
{
int a = 5, b = 5, c = 10;
cout<<( a == b)<<endl;
cout<< (a == c)<<endl;
cout<< (a > b)<<endl;
cout<<( a > c)<<endl;
cout<<( a < b)<<endl;
cout<<"(a < c)<<endl;
cout<<(a != b)<<endl;
cout<<( a != c)<<endl;
cout<<(a >= b)<<endl;
cout<<(a >= c)<<endl;
cout<<(a <= b)<<endl;
cout<<(a <= c)<<endl;
return 0;
}
Output
1
0
0
0
0
1
0
1
1
0
1
1
Logical Operators
Lecture Notes Prepared by Mr. Sarvagya jain

An expression containing a logical operator returns either 0 or 1 depending upon whether the expression
results true or false. Logical operators are commonly used in decision making in C programming.
Operator Meaning Example

Logical AND. True only if If c = 5 and d = 2 then, expression


all operands are true ((c==5) (d>5)) equals to 0.

|| Logical OR. True only if If c = 5 and d = 2 then, expression


either one operand is true ((c==5) || (d>5)) equals to 1.

! Logical NOT. True only if If c = 5 then, expression !(c==5) equals


the operand is 0 to 0.

Example :// Working of logical operators


#include <iostream>
using namespace std;
int main()
{
int a = 5, b = 5, c = 10, result;
result = (a == b) (c > b);
cout<<"\n(a == b) (c > b) is "<< result;
result = (a == b) (c < b);
cout<<"\n(a == b) (c < b) is "<< result;
result = (a == b) || (c < b);
cout<<"\n(a == b) || (c < b) is "<< result;
result = (a != b) || (c < b);
cout<<"\n(a != b) || (c < b) is " <<result;
result = !(a != b);
cout<<"\n!(a != b) is "<< result;
result = !(a == b);
cout<<"\n!(a == b) is "<< result;
return 0;
}
Output
(a == b) (c > b) is 1
(a == b) (c < b) is 0
(a == b) || (c < b) is 1
(a != b) || (c < b) is 0
!(a != b) is 1
!(a == b) is 0
Assignment Operators
An assignment operator is used for assigning a value to a variable. The most common assignment
operator is =
Operator Example Same as

= a=b a=b
Lecture Notes Prepared by Mr. Sarvagya jain

+= a += b a = a+b

-= a -= b a = a-b

*= a *= b a = a*b

/= a /= b a = a/b

%= a %= b a = a%b
Example : // Working of assignment operators
#include <iostream>
using namespace std;
int main()
{
int a = 5, c;
c = a; // c is 5
coût<<"\n c ="<< c;
c += a; // c is 10
coût<<"\n c ="<< c;
c -= a; // c is 5
coût<<"\n c ="<< c;
c *= a; // c is 25
coût<<"\n c ="<< c;
c /= a; // c is 5
coût<<"\n c ="<< c;
c %= a; // c = 0
coût<<"\n c ="<< c;
return 0;
}
Output
c=5
c = 10
c=5
c = 25
c=5
c=0
Bitwise Operators
During computation, mathematical operations like: addition, subtraction, multiplication, division, etc are
converted to bit-level which makes processing faster and saves power.
Bitwise operators are used in C++ programming to perform bit-level operations.
Operators Meaning of operators

& Bitwise AND

| Bitwise OR
Lecture Notes Prepared by Mr. Sarvagya jain

^ Bitwise exclusive OR

~ Bitwise complement

<< Shift left

>> Shift right

1. The (bitwise AND) : takes two numbers as operands and does AND on every bit of two
numbers. The result of AND is 1 only if both bits are 1.
2. The | (bitwise OR) : takes two numbers as operands and does OR on every bit of two numbers.
The result of OR is 1 if any of the two bits is 1.
3. The ^ (bitwise XOR) : takes two numbers as operands and does XOR on every bit of two
numbers. The result of XOR is 1 if the two bits are different.
4. The << (left shift): takes two numbers, left shifts the bits of the first operand, the second operand
decides the number of places to shift.
5. The >> (right shift) :takes two numbers, right shifts the bits of the first operand, the second
operand decides the number of places to shift.
6. The ~ (bitwise NOT) : C or C++ takes one number and inverts all bits of it
Example:
// Program to demonstrate use of bitwise operators
#include <iostream>
using namespace std;
int main()
{
unsigned char a = 5, b = 9;
cout<<"\n a = , b = "<< a<< b;
cout<<"\n a&b = "<<(a&b);
cout<<"\n a|b = " <<(a | b);
cout<<"\n a^b = "<<( a ^ b);
coût<<"\n ~a =" <<(a = ~a);
cout<<"\n b<<1 ="<<( b << 1);
cout<<"\n b>>1 ="<<( b >> 1);
return 0;
}
Output:
a = 5, b = 9
a&b=1
a|b = 13
a^b = 12
~a = 250
b<<1 = 18
b>>1 = 4
Ternary Operator
The ternary operator is used to execute code based on the result of a binary condition.
It takes in a binary condition as input, which makes it similar to an 'if-else' control flow block. It also,
however, returns a value, behaving similar to a function.
Lecture Notes Prepared by Mr. Sarvagya jain

Syntax
result = binaryCondition ? value Returned If True : value Returned If False;
Example:
#include <iostream>
using namespace std;
int main()
{
int age;
cout<<"Enter your age";
cin>>age;
(age>=18)? cout<<"eligible for voting" : cout<<"not eligible for voting";
return 0;
}
Output:
Enter your Age 24;
You are eligible for voting;
❖ Control Flow Statement.
Control statements control the flow of execution of the statements of a program. The various types of
control statements in C language are as under:-
● Conditional/Branching Statements.
● Looping / Iteration Statement.
● Jumping Statement
Conditional/Branching Statements.
These are the statements that execute a statement on the base of the condition. When the condition
matches, the statement is executed or else it is skipped. There are 4 types of selection statements.
These are being explained in detail below.
If Statement
If the statement is a condition block. When the condition is true, all the statements given in this block
are executed. If the condition is not true, then no statement of this block is executed. The general syntax
if(condition)
{
//statements to be executed when condition is true.
}
Example:
// Program to display a number if it is negative
#include <iostream>
using namespace std;
int main()
{
int number;
cout<<"Enter an integer: ";
cin>> number;
// true if number is less than 0
if (number < 0) {
cout<<"\n You entered ."<< number;
}
return 0;
}
Output
Enter an integer: -2
You entered -2.
Lecture Notes Prepared by Mr. Sarvagya jain

If-else Statement
The else block is also appended with the if statement in the if else statement. Else block contains
statements that will execute if the condition is false. Its general syntax is being given below.
if(condition)
{
//Statements to be executed when condition is true.
}
else
{
//Statements to be executed when condition is false.
}
Example
// Check whether an integer is odd or even
#include <iostream>
using namespace std;
int main() {
int number;
cout<<"Enter an integer: ";
cin>> number;
// True if the remainder is 0
if (number%2 == 0) {
cout<<" is an even integer."<<number;
}
else {
cout<<" is an odd integer."<<number;
}
return 0;
}
Output
Enter an integer: 7
7 is an odd integer.
if...else if Ladder
The if...else statement executes two different codes depending upon whether the test expression is true
or false. Sometimes, a choice has to be made from more than 2 possibilities.
The if...else ladder allows you to check between multiple test expressions and execute different
statements.
Syntax
if (test expression1) {
// statement(s)
}
else if(test expression2) {
// statement(s)
}
else if (test expression3) {
// statement(s)
}
.
.
else {
// statement(s)
}
Lecture Notes Prepared by Mr. Sarvagya jain

Example
// Program to relate two integers using =, > or < symbol
#include <iostream>
using namespace std;
int main() {
int number1, number2;
cout<<"Enter two integers: ";
cin>>number1>> number2;
//checks if the two integers are equal.
if(number1 == number2) {
cout<<"Result: "<<number1<<” = ”<<number2;
}
//checks if number1 is greater than number2.
else if (number1 > number2) {
cout<<"Result: " <<number1<<”>” <<number2;
}
//checks if both test expressions are false
else {
cout<<"Result: "<<number1<<”<”<< number2;
}
return 0;
}
Output
Enter two integers: 12
23
Result: 12 < 23
Nested if...else
It is possible to include an if...else statement inside the body of another if...else statement.
Example
// Program to relate two integers using =, > or < symbol
#include <iostream>
using namespace std;
int main() {
int number1, number2;
cout<<"Enter two integers: \n";
cin>> number1>> number2;
if (number1 >= number2) {
if (number1 == number2) {
cout<<"Result: "<<number1<<” = ”<<number2;
}
else {
cout<<"Result: "<< number1<<”>”<< number2;
}
}
else {
cout<<"Result: "<<number1<<”<”<<number2;
}
return 0;
}
Enter two integers: 12
23
Lecture Notes Prepared by Mr. Sarvagya jain

Result: 12 < 23
Switch ... case
The switch case statement is used when we have multiple options and we need to perform a different
task for each option.
Syntax:
switch (variable or an integer expression)
{
case constant:
//C++ Statements
;
case constant:
//C++ Statements
;
default:
//C++ Statements
;
}
Example:
// the working of a switch case statement in C++ program.
#include <iostream>
using namespace std;
int main()
{
int num=2;
switch(num+2)
{
case 1:
cout<<"Case1: Value is: " <<num<<endl;
case 2:
cout<<"Case1: Value is: " <<num<<endl;
case 3:
cout<<"Case1: Value is: "<<num<<endl;
default:
cout<<"Default: Value is: "<< num<<endl;
}
return 0;
}
Output:
Default: value is: 4
Looping Statements:
Looping Statements in C execute the sequence of statements many times until the stated condition
becomes false. A loop in C consists of two parts, a body of a loop and a control statement. The control
statement is a combination of some conditions that direct the body of the loop to execute until the
specified condition becomes false.
‘C++’ programming language provides us with three types of loop constructs:
1. The while loop
2. The do-while loop
3. The for loop
Lecture Notes Prepared by Mr. Sarvagya jain

Sr. Loop Type Description


No.

1. While Loop In a while loop, a condition is evaluated before processing a body


of the loop. If a condition is true then and only then the body of a
loop is executed.

2. Do-While Loop In a do…while loop, the condition is always executed after the
body of a loop. It is also called an exit-controlled loop.

3. For Loop In a for loop, the initial value is performed only once, then the
condition tests and compares the counter to a fixed value after each
iteration, stopping the for loop when false is returned.

For loop
A for loop is a more efficient loop structure in ‘C++’ programming. The general structure of for loop
syntax in C++ is as follows:
Syntax of For Loop:
for (initial value; condition; incrementation or decrementation )
{
statements;
}
// Following program illustrates the for loop in C++ programming example:
#include<iostream>
using namespace std;
int main()
{
int number;
for(number=1;number<=10;number++) //for loop to print 1-10 numbers
{
cout<<"\n"<<number; //to print the number
}
return 0;
}
Output:
1
2
3
4
5
6
7
8
9
10
While Loop :
A while loop is the most straightforward looping structure. While loop syntax in C++ programming
language is as follows:
Syntax of While Loop in C++:
Lecture Notes Prepared by Mr. Sarvagya jain

while (condition) {
statements;
}
Following program illustrates while loop in C++ programming example:
#include<iostream>
using namespace std;
#include<conio.h>
int main()
{
int num=1; //initializing the variable
while(num<=10) //while loop with condition
{
cout<<"\n"<<num;
num++; //incrementing operation
}
return 0;
}
Output:
1
2
3
4
5
6
7
8
9
10
Do-While loop:
A do…while loop in C++ is similar to the while loop except that the condition is always executed after
the body of a loop. It is also called an exit-controlled loop.
Syntax of do while loop in C++ programming language is as follows:
Syntax of Do-While Loop in C++:
do {
statements
} while (expression);

//Below is a do-while loop in C++ example to print a table of number 2:


#include<iostream>
using namespace std;
#include<conio.h>
int main()
{
int num=1; //initializing the variable
do //do-while loop
{
cout<<"\n"<<2*num;
num++; //incrementing operation
}while(num<=10);
return 0;
}
Lecture Notes Prepared by Mr. Sarvagya jain

Output:
2
4
6
8
10
12
14
16
18
20
Jumping Statement:
The C programming language allows jumping from one statement to another. It also supports break,
continue, return and go to jump statements.
break
● It is a keyword which is used to terminate the loop (or) exit from the block.
● The control jumps to the next statement after the loop (or) block.
● break is used with for, while, do-while and switch statement.
● When break is used in nested loops then, only the innermost loop is terminated.
The syntax for break statement is as follows −

Example
//Following is the C++ program for break statement −
#include<iostream>
using namespace std;
int main( ){
int i;
for (i=1; i<=5; i++){
cout<< i<<endl;
if (i==3)
break;
}
return 0;
}
Output
When the above program is executed, it produces the following output −
123
continue
The syntax for the continue statement is as follows −
Lecture Notes Prepared by Mr. Sarvagya jain

Example
//Following is the C++ program for the continue statement −
#include<iostream>
using namespace std;
int main( ){
int i;
for (i=1; i<=5; i++){
if (i==2)
continue;
cout<<"\n"<< i;
}
return 0;
}
Output
When the above program is executed, it produces the following output −
12345
goto
It is used after the normal sequence of program execution by transferring the control to some other part
of the program.
The syntax for the goto statement is as follows −

Example
//Following is the C++ program for the goto statement −
#include<iostream>
using namespace std;
int main( ) {
cout<<"Hello";
goto l1;
cout<<"How are";
l1: cout<<"you";
Lecture Notes Prepared by Mr. Sarvagya jain

return 0;
}
Output
When the above program is executed, it produces the following output −
Hello you

❖ Array
An array is defined as the collection of similar types of data items stored at contiguous memory
locations. Arrays are the derived data type which can store the primitive type of data such as int, char,
double, float, etc. It also has the capability to store the collection of derived data types, such as pointers,
structure, etc. The array is the simplest data structure where each data element can be randomly accessed
by using its index number.
Declaration of Array
data_type array_name[array_size];
the example to declare the array.
int marks[5];
Here, int is the data_type, marks are the array_name, and 5 is the array_size.
Initialization of Array
The simplest way to initialize an array is by using the index of each element. We can initialize each
element of the array by using the index. Consider the following example.
1. marks[0]=80;//initialization of array
2. marks[1]=60;
3. marks[2]=70;
4. marks[3]=85;
5. marks[4]=75;

// array example
#include<iostream>
using namespace std;
int main(){
int i=0;
int marks[5];//declaration of array
marks[0]=80;//initialization of array
marks[1]=60;
marks[2]=70;
marks[3]=85;
marks[4]=75;
//traversal of array
for(i=0;i<5;i++){
cout<<" \n"<<marks[i];
}//end of for loop
return 0;
}
Lecture Notes Prepared by Mr. Sarvagya jain

Output
80
60
70
85
75
Declaration with Initialization
We can initialize the array at the time of declaration.
int marks[5]={20,30,40,50,60};
In such a case, there is no requirement to define the size.
int marks[]={20,30,40,50,60};
//program to declare and initialize the array.
#include<iostream>
using namespace std;
int main(){
int i=0;
int marks[5]={20,30,40,50,60};//declaration and initialization of array
//traversal of array
for(i=0;i<5;i++){
cout<<" \n"<<marks[i];
}
return 0;
}
Output
20
30
40
50
60
Multidimensional Array -Two Dimensional Array
The two-dimensional array can be defined as an array of arrays. The 2D array is organized as matrices
which can be represented as the collection of rows and columns.
Declaration of two dimensional Array.
The syntax to declare the 2D array is given below.
data_type array_name[rows][columns];
example.
int twodimen[4][3];
Here, 4 is the number of rows, and 3 is the number of columns.
Initialization of 2D Array
The two-dimensional array can be declared and defined in the following way.
int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
//Two-dimensional array example.
#include<iostream>
using namespace std;
int main(){
int i=0,j=0;
int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
for(i=0;i<4;i++){
for(j=0;j<3;j++){
coût<<arr[i][j];
}
Lecture Notes Prepared by Mr. Sarvagya jain

}
return 0;
}
Output
1
2
3
2
3
4
3
4
5
4
5
6

You might also like