Unit IObjectOrientedProgrammingParadigm
Unit IObjectOrientedProgrammingParadigm
Paradigm can also be termed as method to solve some problem or do some tasks.
Programming paradigm is an approach to solve problem using some programming
language or also we can say it is a method to solve a problem using tools and
techniques
There are some basic concepts that act as the building blocks of OOPs i.e.
Class
Object
Encapsulation
Abstraction
Polymorphism
Inheritance
Dynamic Binding
Message Passing
Characteristics of an Object-Oriented Programming Language
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 behaviour
of the objects in a Class.
Class is a blueprint representing a group of objects which shares some
common properties and behaviours.
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.
Encapsulation
Encapsulation is defined as wrapping up data and information under a single unit.
In Object-Oriented Programming, Encapsulation is defined as binding together the
data and the functions that manipulate them.
Abstraction
Data abstraction is one of the most essential and important features of object-
oriented programming in C++. 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 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.
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.
For example, 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 behaviour in different situations. This is called polymorphism
Polymorphism in C++
Inheritance :
Acquiring the properties from one class to another class is called as
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 or child class.
Super Class: The class whose properties are inherited by a sub-class is
called Base Class or Superclass or Parent 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 runtime. 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.
Features of C++
Object-Oriented Programming
Machine Independent
Simple
High-Level Language
Popular
Case-sensitive
Compiler Based
Dynamic Memory Allocation
Memory Management
Multi-threading
1.Object-Oriented Programming
4. High-Level Language
C++ is a High-Level Language, unlike C which is a Mid-Level Programming
Language. It makes life easier to work in C++ as it is a high-level language it is
closely associated with the human-comprehensible English language.
5. Popular
C++ can be the base language for many other programming languages that
supports the feature of object-oriented programming. Bjarne Stroustrup found
Simula 67, the first object-oriented language ever, lacking simulations, and
decided to develop C++.
6. Case-sensitive
It is clear that C++ is a case-sensitive programming language. For example, cin is
used to take input from the input stream. But if the “Cin” won’t work. Other
languages like HTML and MySQL are not case-sensitive languages.
7. Compiler Based
C++ is a compiler-based language, unlike Python. That is C++ programs used to
be compiled and their executable file is used to run them. C++ is a relatively faster
language than Java and Python .
8. Dynamic Memory Allocation
When the program executes in C++ then the variables are allocated the dynamical
heap space. Inside the functions, the variables are allocated in the stack space.
Many times, We are not aware in advance how much memory is needed to store
particular information in a defined variable and the size of required memory can be
determined at run time.
9. Memory Management
C++ allows us to allocate the memory of a variable or an array in run
time. This is known as Dynamic Memory Allocation .
In other programming languages such as Java and Python, the compiler
automatically manages the memories allocated to variables. But this is
not the case in C++.
In C++, the memory must be de-allocated dynamically allocated memory
manually after it is of no use.
The allocation and deallocation of the memory can be done using the new
and delete operators respectively.
10. Multi-threading
Multithreading is a specialized form of multitasking and multitasking is a
feature that allows your system to execute two or more programs
concurrently. In general, there are two sorts of multitasking: process-
based and thread-based .
Process-based multitasking handles the concurrent execution of
programs. Thread-based multitasking deals with the multiprogramming
of pieces of an equivalent program.
A multithreaded program contains two or more parts that will run
concurrently. Each part of such a program is named a thread, and every
thread defines a separate path of execution.
Starting from C++11, the standard library provides cross-platform
multithreading support via std::thread, making it easier to work with
threads in a portable way.
History of C++
C++ programming language was developed in 1980 by Bjarne
Stroustrup at bell laboratories of AT&T (American Telephone &
Telegraph), located in U.S.A.
Bjarne Stroustrup is known as the founder of C++ language.
It was develop for adding a feature of OOP (Object Oriented
Programming) in C without significantly changing the C component.
C++ programming is "relative" (called a superset) of C, it means any
valid C program is also a valid C++ program.
Releas
Version e Date Major changes
C++98
October
(ISO/IEC The first version
1998
14882:1998)
C++03
February
(ISO/IEC Introduction of value initialization.
2003
14882:2003)
Future
C++23 The next major revision of the C++ standard
Release
C++ Features
Procedure & Object –Oriented programming means the programs
can write by using procedure and object.
It is not a pure Object-Oriented Programming
Machine Independent & Platform dependent
A C++ executable is not platform-independent (compiled
programs on Linux won’t run on Windows), however, they are
machine-independent. Let us understand this feature of C++ with
the help of an example. Suppose you have written a piece of code
that can run on Linux/Windows/Mac OSx which makes the C++
Machine Independent but the executable file of the C++ cannot
run on different operating systems.
Robust or Powerful language , It supports many Built-in functions
& Data types.
General purpose programming language like Application software
as well as System software or any domain can create using C++
programming language.
High-Level Language
Extensible
Case-sensitive
It is clear that C++ is a case-sensitive programming language.
For example, cin is used to take input from the input stream. But
if the “Cin” won’t work
Compiler Based
C++ is a compiler-based language, unlike Python. That is C++
programs used to be compiled and their executable file is used to
run them. C++ is a relatively faster language than Java and
Python.
Dynamic Memory Allocation
Memory is needed to store particular information in a defined
variable and the size of required memory can be determined at
run time.
Statically or Strongly typed language
Before using variable , it should be declared .
It supports concept of Pointer
– C++20: 81
Namespace is used by C+
Namespace features are not
+, which avoid name
Namespac present inside the C.
collisions.
es
C C++
Aspect
Standard IO header
Standard IO header
is stdio.h and
is iostream.h and
uses scanf() and printf() fun
uses cin and cout are used
ctions are used for
Standard for input/output in C++.
input/output in C.
I/O
C
C++ provides new
provides malloc() and calloc(
operator for memory
) functions for dynamic
allocation and delete
memory allocation,
operator for memory de-
and free() for memory de-
Dynamic allocation.
allocation.
Memory
compiler.
Meta-programming using
Generic Meta-programming using
templates (macros are still
Programm macros and _Generic()
supported but discouraged)
ing
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.
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.
All of these streams are defined inside the <iostream> header file which contains
all the standard input and output tools of C++. The two instances cout and cin of
iostream class are used very often for printing outputs and taking inputs
respectively. These two are the most basic methods of taking input and printing
output in C++.
The C++ cout is the instance of the ostream class used to produce output on the
standard output device(screen). The data needed to be displayed on the screen is
inserted in the standard output stream (cout) using the insertion operator or put
to operator(<<).
Syntax
Syntax
cin >> variable;
For Example
Multiline comment
Multiline comments come into use to define multiple lines descriptions.
Further, they are represented as / * * /
For Example
1./* An example to demonstrate multiline comment */
2. /* This is the first C++ program
To find largest of three numbers */
Linking Section:
The linking section contains two parts:
Header Files:
Generally, a program includes various programming elements like built-in
functions, classes, keywords, constants, operators, etc. that are already defined
in the standard C++ library.
In order to use such pre-defined elements in a program, an appropriate header
must be included in the program.
Standard headers are specified in a program through the preprocessor
directive #include the iostream header is used. When the compiler processes the
instruction #include<iostream>, it includes the contents of the stream in the
program.
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. Or Namespace is one of the new features in this language. It allows
the grouping of different entities such as classes, objects, functions and a variety of
C++ tokens, etc., under a single name.
In the below snippets, namespace std contains declarations for cout, cin, endl,
etc. statements.
using namespace std;
Namespaces can be accessed in multiple ways:
o using namespace std;
o using std :: cout;
The C++ Standards Committee has rearranged the entities of the standard library
under a namespace known as std. The entities of a namespace can be accessed in
several ways which are as follows:
By specifying the using directive
using namespace std;
cout<<“Hello World”;
By specifying the full member name
std: :cout<<“Hello World”;
By specifying the using-declaration
using std:: cout;
cout<<“Hello World”;
As soon as the new-style header includes, its contents include in the std namespace.
Thus, all modern C++ compilers support these statements.
#include<iostream>
using namespace std;
But, some old compilers may not support these statements. In this scenario, these
single statements replace the statements.
#include<iostream.h>
Definition Section:
It is used to declare some constants and assign them some value.
In this section, anyone can define your own datatype using primitive data types .
C++ Tokens
Tokens can be defined as the smallest building block of C++ programs that the
compiler understands. It is the smallest unit of a program into which the compiler
divides the code for further processing.
Types of Tokens in C++
1. Identifiers
2. Keywords
3. Constants
4. Strings
5. Punctuators
6. Operators
1. Identifiers
In C++, entities like variables, functions, classes, or structs must be given unique
names within the program so that they can be uniquely identified. The unique names
given to these entities are known as identifiers.
3.Constants
Constants are the tokens in C++ that are used to define variables at the time of
initialization and the assigned value cannot be changed after that.We can define
the constants in C++ in two ways that are using the const, constexpr keyword and
#define preprocessor directive.
Types of Constants in C++
o Using const Keyword
o Using constexpr Keyword
o Using #define Preprocessor
Syntax
const DATATYPE variable_name = value;
For Example 1. const int a=100;
Syntax
constexpr DATATYPE variable_name = value ;
For Example 1. Constexpr int a=100;
4. Strings
In C++, a string is not a built-in data type like ‘int’, ‘char’, or ‘float’. It is a class
available in the STL library which provides the functionality to work with a
sequence of characters, that represents a string of text.
Syntax
string variable_name;
For example : 1. string name= “This is string”;
When we define any variable using the ‘string’ keyword we are actually defining
an object that represents a sequence of characters. We can perform various
methods on the string provided by the string class such as length(), push_backk(),
and pop_back().
5. Punctuators
Punctuators are the token characters having specific meanings within the syntax of
the programming language. These symbols are used in a variety of functions,
including ending the statements, defining control statements, separating items, and
more.
6. Operators
C++ operators are special symbols that are used to perform operations on operands
such as variables, constants, or expressions. A wide range of operators is available
in C++ to perform a specific type of operations which includes arithmetic
operations, comparison operations, logical operations, and more.
For example, (A+B), in which ‘A’ and ‘B’ are operands, and ‘+’ is an arithmetic
operator which is used to add two operands.
1. Unary Operators
Unary operators are used with single operands only. They perform the operations
on a single variable. For example, increment and decrement operators.
Increment operator ( ++ ): It is used to increment the value of an operand by 1.
Decrement operator ( — ): It is used to decrement the value of an operand by 1.
2. Binary Operators
They are used with the two operands and they perform the operations between the
two variables. For example (A<B), less than (<) operator compares A and B,
returns true if A is less than B else returns false.
Comparison Operators: These operators are used to compare two operands, and
they include ‘==’, ‘!=’, ‘<‘, ‘>’, ‘<=’, and ‘>=’.
3. Ternary Operator
The ternary operator is the only operator that takes three operands. It is also known
as a conditional operator that is used for conditional expressions.
Synatx
1. Integer
2. Character
3. Boolean
4. Floating Point
5. Double Floating Point
6. Valueless or Void
7. Wide Character
int Integer 2 or 4
float Floating-point 4
char Character 1
bool Boolean 1
void Empty 0
1.) Integer
Integer data types represent whole numbers without a fractional or decimal
part. They can be signed (positive, negative, or zero) or unsigned (only
positive or zero).
Example
int signedInt = -42;unsigned int unsignedInt = 123;
This code declares two integer variables, one signed ("signedInt") with a value
of -42 and the other unsigned ("unsignedInt") with a value of 123.
2.) Character
Character data types represent individual characters from a character set, like
ASCII or Unicode. In C++, `char` is commonly used to represent characters.
Example
char myChar = 'A';
The character variable "myChar" with the value "A" is declared using this
code.
3.) Boolean
Boolean data types represent binary values, typically used for true (1) or
false (0) conditions. In C++, `bool` is used for Boolean data.
Example
bool isTrue = true;
bool isFalse = false;
The two boolean variables "isTrue" and "isFalse" are declared in this code
with the values true and false, respectively.
Example
float myFloat = 3.14159f;
The floating-point variable "myFloat" is declared in this code with the value
3.14159.
Example
double myDouble = 3.141592653589793;
Example
void myFunction()
{ // This function does not return a value
}
void* genericPointer;
This code declares a generic void pointer named "genericPointer" as well as
the void function "myFunction," which has no return value.
Example
wchar_t myWideChar = L'A'; // Assigning the wide character 'A'
Using the wide-character literal "L," this code declares the wide-character
variable "myWideChar" with the value "A."
1. Function
A function is the simplest form of user-defined data type. It includes a return
type, a function name and input parameters.
Syntax
return_type function_name(input_param1, input_param2)
{
<function_body>
}
Example 1
#include <iostream>
using namespace std;
string func(int n){
//returns if n is odd or even
if(n%2) return "Given number is Odd !";
else return "Given number is Even !";
}
int main(){
int a;
//enter a number
cin>>a;
cout<<func(a);
//a simple function to check if
//number is odd or even
return 0;
}
Output
Given number is Even !
Syntax
data_type array_name[array_size];
Example 1
#include <iostream>
using namespace std;
int main(){
int arr[5]={1,2,3,2,1};
//define an integer array of size 5
for(auto it:arr)
cout<<it<<" ";
//print the elements of array
return 0;
}
Output
12321
3. Pointer
A pointer is a reference to an element defined previously. The value of the
pointer returns the address location of the element which is associated with
it.
Syntax
data_type * pointer_name=& variable_name;
Example 1
#include <iostream>
using namespace std;
int main() {
int a=20;
//declare variable a
int *p= &a;
//assign pointer to a
cout<<"Address of variable a: "<<p<<endl;
cout<<"Value of variable a: "<<*p<<endl;
return 0;
}
Output
Address of variable a: 0x7ffc49a8637c
Value of variable a: 20
4. Reference
A reference variable is used to create a copy of a variable with the same
reference. Hence, changes made to the reference variable also reflect on the
original variable.
Syntax
data_type & reference_name= variable_name;
Example
#include <iostream>
using namespace std;
int main(){
int c=11;
int& refer=c;
cout<<"Initially value of integer is: "<<c<<endl;
refer=121;
cout<<"After changing value using refer variable :"<<c<<endl;
return 0;
}
Output
Initially value of integer is: 11
After changing value using refer variable :121
2. On Reference
int originalVar = 100;
int&
refVar = originalVar; // Creating a reference to 'originalVar'
refVar = 200; // Modifying 'originalVar' through 'refVar'
// Both 'originalVar' and 'refVar' now have the value 200
1. Class
A class is a defined in Object Oriented Programming as a custom data type
which is used to construct an object. It is the framework of an object, and it
can include constructors, methods and OOP concepts like Polymorphism,
Inheritance, etc.
Syntax
class Class_name
{
<class body>
class_name(parameters)
{
<constructor body>
}
return_type method_name(paremeters)
{
<method body>
}
}
Example
#include <iostream>
using namespace std;
class TP
{
public:
string tp;
void print()
{
cout<<tp<<endl;
}
};
int main()
{
TP object;
object.tp="I Love C++ !!!";
object.print();
return 0;
}
Output
I Love C++!!!
2. Structure (struct)
In structure data type, the user can introduce multiple primitive data types
inside the struct body.
Syntax
struct struct_name
{
data_type1 var_name1;
data_type2 var_name2;
}
Example 1.
#include <iostream>
using namespace std;
struct TP{
string tp;
int grade;
};
int main(){
TP object;
object.tp="I Love C++ !!!";
object.grade=10;
cout<<object.tp<<endl;
cout<<"How much would you rate it?"<<" : "<< object.grade;
return 0;
}
Output
I Love C++!!!
How much would you rate it? : 10
3. Union
Union is similar to a structure. In this, the memory location of all variables
is same, and all variables share the same reference. Hence, a change in one
value leads to all other values getting changed.
Syntax
union union_name
{
data_type var_name1;
data_type var_name2;
};
Example 1
#include <iostream>
using namespace std;
union TP{
int tp1,tp2;
};
int main(){
union TP t;
t.tp1=2;
cout<<"Value of tp1 initially: "<<t.tp1<<endl;
t.tp2=4;
cout<<"When we change tp2, value of tp1 is : "<<t.tp1<<endl;
return 0;
}
Output
Value of tp1 initially: 2
When we change tp2, value of tp1 is : 4
4. Enumeration (Enum)
Enumeration or simply enum is a user-defined data type that is used to give
name to integer constants in a program. This increases the user-readability
of a program.
Syntax
enum enum_name{
var_name1 , var_name2,
}
Example
#include <iostream>
using namespace std;
enum TP{ C, Java, Python, Ruby, Kotlin, Javascript, TypeScript,
Others};
int main(){
enum TP course;
cout<<"Which course do you love the most?"<<endl;
course=Kotlin;
cout<<"I love the "<<course+1<<"th course !!!";
return 0;
}
Output
Which course do you love the most?
I love the 5th course !!!
6.typedef Declarations
You can create a new name for an existing type using typedef. Following is
the simple syntax to define a new type using typedef −
Synatx
typedef type newname;
For example, the following tells the compiler that feet is another name for int −
typedef int feet;
1. Signed
2. Unsigned
3. Short
4. Long
1. Signed
The signed modifier is used to indicate that a variable can hold both positive
and negative values. However, most built-in integer types (like int) are
signed by default in C++. So, you rarely need to explicitly use the signed
keyword.
Example
int signedVariable = -10; // "int" is signed by default
This code in C++ Online Editor declares the signed integer variable
"signedVariable" with the value -10. It's vital to know that "int" is signed by
default in C++.
2. Unsigned
The unsigned modifier is used to indicate that a variable can only hold non-
negative values (i.e., zero or positive values). It is often used when you
know that a variable should not have negative values, and you want to save
memory by avoiding the storage of negative numbers.
Example
unsigned int unsignedVariable = 20; // unsigned integer
The unsigned integer variable "unsignedVariable" is declared in this code
with the value 20 and the restriction that it can only store non-negative
integer values.
3. Short
The short modifier is used to indicate that a variable should be stored using
fewer bits than the default data type. This is often used to save memory
when you know that a variable's value will fit within a smaller range.
Example
short shortVariable = 32767; // short integer
The maximum value that can be declared for the short integer variable
"shortVariable" according to this code is 32767.
4. Long
The long modifier is used to indicate that a variable should be stored using
more bits than the default data type. This is used when you need to store
larger values that cannot fit within the range of a standard data type.
Example
long long longVariable = 1234567890; // long integer
With the value 1234567890, the long integer variable "longVariable" is
declared in this code.
Variables
A variable is a named storage location of data in memory. Data types of
variables can be int, float, boolean, char, and double.
You can assign the value to the variable f after a declaration like this:
f=15.7;
The variables of the same type can be declared in a single line like this:
Syntax
type var1, var2, ... varn;
Example
int a, b, c;
1. Name can consist of alphabets (both uppercase and lowercase), digits, and
underscore(_).
2. The first character must be either an alphabet or an underscore.
3. Variable names are case sensitive, i.e., num and Numare two different
variable names.
4. No white spaces and special characters like !, *, must be there in the variable
names.
5. A keyword cannot be your variable name.
6. The type of the declared variable cannot be changed after declaration.
Types of Variables in C++
1. Local Variable
2. Instance Variable
3. Static Variable
4. Automatic Variable
5. External Variable
1.Local Variable
Local variables are declared and initialized at the start of a function or block and
allocated memory inside that execution scope. The statements only inside that
function can access that local variable. Such variables get destroyed when the
control exits from the function.
Example
#include <iostream>
void local();
int main() {
int a = 22, b = 44;
local();
std::cout << "Values in the main() function a = " << a << " and b = " << b <<
std::endl;
return 0;
}
void local() {
int a = 50, b = 80;
std::cout << "Values in the local() function a = " << a << " and b = " << b <<
std::endl;
}
In the above code, there are two functions, main() and local(). The variables a
and b are local variables declared inside each function with different values. The
value of a and b is restricted to the function in which it is declared.
Output
Values in the local() function a = 50 and b = 80
Values in the main() function a = 22 and b = 44
2. Instance Variable
Instance variables are non-static variables declared in a class outside
constructors, methods, and other blocks. Their memory is allocated when the
object of that class in which they are declared is created and destroyed when the
object is destroyed. Their initialization is not compulsory while declaring, by
default, they will have garbage values. Every object of the class gets a separate
copy of its instance variables. The scope of the instance variable is controlled by
the access specifiers.
Example 1.
#include <iostream>
using namespace std;
class Student {
public:
// instance variables
int roll_no;
string name;
float marks;
};
int main() {
Student obj; //object of Student class
return 0;
}
You will understand instance variables in a better way while learning Object
Oriented Programming (OOPs) Concepts in C++
3.Static Variable
These are similar to instance variables but common to every object of the class.
There is only a single copy of static variables per class and static variables are
declared with a “static keyword”. Their memory gets allocated at the start of
the program and gets destroyed at the termination of the program. Their
initialization is compulsory and it is done outside the class. by default int
variable will have a 0 value, boolean will have a false value.
Example 1.
#include <iostream>
using namespace std;
class Student {
public:
// static variable
static float passing_marks;
};
4.Automatic Variable
All the local variables are automatic variables by default. They are also known
as auto variables.
Example 1.
#include <iostream>
int main() {
int x = 10; // local variable (also automatic)
auto y = 20; // automatic variable
return 0;
}
5.External Variable
External or global variables are declared using the extern keyword. You can
declare an external variable any number of times but, the value can be assigned
only once. Their default value is 0 or null.
Example
#include <iostream>
extern int a; // Declaration of the global variable 'a'
int main() {
std::cout << a << std::endl; // Display the value of the global variable 'a'
return 0;
}
int a; // Definition of the global variable 'a'
Constant expressions
Integral expressions
Float expressions
Pointer expressions
Relational expressions
Logical expressions
Bitwise expressions
Special assignment expressions
Constant expressions: Constant Expressions consists of only constant values.
A constant value is one that doesn’t change.
Examples:
5, 10 + 5 / 6.0, 'x’
Integral expressions: Integral Expressions are those which produce integer
results after implementing all the automatic and explicit type conversions.
Examples:
x, x * y, x + int( 5.0)
where x and y are integer variables.
Floating expressions: Float Expressions are which produce floating point
results after implementing all the automatic and explicit type conversions.
Examples:
x + y, 10.75
where x and y are floating point variables.
Relational expressions: Relational Expressions yield results of type bool
which takes a value true or false. When arithmetic expressions are used on
either side of a relational operator, they will be evaluated first and then the
results compared. Relational expressions are also known as Boolean
expressions.
Examples:
x <= y, x + y > 2
Logical expressions: Logical Expressions combine two or more relational
expressions and produces bool type results.
Examples:
x > y && x == 10, x == 10 || y == 5
Pointer expressions: Pointer Expressions produce address values.
Examples:
&x, ptr, ptr++
where x is a variable and ptr is a pointer.
Bitwise expressions: Bitwise Expressions are used to manipulate data at bit
level. They are basically used for testing or shifting bits.
Examples:
x << 3
shifts three bit position to left
y >> 1
shifts one bit position to right.
Shift operators are often used for multiplication and division by powers of two.
Special assignment Expression in C++
Conditional Statements
In C++, conditional statements are control structures that let code make decisions.
These statements are also known as decision-making statements. They are of the
type if statement, if-else, if else-if ladder, switch, etc. These statements determine
the flow of the program execution.
Types of Conditional Statements
if … else statements
if-else is the first kind of control statement in C++. In this, the operations are
performed according to some specified condition. The statements inside the body of
the if block get executed if and only if the given condition is true.
Variants of if-else statements in C++
We have four variants of if-else statements in C++. They are:
1. if statement in C++
2. if-else statement in C++
3. if else-if ladder in C++
4. nested if statement in C++
1. if statement in C++
if statements in C++ are one of the most simple statements for deciding in a
program. When you want to print any code only upon the satisfaction of a given
condition, go with the simple if statement.
Syntax
if(testcondition)
{
// Statements to execute if condition is true
}
Example
// C++ program to understand if statement
#include <iostream>
using namespace std;
int main()
{
int i = 11;
if (i > 15)
{
cout << "11 is greater than 15";
}
cout << "I am Not in if";
return 0;
}
This C++ code in C++ Compiler initializes the integer I to 11 and then checks to
see if it is greater than 15 using an if statement. It outputs "I am Not in if" to the
console because 11 is not greater than 15.
Output
I am Not in if
2. if-else statement
It is an extension of the if statement. Here, there is an if block and
an else block. When one wants to print output for both cases
- true and false, use the if-else statement.
Syntax
if (testcondition)
{
// Executes this block if condition is true
}
else
{
// Executes this block if condition is false
}
if (testcondition1)
statement;
else if (testcondition2)
statement;
else
statement;
#include <iostream>
int main()
int A = 20;
if (A == 10)
else if (A == 15)
else if (A == 20)
else
return 0;
}
Output
A is 20
4.nested if statement
We can include an if-else block in the body of another if-else block. This becomes
a nested if-else statement.
Syntax
if(test condition1)
{ //if condition1 becomes true
if(test condition1.1)
{
//code executes if both condition1 and condition 1.1 becomes true
}
else
{
//code executes if condition1 is true but condition 1.1 is false
}
}
else
{
//code executes if condition1 becomes false
}
return 0;
}
Output
10 is even
#include <iostream>
using namespace std;
int main ()
{
int num;
cout<<"Enter a number:";
cin>>num;
switch (num)
{
case 20:
cout<<"It is 20";
break;
case 30:
cout<<"It is 30";
break;
case 40:
cout<<"It is 40";
break;
default:
cout<<"Not 20, 30 or 40";
}
return 0;
}
LOOP
In C++ programming language, there are three loop statements, these looping
statements and loop control statements help to execute a block of code
iteratively in a loop and control the loop execution respectively.
1. The while statement (loop).
2. The do…while statement (loop).
3. The for statement (loop).
Statement(s) inside the do block is executed and the while condition is checked. If the
condition is true, statement(s) inside the do block is executed.The condition is checked
again. If it evaluates to true,the statement(s) inside the while loop is executed. This
cycle goes on. If at all, the condition evaluates to false,program control comes out of
the loop, meaning do-while loop execution is completed. And the program continues
with the execution of statements after the do-while loop if any.
Example 1: Do-While Loop
In this example, we shall write a do-while loop that prints the string Hello five
times.
#include <iostream>
using namespace std;
int main() {
int i=0;
do {
cout << "Hello" << endl;
} while (++i < 5);
}
3. for-Loop
For Loop can execute a block of statements in a loop based on a condition. It
is similar to a while loop in working, but the only difference is that for loop
has provision for initialization and update in its syntax.
1.Break
As soon as a break statement is encountered inside a loop, the loop terminates
immediately, and control is transferred to the next statement outside the loop.
Syntax
//loop or switch case
break;
Example 1.
#include <iostream>
using namespace std;
int main()
{
for (int i = 1; i <= 10; i++)
{
if (i == 5)
{
break;
}
cout << i << endl;
}
return 0;
}
Output
1
2
3
4
2.continue Statement
In computer programming, the continue statement is used to skip the current
iteration of the loop and the control of the program goes to the next iteration.
#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
3.goto Statement
In C++ programming, the goto statement is used for altering the normal
sequence of program execution by transferring control to some other part of the
program.
# include <iostream>
using namespace std;
int main()
{
float num, average, sum = 0.0;
int i, n;
cout << "Maximum number of inputs: ";
cin >> n;
for(i = 1; i <= n; ++i)
{
cout << "Enter n" << i << ": ";
cin >> num;
if(num < 0.0)
{
// Control of the program move to jump:
goto jump;
}
sum += num;
}
jump:
average = sum / (i - 1);
cout << "\nAverage = " << average;
return 0;
}
Output
Maximum number of inputs: 10
Enter n1: 2.3
Enter n2: 5.6
Enter n3: -5.6
Average = 3.95