0% found this document useful (0 votes)
19 views26 pages

Unit I Introduction to OOP

Uploaded by

amrutachougale
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
19 views26 pages

Unit I Introduction to OOP

Uploaded by

amrutachougale
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 26

Object Oriented Programming using C++

Unit 1: Introduction to OOP


Structure of C++ Program:-

The C++ program is written using a specific template structure. The structure of the program
written in C++ language is as follows:

Documentation Section:
 This section comes first and is used to document the logic and purpose of the program.
Documentation section is the comment and is not compiled by the compiler. It is optional and
the program can execute without them.
 Link Section-
The linking section contains two parts:
Header Files:
 In order to use pre-defined elements in a program such as built-in functions, classes,
keywords, constants, operators, etc.(which are defined in the standard C++ library), an
appropriate header must be included in the program.
 Standard headers(iostream) are specified in a program through the preprocessor
directive #include. When the compiler processes the instruction #include<iostream>, it includes
the contents of the stream in the program. This enables the programmer to use standard input,
output, and error facilities that are provided only through the standard streams defined in
<iostream>. These standard streams process data as a stream of characters, that is, data is read
and displayed in a continuous flow. The standard streams defined in <iostream> are listed here.

#include<iostream>

Namespaces:
 A namespace permits grouping of various entities like classes, objects, functions, and
various C++ tokens, etc. under a single name.
 Any user can create separate namespaces of its own and can use them in any other program.
 namespace std contains declarations for cout, cin, endl, etc. statements.

using namespace std;


 Namespaces can be accessed in multiple ways:
 using namespace std;
 using std :: cout;

Definition Section:
 It is used to declare some constants and assign them some value.

Mrs. P.D.Titavekar
Object Oriented Programming using C++
 In this section, anyone can define your own datatype using primitive data types.
 In #define is a compiler directive which tells the compiler whenever the message is found to
replace it with given string.
Global Declaration Section:
 The variables and the class definitions which are going to be used in the program are declared
to make them global.
 The scope of the variable declared in this section lasts until the entire program terminates.
 These variables are accessible within the user-defined functions also.
Function Declaration Section:
 It contains all the functions which our main functions need.
 Usually, this section contains the User-defined functions.
 This part of the program can be written after the main function but for this, write the function
prototype in this section for the function which for you are going to write code after the main
function.
Main Function:
 The main function tells the compiler where to start the execution of the program. The execution
of the program starts with the main function.
 All the statements that are to be executed are written in the main function.
 The compiler executes all the instructions which are written in the curly braces {} which
encloses the body of the main function.
 Once all instructions from the main function are executed, control comes out of the main
function and the program terminates and no further execution occur.

1.//Simple Hello World

#include<iostream>

using namespace std;

int main()

cout<<"Hello World"<<endl;

return 0;

2. /* Print hello world using £define that is global declaration */

#include<iostream>

using namespace std;

#define msg "Hello World"

int main()

cout<<msg<<endl;

Mrs. P.D.Titavekar
Object Oriented Programming using C++
return 0;

3. /* Print hello world using function declaration*/

#include<iostream>

using namespace std;

void display();

int main()

display();

return 0;

void display()

cout<<"Hello World";

4. /* Print hello world using scope resolution operator that iswithout namespace use */

#include<iostream>

int main()

std::cout<<"Hello World"<<std::endl;

return 0;

5./* To calculate addition of two numbers*/


#include <iostream>

using namespace std;

Mrs. P.D.Titavekar
Object Oriented Programming using C++

int main() {

int a, b, sum=0;

cout << "Enter any two numbers: ";

cin >> a >> b;

// sum of two numbers in stored in variable sum Of Two Numbers

sum = a+b;

// prints sum

cout <<‖ Addition of ‖ <<a<<‖ and ‖ <<b<<‖ is ‖<<sum;

return 0;

Basic concepts of OOP:-

Object-oriented programming – As the name suggests uses objects in programming. Object-oriented


programming aims to implement real-world entities like inheritance, hiding, polymorphism, etc. in
programming. The main aim of OOP is to bind together the data and the functions that operate on
them so that no other part of the code can access this data except that function.
There are some basic concepts that act as the building blocks of OOPs i.e.
1. Class
2. Objects
3. Encapsulation
4. Abstraction
5. Polymorphism
6. Inheritance
7. Dynamic Binding
8. Message Passing

Class
A Class in C++ is a blueprint representing a group of objects which shares some common
properties and behaviors.
 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.

Mrs. P.D.Titavekar
Object Oriented Programming using C++
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.
// C++ Program to show the syntax/working of Objects as a

// part of Object Oriented PProgramming

#include <iostream>

using namespace std;

class person {

char name[20];

int id;

public:

void getdetails() {}

};

int main()

person p1; // p1 is a object

return 0;

Objects take up space in memory and have an associated address like a record in structure or union.
When a program is executed the objects interact by sending messages to one another.

Data Encapsulation and Abstraction


Encapsulation

The wrapping up of data and function into a single unit is known as Encapsulation.

Abstraction

Abstraction means displaying only essential information and hiding the details. Data abstraction
refers to providing only essential information about the data to the outside world, hiding the
background details or implementation.

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

Mrs. P.D.Titavekar
Object Oriented Programming using C++
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.

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.

C++ supports operator overloading and function overloading.


 Operator Overloading: The process of making an operator exhibit different behaviours 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.
Example: Suppose we have to write a function to add some integers, sometimes there are 2
integers, and sometimes there are 3 integers. We can write the Addition Method with the same
name having different parameters, the concerned method will be called according to parameters.

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.

Mrs. P.D.Titavekar
Object Oriented Programming using C++
Dynamic Binding
In dynamic binding, the code to be executed in response to the function call is decided at runtime.
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.
Features of OOPs i.e.
1. Class
2. Objects
3. Encapsulation
4. Abstraction
5. Polymorphism
6. Inheritance
7. Dynamic Binding
8. Message Passing

Benefits of OOP:-
 We can build the programs from standard working modules that communicate with one another,
rather than having to start writing the code from scratch which leads to saving of development
time and higher productivity,
 OOP language allows breaking the program into the bit-sized problems that can be solved
easily (one object at a time).
 The new technology promises greater programmer productivity, better quality of software and
lesser maintenance cost.
 OOP systems can be easily upgraded from small to large systems.
 It is possible that multiple instances of objects co-exist without any interference,
 It is very easy to partition the work in a project based on objects.
 It is possible to map the objects in problem domain to those in the program.
 The principle of data hiding helps the programmer to build secure programs which cannot be
invaded by the code in other parts of the program.
 By using inheritance, we can eliminate redundant code and extend the use of existing classes.
 Message passing techniques is used for communication between objects which makes the
interface descriptions with external systems much simpler.
 The data-centered design approach enables us to capture more details of model in an
implementable form.

C++ Data Types

In C++, data types are declarations for variables. This determines the type and size of data associated
with variables.

C++ supports the following data types:


1. Primary or Built-in or Fundamental data type
2. Derived data types
3. User-defined data types

Mrs. P.D.Titavekar
Object Oriented Programming using C++
1. Primary or Built-in or Fundamental data type

These data types are built-in or predefined data types and can be used directly by the user to declare
variables.

Datatype Modifiers
As the name suggests, datatype modifiers are used with built-in data types to modify the length of
data that a particular data type can hold.
Data type modifiers available in C++ are:
 Signed
 Unsigned
 Short
 Long

The below table summarizes the modified size and range of built-in datatypes when combined with
the type modifiers:
Data Type Size (in bytes) Range

short int 2 -32,768 to 32,767

unsigned short int 2 0 to 65,535

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

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

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

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

long long int 8 -(2^63) to (2^63)-1

unsigned long long int 8 0 to 18,446,744,073,709,551,615

signed char 1 -128 to 127

unsigned char 1 0 to 255

float 4 -3.4×10^38 to 3.4×10^38

double 8 -1.7×10^308 to1.7×10^308

long double 12 -1.1×10^4932 to1.1×10^4932

wchar_t 2 or 4 1 wide character

Mrs. P.D.Titavekar
Object Oriented Programming using C++
2. Derived Data Types

The data-types that are derived from the primitive or built-in datatypes are referred to as Derived
Data Types. These can be of four types namely:
 Function
 Array
 Pointers
 References

1. Function: A function is a block of code or program-segment that is defined to perform a specific


well-defined task. A function is generally defined to save the user from writing the same lines of
code again and again for the same input. All the lines of code are put together inside a single
function and this can be called anywhere required. main() is a default function that is defined in
every program of C++.
Syntax:
Return_Type function_Name(parameters)
{
//Statements
}
Ex:- void Sum(int a,int b)

Int sum;

sum =a+b;

cout<<‖Sum = ‖<< sum;

2. Array: An array is a collection of items stored at continuous memory locations. The idea of
array is to represent many instances in one variable.

Syntax:
DataType ArrayName[size];
Ex:- int a[10];
3. Pointers: Pointers are symbolic representation of addresses. They enable programs to simulate
call-by-reference as well as to create and manipulate dynamic data structures. It‘s general
declaration in C/C++ has the format:
Syntax:
datatype *ptr_name;
Example:
int *p;
4. Reference: When a variable is declared as reference, it becomes an alternative name for an
existing variable. A variable can be declared as reference by putting ‗&‘ in the declaration.

Mrs. P.D.Titavekar
Object Oriented Programming using C++

3. User-Defined DataTypes:

The data types that are defined by the user are called the derived datatype or user-defined derived
data type.
These types include:
 Class
 Structure
 Union
 Enumeration
 Typedef defined DataType
Below is the detailed description of the following types:
1. 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.
Syntax:

Example:

Class College
{
Public:
Char name[10]=‖nckbca‖;
Void display()
{
Cout<<‖College name is ‖<<name;
}
}

Structure: A structure is a user defined data type in C/C++. A structure creates a data type that
can be used to group items of possibly different types into a single type.

Mrs. P.D.Titavekar
Object Oriented Programming using C++
Union: Like Structures, union is a user defined data type. In union, all members share the same
memory location.
Enumeration: Enumeration (or enum) is a user defined data type in C. It is mainly used to
assign names to integral constants, the names make a program easy to read and maintain.
Syntax:

enum State {Working = 1, Failed = 0};

// Program to demonstrate working

// of enum in C++

#include <iostream>

using namespace std;

enum week { Mon,

Tue,

Wed,

Thur,

Fri,

Sat,

Sun };

int main()

enum week day;

day = Wed;

Mrs. P.D.Titavekar
Object Oriented Programming using C++

cout << day;

return 0;

Output:
2

Typedef : C++ allows you to define explicitly new data type names by using the keyword
typedef. Using typedef does not actually create a new data class, rather it defines a name for an
existing type. This can increase the portability(the ability of a program to be used across
different types of machines; i.e., mini, mainframe, micro, etc; without much changes into the
code)of a program as only the typedef statements would have to be changed. Using typedef one
can also aid in self-documenting code by allowing descriptive names for the standard data
types.
Syntax:
typedef datatype name;
Keywords
Keywords(also known as reserved words) have special meanings to the C++ compiler and are
always written or typed in short(lower) cases. Keywords are words that the language uses for a
special purpose, such as void, int, public, etc. It can‘t be used for a variable name or function name
or any other identifiers. The total count of reserved keywords is 95. Below is the table for some
commonly used C++ keywords.
C++ Keyword

asm double new switch

auto else operator template

break enum private this

case extern protected throw

catch float public try

char for register typedef

class friend return union

const goto short unsigned

Mrs. P.D.Titavekar
Object Oriented Programming using C++

C++ Keyword

continue if signed virtual

default inline sizeof void

delete int static volatile

do long struct while


 asm: To declare that a block of code is to be passed to the assembler.
 auto: A storage class specifier that is used to define objects in a block.
 continue:- Transfers control to the start of a loop.
 enum: To declare a user-defined enumeration data type.
 friend: A class or operation whose implementation can access the private data members of a
class.
 goto: Transfer control to a specified label.
 inline: A function specifier that indicates to the compiler that inline substitution of the
function body is to be preferred to the usual function call implementation.
 operator: Overloads a c++ operator with a new declaration.
 register: A storage class specifier that is an auto specifier, but which also indicates to the
compiler that an object will be frequently used and should therefore be kept in a register.
 short: A data type modifier that defines a 16-bit int number.
 signed: A data type modifier that indicates an object‘s sign is to be stored in the high-order bit.
 sizeof: Returns the size of an object in bytes.
 template: parameterized or generic type.
 this: A class pointer points to an object or instance of the class.
 throw: Generate an exception.
 try: Indicates the start of a block of exception handlers.
 typedef: Synonym for another integral or user-defined type.
 unsigned: A data type modifier that indicates the high-order bit is to be used for an object.
 virtual: A function specifier that declares a member function of a class that will be redefined by
a derived class.

Operators in C++ :-
An operator is a symbol that operates on a value to perform specific mathematical or logical
computations. They form the foundation of any programming language.
Operators in C++ can be classified into 6 types:
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Bitwise Operators
5. Assignment Operators
6. Ternary or Conditional Operators

1) Arithmetic Operators

Arithmetic Operators can be classified into 2 Types:


A) Unary Operators: These operators operate or work with a single operand. For example:
Increment(++) and Decrement(–) Operators.

Mrs. P.D.Titavekar
Object Oriented Programming using C++

Name Symbol Description Example

int a = 5;
Increases the integer value of the variable by
Increment Operator ++ a++; // returns
one
6

int a = 5;
Decrement Decreases the integer value of the variable by

Operator one a–; // returns 4

B) Binary Operators: These operators operate or work with two operands. For example:
Addition(+), Subtraction(-), etc.
Name Symbol Description Example

int a = 3, b = 6;
Addition + Adds two operands
int c = a+b; // c = 9

int a = 9, b = 6;
Subtraction – Subtracts second operand from the first
int c = a-b; // c = 3

int a = 3, b = 6;
Multiplication * Multiplies two operands
int c = a*b; // c = 18

int a = 12, b = 6;
Division / Divides first operand by the second operand
int c = a/b; // c = 2

int a = 8, b = 6;
Modulo Operation % Returns the remainder an integer division
int c = a%b; // c = 2

2) Relational Operators

Name Symbol Description Example

int a = 3, b
= 6;
Is Equal To == Checks if both operands are equal a==b;
// returns
false

Checks if first operand is greater than the second int a = 3, b


Greater Than > = 6;
operand

Mrs. P.D.Titavekar
Object Oriented Programming using C++

Name Symbol Description Example

a>b;
// returns
false

int a = 3, b
= 6;
Greater Than or Checks if first operand is greater than or equal to a>=b;
>=
Equal To the second operand
// returns
false

int a = 3, b
= 6;
Checks if first operand is lesser than the second a<b;
Less Than <
operand
// returns
true

int a = 3, b
= 6;
Less Than or Equal Checks if first operand is lesser than or equal to a<=b;
<=
To the second operand
// returns
true

int a = 3, b
= 6;
Not Equal To != Checks if both operands are not equal a!=b;
// returns
true

3) Logical Operators

These operators are used to combine two or more conditions or constraints or to complement the
evaluation of the original condition in consideration. The result returns a Boolean value,
i.e., true or false.
Name Symbol Description Example

int a = 3, b =
Logical Returns true only if all the operands are true or non- 6;
&&
AND zero a&&b;
// returns true

Mrs. P.D.Titavekar
Object Oriented Programming using C++

Name Symbol Description Example

int a = 3, b =
Returns true if either of the operands is true or non- 6;
Logical OR ||
zero a||b;
// returns true

int a = 3;
Logical NOT ! Returns true if the operand is false or zero !a;
// returns false

4) Bitwise Operators

These operators are used to perform bit-level operations on the operands. The operators are first
converted to bit-level and then the calculation is performed on the operands. Mathematical
operations such as addition, subtraction, multiplication, etc. can be performed at the bit level for
faster processing.

Name Symbol Description Example

int a = 2, b =
Copies a bit to the evaluated result if it exists in both 3;
Binary AND &
operands (a & b);
//returns 2

int a = 2, b =
Copies a bit to the evaluated result if it exists in any 3;
Binary OR |
of the operand (a | b);
//returns 3

int a = 2, b =
Copies the bit to the evaluated result if it is present 3;
Binary XOR ^
in either of the operands but not both (a ^ b);
//returns 1

int a = 2, b =
Shifts the value to left by the number of bits 3;
Left Shift <<
specified by the right operand. (a << 1);
//returns 4

Mrs. P.D.Titavekar
Object Oriented Programming using C++

Name Symbol Description Example

int a = 2, b =
Shifts the value to right by the number of bits 3;
Right Shift >>
specified by the right operand. (a >> 1);
//returns 1

int b = 3;
One‘s
~ Changes binary digits 1 to 0 and 0 to 1
Complement (~b); //returns
-4

5) Assignment Operators

These operators are used to assign value to a variable. The left side operand of the assignment
operator is a variable and the right side operand of the assignment operator is a value. The value on
the right side must be of the same data type as the variable on the left side otherwise the compiler
will raise an error.

Namemultiply Symbol Description Example

Assignment Assigns the value on the right to the variable on the int a = 2;
Operator = left // a = 2

Add and First adds the current value of the variable on left to int a = 2,
b = 4;
Assignment += the value on the right and then assigns the result to
Operator the variable on the left a+=b; // a
=6

Subtract and First subtracts the value on the right from the int a = 2,
- b = 4;
Assignment current value of the variable on left and then assign
Operator = the result to the variable on the left a-=b; // a
= -2

Multiply and First multiplies the current value of the variable on int a = 2,
b = 4;
Assignment *= left to the value on the right and then assign the
Operator result to the variable on the left a*=b; // a
=8

Divide and First divides the current value of the variable on left int a = 4,
b = 2;
Assignment /= by the value on the right and then assign the result
Operator to the variable on the left a /=b; // a
=2

Mrs. P.D.Titavekar
Object Oriented Programming using C++
6) Ternary or Conditional Operators(?:)

This operator returns the value based on the condition.


Expression1? Expression2: Expression3
The ternary operator ? determines the answer on the basis of the evaluation of Expression1. If it
is true, then Expression2 gets evaluated and is used as the answer for the expression.
If Expression1 is false, then Expression3 gets evaluated and is used as the answer for the
expression.
This operator takes three operands, therefore it is known as a Ternary Operator.

#include <iostream>

using namespace std;

int m=10; //global m

void arithmetic (int n1, int n2);

void incdec(int n1, int n2);

void assign(int n1, int n2);

void relational(int n1, int n2);

void logical();

void scope_resolution();

int main() {

int a, b;

a = 7;

b = 2;

//Arithmatic Operators

arithmetic(a,b);

// increment and decrement operators

a = 10;

b = 100;

incdec(a,b);

Mrs. P.D.Titavekar
Object Oriented Programming using C++
//Assignment operator

a = 2;

b = 7;

assign(a,b);

//Relational Operators

a = 3;

b = 5;

relational(a,b);

//Logical Operators

logical();

scope_resolution();

return 0;

void arithmetic (int n1, int n2)

// printing the sum of a and b

cout <<"a + b = "<< (n1 + n2) << endl;

// printing the difference of a and b

cout <<"a - b = "<< (n1 - n2) << endl;

// printing the product of a and b

cout <<"a * b = "<< (n1 * n2) << endl;

Mrs. P.D.Titavekar
Object Oriented Programming using C++
// printing the division of a by b

cout <<"a / b = "<< (n1 / n2) << endl;

// printing the modulo of a by b

cout <<"a % b = "<< (n1 % n2) << endl;

void incdec(int n1, int n2)

// incrementing a by 1 and storing the result in result_a

int result_a = ++n1;

cout <<"result_a = "<< result_a << endl;

// decrementing b by 1 and storing the result in result_b

int result_b = --n2;

cout <<"result_b = "<< result_b << endl;

void assign(int n1, int n2)

cout <<"a = "<< n1 << endl;

cout <<"b = "<< n2 << endl;

cout <<"\nAfter a += b;"<< endl;

// assigning the sum of a and b to a

n1 += n2; // a = a +b

Mrs. P.D.Titavekar
Object Oriented Programming using C++
cout <<"a = "<< n1 << endl;

void relational(int n1, int n2)

bool result;

result = (n1 == n2); // false

cout <<"3 == 5 is "<< result << endl;

result = (n1 != n2); // true

cout <<"3 != 5 is "<< result << endl;

result = n1 > n2; // false

cout <<"3 > 5 is "<< result << endl;

result = n1 < n2; // true

cout <<"3 < 5 is "<< result << endl;

result = n1 >= n2; // false

cout <<"3 >= 5 is "<< result << endl;

result = n1 <= n2; // true

cout <<"3 <= 5 is "<< result << endl;

void logical()

bool result;

Mrs. P.D.Titavekar
Object Oriented Programming using C++

result = (3 != 5) && (3 < 5); // true

cout <<"(3 != 5) && (3 < 5) is "<< result << endl;

result = (3 == 5) && (3 < 5); // false

cout <<"(3 == 5) && (3 < 5) is "<< result << endl;

result = (3 == 5) && (3 > 5); // false

cout <<"(3 == 5) && (3 > 5) is "<< result << endl;

result = (3 != 5) || (3 < 5); // true

cout <<"(3 != 5) || (3 < 5) is "<< result << endl;

result = (3 != 5) || (3 > 5); // true

cout <<"(3 != 5) || (3 > 5) is "<< result << endl;

result = (3 == 5) || (3 > 5); // false

cout <<"(3 == 5) || (3 > 5) is "<< result << endl;

result = !(5 == 2); // true

cout <<"!(5 == 2) is "<< result << endl;

result = !(5 == 5); // false

cout <<"!(5 == 5) is "<< result << endl;

void scope_resolution()

Mrs. P.D.Titavekar
Object Oriented Programming using C++
{

int m=20; // m redeclared local to scope_resolution

int k=m;

int m=30;// m declared again - local to inner block

cout<<"we are in inner block- "<<endl;

cout<<"k= "<<k<<"\n";

cout<<"m= "<<m<<"\n";

cout<<"::m= "<<::m<<"\n";

cout<<"we are in outer block- "<<endl;

cout<<"m= "<<m<<"\n";

cout<<"::m= "<<::m<<"\n";

Control Structure – Conditional and Looping :-

C++ is a programming language from a high level that is widely used for creating applications and
software. One of the most important concepts in C++ programming is Flow Control, which refers to
the ability to direct the flow of a program based on specific conditions. This allows developers to
control how their programs execute and can help to make them more efficient and effective. In this
article, we will see the different types of flow control available in C++, how they work, and when
they are most appropriate.

There are three types of control structure:-

1. Sequence Structure(Straight Line)


2. Conditional Statement(Selection structure or branching)
3. Looping Statement

Conditional Statements:

Conditional Statements are used in C++ to run a certain piece of program only if a specific condition
is met. There are generally three types of conditional statements in C++: if, if-else, and switch.

if Statement:

Mrs. P.D.Titavekar
Object Oriented Programming using C++
The if statement is the simplest of the three and is used to run a certain piece of code nly if a certain
condition is true. For example:

int x = 5;
if (x == 5) {
std::cout << "x is 5" << std::endl;
}

In this example, the block of code inside the curly braces will only be executed if the condition inside
the parentheses is true.

if-else Statement:

The if-else statement is used when we want to execute some code only if some condition exists. If the
given condition is true then code will be executed otherwise else statement will be used to run other
part of the code.For example:

C++ Code:

1. int x = 5;
2. if (x == 5) {
3. std::cout << "x is 5" << std::endl;
4. } else {
5. std::cout << "x is not 5" << std::endl;
6. }

In this example, if the condition inside the parentheses is true, the first block of code will be executed.
Otherwise, the second block of code will be executed.

switch Statement:

The switch statement is used to execute different blocks of code based on the value of a variable. For
example:

1. switch (variable) {
2. case value1:
3. // code to execute if the variable is equal to value1
4. break;
5. case value2:
6. // code to execute if the variable is equal to value2
7. break;
8. // add more cases as needed
9. default:

Mrs. P.D.Titavekar
Object Oriented Programming using C++

10. // code to execute if the variable does not match any case
11. }

C++ code:

1. int x = 2;
2. switch (x) {
3. case 1:
4. std::cout << "x is 1" << std::endl;
5. break;
6. case 2:
7. std::cout << "x is 2" << std::endl;
8. break;
9. default:
10. std::cout << "x is not 1 or 2" << std::endl;
11. break;
12. }

In this example, the switch statement will execute the block of code associated with the value of x. If
x is 1, the first block of code will be executed. If x is 2, the second block of code will be executed. If x
is any other value, the default block of code will be executed.

Loops:

Loops are used in C++ to execute a block of code multiple times, either until a certain condition is
met or for a specific number of times. There are generally three types of loops in C++: while, do-
while, and for.

While Loop:

The while loop is used to execute when we want to run some code for until some specific condition
matches. For example:

C++ Code:

1. int x = 0;
2. while (x < 5) {
3. std::cout << x << std::endl;
4. x++;
5. }

In this example, the while loop will continue to execute the block of code inside the curly braces as
long as x is less than 5. Each time the loop executes, the value of x will be incremented by 1.

Mrs. P.D.Titavekar
Object Oriented Programming using C++

do-while Loop:

The do-while loop is the same as the while loop, but the condition is checked after the first iteration
of the loop. For example:

C++ Code:

1. int x = 0;
2. do {
3. std::cout << x << std::endl;
4. x++;
5. } while (x < 5);

In this example, the do-while loop will execute the block of code inside the curly brackets, and then it
will check the condition. So it will be executed a minimum of one time.

for Loop:

The for loop allows a program to execute a piece of program a fixed number of times. The syntax for
the for loop is:

Pseudo Code:

1. for (initialization; condition; increment/decrement) {


2. // code to execute repeatedly
3. }

Here is an example that uses the for loop to print the numbers from 1 to 10:

C++ Code:

1. for (int i = 1; i <= 10; i++) {


2. cout << i << " ";
3. }

Mrs. P.D.Titavekar

You might also like