0% found this document useful (0 votes)
28 views51 pages

Unit IObjectOrientedProgrammingParadigm

The document discusses programming paradigms, focusing on procedural and object-oriented programming, particularly in C++. It outlines key concepts of object-oriented programming such as classes, objects, encapsulation, abstraction, polymorphism, and inheritance, as well as features and history of C++. Additionally, it compares C and C++, highlighting their differences in support for object-oriented programming and other functionalities.

Uploaded by

nikhillakmaje420
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views51 pages

Unit IObjectOrientedProgrammingParadigm

The document discusses programming paradigms, focusing on procedural and object-oriented programming, particularly in C++. It outlines key concepts of object-oriented programming such as classes, objects, encapsulation, abstraction, polymorphism, and inheritance, as well as features and history of C++. Additionally, it compares C and C++, highlighting their differences in support for object-oriented programming and other functionalities.

Uploaded by

nikhillakmaje420
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 51

Programming Paradigms

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

 Procedural programming paradigm –


This paradigm emphasizes on procedure in terms of under lying machine model.
There is no difference in between procedural and imperative approach. It has the
ability to reuse the code and it was boon at that time when it was in use because of
its reusability.

 Object oriented programming –


The program is written as a collection of classes and object which are meant for
communication. The smallest and basic entity is object, and all kind of
computation is performed on the objects only.

Basic Concept of Object Oriented Programming in C++

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

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

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.

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

C++ is an Object-Oriented Programming Language, unlike C which is a procedural


programming language. This is the most important feature of C++. It can
create/destroy objects while programming. Also, It can create blueprints with
which objects can be created..
Concepts of Object-oriented programming Language:
 Class
 Objects
 Encapsulation
 Polymorphism
 Inheritance
 Abstraction
2. Machine Independent
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 OS which makes the
C++ Machine Independent but the executable file of the C++ cannot run on
different operating systems.
3. Simple
It is a simple language in the sense that programs can be broken down into logical
units and parts, has rich library support and has a variety of data types.

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.

C++ was initially developed by Bjarne Stroutrup as an extension of


C language to include OOPs concepts. It was first introduces as “C
with Classes” in 1979 at Bell Labs. It was named C++ in 1982. The
language later standardized by the International Organization for
Standardization (ISO).
 The first official standard C++98 released in 1998.
 This was followed by C++03 in 2003 which was a minor update
that addressed defects and clarified ambiguities in the C++98
standard.
 The major update came with C++ 11 in 2011 which introduced a
lot of features like lambda expressions, smart pointers, etc. After
this, an update starts being released once in 3 years.
 C++14 (2014) and C++17 (2017), brought incremental
improvements, refining C++11 features and adding new utilities
like filesystem support.
 The latest major standards C++20 (2020) and C++23 (2024)
continue to modernize the language with concepts, modules, and
enhanced concurrency.

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)

Introduction of Lambda Expressions,


Delegating Constructors, Uniform
August
C++11 Initialization Syntax, nullptr, Automatic Type
2011
Deduction and decltype, Rvalue References
etc.
Releas
Version e Date Major changes

Introduction of polymorphic lambdas, digit


August separators, generalized lambda capture,
C++14
2014 variable templates, binary integer literals,
quoted strings etc.

Introduction of fold expressions,


Decemb hexadecimal floating point literals, a u8
C++17
er 2017 character literal, selection statements with
initializer, inline variables etc.

This update extends C++ with the facilities


March
to inspect program entities such as
C++20
2020 variables, enumerations, classes and their
members, lambdas and their captures, etc.

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

Difference between C and C++


C C++
Aspect

C was developed by Dennis


Ritchie between the year C++ was developed by
1969 and 1973 at AT&T Bell Bjarne Stroustrup in 1979.
Labs.
Developer

C does not support


C++
polymorphism,
supports polymorphism, en
encapsulation, and
capsulation,
inheritance which means
and inheritance because it
that C does not support
is an object-oriented
object-oriented
OOPs programming language.
programming.
Support

C is (mostly) a subset of C+ C++ is (mostly) a superset


Subset/ +. of C.
Superset

Keywords Number of keywords in C: Number of keywords in C+


– C90: 32 +:
– C99: 37 – C++98: 63
– C11: 44 – C++11: 73
– C23: 59 – C++17: 73
C C++
Aspect

– C++20: 81

C++ is known as hybrid


For the development of language because C++
code, C supports procedural supports both procedural
Programm programming. and object-oriented
ing programming paradigms.
Paradigm

Data and functions are


Data and functions are
separated in C because it is
encapsulated together in
a procedural programming
Encapsulat form of an object in C++.
language.
ion

Data is hidden by the


Encapsulation to ensure
C does not support data
that data structures and
hiding.
operators are used as
Data intended.
Hiding

C is a function driven C++ is an object driven


language because C is a language because it is an
procedural programming object-oriented
Focus of language. programming.
Language

Function and operator Function and operator


overloading is not supported overloading is supported by
Overloadin in C. C++.
g

Function Functions in C are not Functions can be used


Inside defined inside structures. inside a structure in C++.
Structures

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

Reference variables are not Reference variables are


Reference supported by C. supported by C++.
s

Virtual and friend


Virtual and friend functions
functions are supported by
Virtual are not supported by C.
C++.
Functions

C does not support


Inheritanc C++ supports inheritance.
inheritance.
e

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

Direct support for exception


Exception handling is
handling is not supported by
Exception supported by C++.
C.
Handling

C structures don’t have C ++ structures have


Access access modifiers. access modifiers.
Modifiers

Type There is no strict type Strict type checking in done


Checking checking in C programming in C++. So many programs
language. that run well in C compiler
will result in many warnings
and errors under C++
C C++
Aspect

compiler.

Type punning with unions is


Type Type punning with unions is undefined behavior (except
Punning allows (C99 and later) in very specific
with circumstances)
Unions

Named initializers must


Named initializers may
match the data layout of
Named appear out of order
the struct
Initializers

File extension is “.cpp” or


File extension is “.c”
“.c++” or “.cc” or “.cxx”
Extension

Meta-programming using
Generic Meta-programming using
templates (macros are still
Programm macros and _Generic()
supported but discouraged)
ing

Basic Input / 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.

 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++.

Standard Output Stream – cout

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

cout << value/variable;

For example : 1. cout<<”Hello C++ world “; // prints string on the monitor

2. cout<< a; // prints variable value on the screen

3. cout<<” The value of a & b value is “<<a<<b; // It prints the


string as well as the value of a & b.

Standard Input Stream – cin


The C++ cin statement is the instance of the class istream and is used to read
input from the standard input device (keyboard). The extraction operator or get
from operator (>>) is used along with the object cin for extracting the data from
the input stream and store it in some variable in the program.

Syntax
cin >> variable;

For example 1. cin>>a>>b; // Read the value of a & b from keyword

2. cin>>a; // Read the value of a from keyword

Structure of C++ Program

The structure of the program written in C++ language is as follows:


Documentation Section :
 Whatever written in the documentation section is the comment and is not
compiled by the compiler.
 Documentation Section is optional since the program can execute without them.

C++ struct is known for supporting two comment styles-

 Single line comment


The use of single comments is to define line-by-line descriptions. Double
slash // comes into use for representing single-line comments. Consider the
statement below to understand its concept:

For Example

1. / / An example to show single line comment It can also be written as:


2. / / An example to demonstrate
3. / / single line comment

 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 .

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 occurs.

// 1. This is first program to display name using namespace


#include <iostream>
// using directive
using namespace std;
int main( )
{
string first_name ;
cout << "Enter your first name: ";
cin >> first_name;
cout << "Hello " << first_name << "!" << endl;
cout << "Welcome!";
return 0;
}
**********OUTPUT*********
Enter your first name: Rohan
Hello Rohan!
Welcome!

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++

There are six types of token , they are

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.

1. An identifier can only begin with a letter or an underscore(_).


2. An identifier can consist of letters (A-Z or a-z), digits (0-9), and underscores
(_). White spaces and Special characters can not be used as the name of an
identifier.
3. Keywords cannot be used as an identifier because they are reserved words to do
specific tasks. For example, string, int, class, struct, etc.
4. Identifier must be unique in its namespace.
5. As C++ is a case-sensitive language so identifiers such as ‘first_name’ and
‘First_name’ are different entities.
2. Keywords
Keywords in C++ are the tokens that are the reserved words in
programming languages that have their specific meaning and functionalities within
a program. Keywords cannot be used as an identifier to name any variables.
For example, a variable or function cannot be named as ‘int’ because it is reserved
for declaring integer data type.There are 95 keywords reserved in C++.

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

Using const Keyword


Defining constants using const keyword is one of the older methods that C++
inherited

Syntax
const DATATYPE variable_name = value;
For Example 1. const int a=100;

We have to initialize the constant variable at the time of declaration as we cannot


modify the value of it.
Using constexpr Keyword
The constexpr keyword is similar to const keyword and is also used to declare
constants .

Syntax
constexpr DATATYPE variable_name = value ;
For Example 1. Constexpr int a=100;

Using #define Preprocessor


We can also define constants using the #define. Constants created using the
#define preprocessor are called "macro constants".
Syntax
#define MACRO_NAME replacement_value
#define side = 5

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.

Below are the most common punctuators used in C++ programming:

Semicolon (;): It is used to terminate the statement.

Square brackets []: They are used to store array elements.

Curly Braces {}: They are used to define blocks of code.

Double-quote (“): It is used to enclose string literals.

Single-quote (‘): It is used to enclose character literals.

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.

There can be three types of operators:

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.

Arithmetic Operators: These operators perform basic arithmetic operations on


operands. They include ‘+’, ‘-‘, ‘*’, ‘/’, and ‘%’

Comparison Operators: These operators are used to compare two operands, and
they include ‘==’, ‘!=’, ‘<‘, ‘>’, ‘<=’, and ‘>=’.

Logical Operators: These operators perform logical operations on boolean values.


They include ‘&&’, ‘||’, and ‘!‘.

Assignment Operators: These operators are used to assign values to variables,


and they include ‘variables‘, ‘-=‘, ‘*=‘, ‘/=‘, and ‘%=’.
Bitwise Operators: These operators perform bitwise operations on integers. 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

Expression1 ? Expression2 : Expression3;

If Expression1 became true then Expression2 will be executed otherwise


Expression3 will be executed.

Data Types in C++: An Overview


A Data Type is a classification of specific types of data by a certain value or
certain types of mathematical or logical operations
Primitive Data type
Primitive data types in C++ are some inbuilt data types that can be used by the
user directly for the declaration of the variable. Some primitive data types in C++
are:

1. Integer
2. Character
3. Boolean
4. Floating Point
5. Double Floating Point
6. Valueless or Void
7. Wide Character

Data Type Meaning Size (in Bytes)

int Integer 2 or 4

float Floating-point 4

double Double Floating-point 8

char Character 1

wchar_t Wide Character 2

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.

4.) Floating Point


Floating-point data types represent numbers with a fractional part. In C++, `
float` is a single-precision floating-point type.

Example
float myFloat = 3.14159f;

The floating-point variable "myFloat" is declared in this code with the value
3.14159.

5.) Double Floating Point


Double-precision floating-point data types are used to represent numbers
with a larger range and higher precision compared to 'float'. In C++, 'double'
is commonly used.

Example
double myDouble = 3.141592653589793;

This code declares a high-precision double-precision floating-point variable


named "myDouble" with the value of (pi).

6.) Valueless or Void


The void data type in C++ is used to indicate that a function does not return
any value or to declare generic pointers that do not point to a specific data
type.

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.

7.) Wide Character


Wide character data types, like 'wchar_t', are used to represent characters
from extended character sets, such as Unicode characters that require more
storage than a standard `char`.

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."

Derived Data Types


Data types which are obtained from pre-defined data types in C++ are
known as Derived Data Types. These can be classified into four categories, namely

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 !

// 2. Function that adds two integers and returns the result


int add(int a, int b) {
return a + b;
} // Function that concatenates two strings and returns the result
std::string concatenate(std::string str1, std::string str2) {
return str1 + str2;
} int main() {
int sum = add(5, 3);
std::string result = concatenate("Hello, ", "World!");
return 0;
}
2. Array
An array is a series of elements of same data type. Elements of an array are
stored in contiguous memory locations in the storage.

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

// 2. Declaration and initialization of an integer array


int numbers[5] = {1, 2, 3, 4, 5}; // Accessing elements of the array
int firstNumber = numbers[0]; // Accessing the first element (index 0)
int thirdNumber = numbers[2]; // Accessing the third element (index 2)

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

//2. Declaration and initialization of a pointer


int* ptr; // Pointer to an integer
int num = 42;
ptr = &num; // Assigning the address of 'num' to 'ptr' // Accessing the
value through the pointer
int value = *ptr; // Dereferencing the pointer to get the value (value =
42)

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

This code in C++ Online Compiler generates a reference variable "refVar"


that references to the integer variable "originalVar" and allows adjustments
through it, so updating "refVar" to 200 updates "originalVar" to 200 as well,
resulting in both variables having the value 200.

User-Defined Data Types


Data types which are defined by the user intuitively without using any pre-
defined data types are known as User-Defined Data Types. They are
1. Class
2. Structure
3. Union
4. Enumeration
5. Typedef defined Datatype

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;

Now, the following declaration is perfectly legal and creates an integer


variable called distance –

Datatype Modifiers in C++


In C++, data type modifiers are used to modify the behavior and storage
characteristics of basic data types. In C++, there are four modifiers. int,
double, and char are the data types that can be modified using these
modifiers. They are as follows:

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.

Some basic data types of C++ programming language


Data Type Size Range
int or signed int 4 Bytes -2,147,483,648 to 2,147,483,647
unsigned int 4 Bytes 0 to 4,294,967,295
short int 2 bytes -32,768 to 32,767
long int 4 bytes -2,147,483,648 to 2,147,483,647
unsigned short int 2 bytes 0 to 65,535
unsigned long int 8 Bytes 0 to 4,294,967,295
long long int 8 Bytes -(2^63) to (2^63)-1
unsigned long long int 8 Bytes 0 to 18,446,744,073,709,551,615
signed char 1 Bytes -128 to 127
unsigned char 1 Bytes 0 to 255
wchar_t 2 or 4 Bytes 1 wide character
float 4 Bytes
double 8 Bytes
long double 12 Bytes

Variables
A variable is a named storage location of data in memory. Data types of
variables can be int, float, boolean, char, and double.

How to Declare a Variable?


Syntax
type variableName;
Example
float f;
Here we can see that a float type variable f is created. This means that a
memory location of name f which can store floating value is being created in
the memory.

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;

You can also declare a variable by assigning values to it in the following


way:
int a=10,b=20;//declaring 2 variable of integer type
float f=20.8;
char c='A';

Initialization of Variables in C++


This can be done in two ways:
1.Initialization at the time of declaration
int a=10;
float f=20.8;
char c='A';
2.Initialization after the declaration
int a, b, c;
a = 55;
b = 10;
c = a - b;
If we don't assign the value at the time of declaration, the garbage value is
assigned by the compiler
What are the rules for naming a variable?

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;
};

float Student::passing_marks = 21;


int main() {
Student obj; //object of Student class
return 0;
}

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'

Expression: An expression is a combination of operators, constants and variables.


An expression may consist of one or more operands, and zero or more operators to
produce a value.
Types of Expressions:

 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++

 Special assignments in C++ can be classified depending on the value of


the variable that is assigned
 Chained assignment expressions- in chained assignment expression
assigns the same values more than once by using only one statement

For Example : #include <iostream>


using namespace std;
int main()
{
int x; // variable declaration
int y; // variable declaration
x = y = 80; // chained assignment
cout << "Values of 'x' and 'y' are: " << x << "," << y << endl;
return 0;
}
Note: An expression may also use combinations of the above expressions. Such
expressions are known as compound expressions.

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
}

 In the if statement, the test condition is in ().


 If the test condition becomes true, the body of the if block executes else no
statement of the if block gets printed.

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
}

// C++ program to understand the if-else statement


#include <iostream>
using namespace std;
int main()
{
int A = 16;
if (A < 15)
cout << "A is smaller than 15";
else
cout << "A is greater than 15";
return 0;
}
This C++ program initializes the integer variable A to 16 and then checks to see if it
is less than 15 using the if-else statement. It outputs "A is greater than 15" to the
console because it isn't.

3.if else-if ladder

It is an extension of the if-else statement. If we want to check multiple conditions if


the first if condition becomes false, use the if else-if ladder. If all the if conditions
become false the else block gets executed.
Syntax

if (testcondition1)

statement;

else if (testcondition2)

statement;

else
statement;

// C++ program to understand if-else-if ladder

#include <iostream>

using namespace std;

int main()

int A = 20;

if (A == 10)

cout << "A is 10";

else if (A == 15)

cout << "A is 15";

else if (A == 20)

cout << "A is 20";

else

cout << "A is not present";

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
}

// C++ program to understand nested-if statement


#include <iostream>
using namespace std;
int main() {
int a = 10;
int b = 5;
if (a > b) {
// Control goes to the nested if
if (a % 2 == 0) {
cout << a << " is even";
}
else {
cout << a << " is odd";
}
}
else {
cout << a << " is not greater than " << b;
}

return 0;
}
Output
10 is even

Switch Statement in C++


we saw the if else-if ladder to check multiple conditions if one or the other fails.
The switch statement serves as an alternative to the if else-if ladder. It checks
multiple cases for different values of a single variable.

Switch Statement Syntax


switch(expression)
{
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
......
default:
code to be executed if all cases are not matched;
}
It starts with the keyword, switch followed by a set of () containing an expression.
The expression is evaluated once and compared with the values of each case.
If any case matches, the corresponding case statement executes.
After the execution of the matching case statement, the control comes out of the
switch statement due to the break keyword.
If no case matches, the default statement, if present, gets executed.

Rules for the switch statement in C++


The data type of the switch expression must be of an integer or character.
All the case labels must be followed by a colon “:”.
The case value must be an integer or character constant.
The break keyword is optional, but it can decrease the execution time of your
program. It will stop the unnecessary execution of other cases after a match isfound.

#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).

1.The while STATEMENT.


At the start of the while loop execution, the condition is checked. If the
condition is true, statement(s) inside while the 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,execution comes out of the while loop, meaning the while
loop is completed. And theprogram continues with the execution of
statements after the while loop if any.

The while statement or loop Syntax:


while (condition) {
// body of the loop
}
Here,
A while loop evaluates the condition
If the condition evaluates to true, the code inside the while loop is executed.
The condition is evaluated again.
This process continues until the condition is false.
When the condition evaluates to false, the loop terminates.
Example1: In this example, we shall write a while loop that prints numbers from 1
to 5.
#include <iostream>
using namespace std;
int main()
{
int n = 5;
int i = 1;
while (i<=n)
{
cout << i << "\n";
i++;
}
}
2.Do-While Loop
Do-While Loop can execute a block of statements in a loop based on a
condition .
Following is the syntax of do while loop in C++.
do {
// statement(s)
} while (condition);

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.

The for-loop Syntax is:


for (initial value; condition; increment /decrement)
{
Block_of_statements ;
}
At the start of for loop execution, initialization statement is executed and then the
condition is checked. If the condition is true, statement(s) inside for block are
executed. And the update statement is executed. The condition is checked again. If it
evaluates to true, the statement(s) inside the for loop are executed. This cycle goes
on. If at all, the condition evaluates to false.

Example 1: For Loop


In this example, we shall write a for loop that prints numbers from 1 to 5.
#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 5; i++) {
cout << i << "\n";
}
}
Jump Statements

Types of Jump Statements


There are four types of jump statements
1. break
2. continue
3. goto
4. return

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.

The syntax of the continue statement is:


continue;

// 1. program to print the value of i

#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.

Syntax of goto Statement


goto label;
... .. ...
... .. ...
... .. ...
label:
statement;
... .. ...
In the syntax above, label is an identifier. When goto label; is encountered,
the control of program jumps to label: and executes the code below it.

Working of goto statement in C++ programming


Example
// This program calculates the average of numbers entered by the user.
// If the user enters a negative number, it ignores the number and
// calculates the average number entered before it.

# 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

You might also like