0% found this document useful (0 votes)
41 views61 pages

Oop 1

The document provides an overview of Object-Oriented Programming (OOP), highlighting its fundamental concepts such as classes, objects, encapsulation, inheritance, and polymorphism. It contrasts OOP with procedural programming, noting advantages like improved software maintainability and productivity, while also addressing disadvantages like a steeper learning curve and larger program sizes. Additionally, it covers C++ data types and basic input/output operations, emphasizing the importance of data types in memory allocation and variable declaration.

Uploaded by

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

Oop 1

The document provides an overview of Object-Oriented Programming (OOP), highlighting its fundamental concepts such as classes, objects, encapsulation, inheritance, and polymorphism. It contrasts OOP with procedural programming, noting advantages like improved software maintainability and productivity, while also addressing disadvantages like a steeper learning curve and larger program sizes. Additionally, it covers C++ data types and basic input/output operations, emphasizing the importance of data types in memory allocation and variable declaration.

Uploaded by

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

UNIT I

1. Object Oriented Thinking:-

Traditionally, a programming problem is attacked by coming up with some kinds of data


representations, and procedures that operate on that data. Under this model, data is inert,
passive, and helpless; it sits at the complete mercy of a large procedural body, which is active,
logical, and all-powerful.

The problem with this approach is that programs are written by programmers, who are only
human and can only keep so much detail clear in their heads at any one time. As a project gets
larger, its procedural core grows to the point where it is difficult to remember how the whole
thing works. Minor lapses of thinking and typographical errors become more likely to result in
well-concealed bugs. Complex and unintended interactions begin to emerge within the
procedural core, and maintaining it becomes like trying to carry around an angry squid without
letting any tentacles touch your face. There are guidelines for programming that can help to
minimize and localize bugs within this traditional paradigm, but there is a better solution that
involves fundamentally changing the way we work.

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


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

Characteristics Of Object-Oriented Programming:

1) Object

This is the basic unit of object oriented programming. That is both data and function that
operate on data are bundled as a unit called as an object.
2) Class

When you define a class, you define a blueprint for an object. This doesn't define any data,
but it does define what the class name means, that is, what an object of the class will consist
of and what operations can be performed on such an object.

EXAMPLE-

#include <iostream>

using namespace std;

// Define a class named 'Person'

class Person {

public:

// Data members

string name;

int age;

// Member function to introduce the person

void introduce() {

cout << "Hi, my name is " << name << " and I am " << age << " years old." << endl;

};

int main() {

// Create an object of the Person class

Person person1;

// Assign values to the object's data members

person1.name = "John";

person1.age = 30;
// Call the member function

person1.introduce();

return 0;

3) Abstraction

Data abstraction refers to, providing only essential information to the outside world and hiding
their background details, i.e., to represent the needed information in program without presenting
the details. For example, a database system hides certain details of how data is stored and
created and maintained. Similar way, C++ classes provide different methods to the outside
world without giving internal detail about those methods and data.

4) Encapsulation

Encapsulation is placing the data and the functions that work on that data in the same place.
While working with procedural languages, it is not always clear which functions work on which
variables but object-oriented programming provides you a framework to place the data and the
relevant functions together in the same object.

5) Inheritance

One of the most useful aspects of object-oriented programming is code reusability. As the name
suggests Inheritance is the process of forming a new class from an existing class that is from the
existing class called as a base class, a new class is formed called as derived class.

This is a very important concept of object-oriented programming since this feature helps to
reduce the code size.

6) Polymorphism

The ability to use an operator or function in different ways in other words giving different
meaning or functions to the operators or functions is called polymorphism. Poly refers to many.
That is a single function or an operator functioning in many ways different upon the usage is
called polymorphism.

7) Overloading

The concept of overloading is also a branch of polymorphism. When the exiting operator or
function is made to operate on new data type, it is said to be overloaded.
3. Procedural Programming vs Object-Oriented Programming

Below are some of the differences between procedural and object-oriented programming:

Procedural Oriented Programming Object-Oriented Programming

In procedural programming, the program is In object-oriented programming, the program


divided into small parts called functions. is divided into small parts called objects.

Procedural programming follows a top-down Object-oriented programming follows


approach. a bottom-up approach.

There is no access specifier in procedural Object-oriented programming has access


programming. specifiers like private, public, protected, etc.

Adding new data and functions is not easy. Adding new data and function is easy.

Procedural programming does not have any Object-oriented programming provides data
proper way of hiding data so it is less secure. hiding so it is more secure.

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


not possible. programming.

In procedural programming, there is no In object-oriented programming, the concept


concept of data hiding and inheritance. of data hiding and inheritance is used.

In procedural programming, the function is In object-oriented programming, data is more


more important than the data. important than function.

Procedural programming is based on Object-oriented programming is based on


Procedural Oriented Programming Object-Oriented Programming

the unreal world. the real world.

Procedural programming is used for designing Object-oriented programming is used for


medium-sized programs. designing large and complex programs.

Procedural programming uses the concept of Object-oriented programming uses the


procedure abstraction. concept of data abstraction.

Code reusability absent in procedural Code reusability present in object-oriented


programming, programming.

Examples: C, FORTRAN, Pascal, Basic, etc. Examples: C++, Java, Python, C#, etc.

4. Features of object oriented programming paradigm

 Programs are divided into simple elements referred to as object

 Focus is on properties and functions rather than procedure.

 Data is hidden from external functions.

 Functions operate on the properties of an object.

 Objects may communicate with each other through a function called messaging.

 Follow the bottom-up approach in oop design

5. Some of the advantages of object-oriented programming include:

1. Improved software-development productivity: Object-oriented programming is modular, as it


provides separation of duties in object-based program development. It is also extensible, as
objects can be extended to include new attributes and behaviors. Objects can also be reused
within an across applications. Because of these three factors – modularity, extensibility, and
reusability – object-oriented programming provides improved software-development
productivity over traditional procedure-based programming techniques.

2. Improved software maintainability: For the reasons mentioned above, object- oriented
software is also easier to maintain. Since the design is modular, part ofthe system can be
updated in case of issues without a need to make large-scale changes.

3. Faster development: Reuse enables faster development. Object-oriented programming


languages come with rich libraries of objects, and code developed during projects is also
reusable in future projects.

4. Lower cost of development: The reuse of software also lowers the cost of development.
Typically, more effort is put into the object-oriented analysis and design, which lowers the
overall cost of development.

5. Higher-quality software: Faster development of software and lower cost of development


allows more time and resources to be used in the verification of the software. Although quality
is dependent upon the experience of the teams, object- oriented programming tends to result in
higher-quality software.

6. Some of the disadvantages of object-oriented programming include:

1. Steep learning curve: The thought process involved in object-oriented programming may not
be natural for some people, and it can take time to get used to it. It is complex to create
programs based on interaction of objects. Some of the key programming techniques, such as
inheritance and polymorphism, can be challenging to comprehend initially.

2. Larger program size: Object-oriented programs typically involve more lines of code than
procedural programs.

3. Slower programs: Object-oriented programs are typically slower than procedure- based
programs, as they typically require more instructions to be executed.

4. Not suitable for all types of problems: There are problems that lend themselves well to
functional-programming style, logic-programming style, or procedure-based programming
style, and applying object-oriented programming in those situations will not result in efficient
programs.

7. Object Model

An object model is a logical interface, software or system that is modeled through the use of
object-oriented techniques. It enables the creation of an architectural software or system model
prior to development or programming.

An object model is part of the object-oriented programming (OOP) lifecycle.


An object model helps describe or define a software/system in terms of objects and classes. It
defines the interfaces or interactions between different models, inheritance, encapsulation and
other object-oriented interfaces and features.

Object model examples include:

Document Object Model (DOM): A set of objects that provides a modeled representation of
dynamic HTML and XHTML-based Web pages

Component Object Model (COM): A proprietary Microsoft software architecture used to create
software components.

8. What are the various elements of OOP?

Various elements of OOP are:

- Object

- Class

- Method

- Encapsulation

- Information Hiding

- Inheritance

- Polymorphism

9. Basic Input / Output in C++

C++ comes with libraries that provide us with many ways for performing input and output. In

C++ input and output are performed in the form of a sequence of bytes or more commonly

known as streams.

 Input Stream: If the direction of flow of bytes is from the device(for example, Keyboard)
to the main memory then this process is called input.
 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.

Header files available in C++ for Input/Output operations are:

1. iostream: iostream stands for standard input-output stream. This header file contains
definitions of objects like cin, cout, cerr, etc.

2. iomanip: iomanip stands for input-output manipulators. The methods declared in these files
are used for manipulating streams. This file contains definitions of setw, setprecision, etc.

3. fstream: This header file mainly describes the file stream. This header file is used to handle
the data being read from a file as input or data being written into the file as output.

4. bits/stdc++: This header file includes every standard library. In programming contests,
using this file is a good idea, when you want to reduce the time wasted in doing chores;
especially when your rank is time sensitive.

5. In C++ after the header files, we often use ‘using namespace std;‘. The reason behind it is
that all of the standard library definitions are inside the namespace std. As the library
functions are not defined at global scope, so in order to use them we use namespace std. So,
that we don’t need to write STD:: at every line (eg. STD::cout etc.).

The two instances cout in C++ and cin in C++ 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++. To use cin and cout in C++ one must include the header
file iostream in the program.

Standard output stream (cout): Usually the standard output device is the display screen.
The C++ cout statement is the instance of the ostream class. It is used to produce output on
the standard output device which is usually the display screen. The data needed to be
displayed on the screen is inserted in the standard output stream (cout) using the insertion
operator(<<).

 standard input stream (cin): Usually the input device in a computer is the keyboard. C++
cin statement is the instance of the class istream and is used to read input from the standard
input device which is usually a keyboard.
The extraction operator(>>) is used along with the object cin for reading inputs. The
extraction operator extracts the data from the object cin which is entered using the keyboard.

10. C++ Data Type

All variables use data type during declaration to restrict the type of data to be stored. Therefore,
we can say that data types are used to tell the variables the type of data they can store.
Whenever a variable is defined in C++, the compiler allocates some memory for that variable
based on the data type with which it is declared. Every data type requires a different amount of
memory.
C++ supports a wide variety of data types and the programmer can select the data type
appropriate to the needs of the application. Data types specify the size and types of values to be
stored. However, storage representation and machine instructions to manipulate each data type
differ from machine to machine, although C++ instructions are identical on all machines.

C++ supports the following data types:


1. Primary or Built-in or Fundamental data type
2. Derived data types
3. User-defined data types
Data Types in C++ are Mainly Divided into 3 Types:

1. Primitive Data Types: These data types are built-in or predefined data types and can be used
directly by the user to declare variables. example: int, char, float, bool, etc. Primitive data types
available in C++ are:
 Integer
 Character
 Boolean
 Floating Point
 Double Floating Point
 Valueless or Void
 Wide Character

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

3. Abstract or User-Defined Data Types: Abstract or User-Defined data types are defined by
the user itself. Like, defining a class in C++ or a structure. C++ provides the following user-
defined datatypes:
 Class
 Structure
 Union
 Enumeration
 Typedef defined Datatype

Primitive Data Types


 Integer: The keyword used for integer data types is int. Integers typically require 4 bytes of
memory space and range from -2147483648 to 2147483647.
 Character: Character data type is used for storing characters. The keyword used for the
character data type is char. Characters typically require 1 byte of memory space and range
from -128 to 127 or 0 to 255.
 Boolean: Boolean data type is used for storing Boolean or logical values. A Boolean
variable can store either true or false. The keyword used for the Boolean data type is bool.
 Floating Point: Floating Point data type is used for storing single-precision floating-point
values or decimal values. The keyword used for the floating-point data type is float. Float
variables typically require 4 bytes of memory space.
 Double Floating Point: Double Floating Point data type is used for storing double-precision
floating-point values or decimal values. The keyword used for the double floating-point data
type is double. Double variables typically require 8 bytes of memory space.
 void: Void means without any value. void data type represents a valueless entity. A void
data type is used for those function which does not return a value.
 Wide Character: Wide character data type is also a character data type but this data type
has a size greater than the normal 8-bit data type. Represented by wchar_t. It is generally 2
or 4 bytes long.
 sizeof() operator: sizeof() operator is used to find the number of bytes occupied by a
variable/data type in computer memory.

Datatype Modifiers
As the name suggests, datatype modifiers are used with built-in data types to modify the length
of data that a particular data type can hold.

Data type modifiers available in C++ are:


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

short int 2 -32,768 to 32,767

unsigned short int 2 0 to 65,535

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

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

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

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

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

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

signed char 1 -128 to 127

unsigned char 1 0 to 255

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

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

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

wchar_t 2 or 4 1 wide character

Macro Constants
Name Expresses
Name Expresses

CHAR_MIN The minimum value for an object of type char

CHAR_MAX Maximum value for an object of type char

SCHAR_MIN The minimum value for an object of type Signed char

SCHAR_MAX Maximum value for an object of type Signed char

UCHAR_MAX Maximum value for an object of type Unsigned char

CHAR_BIT Number of bits in a char object

MB_LEN_MAX Maximum number of bytes in a multi-byte character

SHRT_MIN The minimum value for an object of type short int

SHRT_MAX Maximum value for an object of type short int

USHRT_MAX Maximum value for an object of type Unsigned short int

INT_MIN The minimum value for an object of type int

INT_MAX Maximum value for an object of type int

UINT_MAX Maximum value for an object of type Unsigned int


Name Expresses

LONG_MIN The minimum value for an object of type long int

LONG_MAX Maximum value for an object of type long int

ULONG_MAX Maximum value for an object of type Unsigned long int

LLONG_MIN The minimum value for an object of type long long int

LLONG_MAX Maximum value for an object of type long long int

ULLONG_MAX Maximum value for an object of type Unsigned long long int

Type Conversion in C++

Type conversion is the process that converts the predefined data type of one variable into an
appropriate data type. The main idea behind type conversion is to convert two different data
type variables into a single data type to solve mathematical and logical expressions easily
without any data loss.

For example, we are adding two numbers, where one variable is of int type and another of float
type; we need to convert or typecast the int variable into a float to make them both float data
types to add them.

Type conversion can be done in two ways in C++, one is implicit type conversion, and the
second is explicit type conversion. Those conversions are done by the compiler itself, called
the implicit type or automatic type conversion. The conversion, which is done by the user or
requires user interferences called the explicit or user define type conversion. Let's discuss the
implicit and explicit type conversion in C++.
Implicit Type Conversion

The implicit type conversion is the type of conversion done automatically by the compiler
without any human effort. It means an implicit conversion automatically converts one data type
into another type based on some predefined rules of the C++ compiler. Hence, it is also known
as the automatic type conversion.

Order of the typecast in implicit conversion

The following is the correct order of data types from lower rank to higher rank:

bool -> char -> short int -> int -> unsigned int -> long int -> unsigned long int -
> long long int -> float -> double -> long double

Example of Type Implicit Conversion:

// An example of implicit conversion

#include <iostream>

using namespace std;

int main()

int x = 10; // integer x

char y = 'a'; // character c

// y implicitly converted to int. ASCII

// value of 'a' is 97

x = x + y;
// x is implicitly converted to float

float z = x + 1.0;

cout << "x = " << x << endl

<< "y = " << y << endl

<< "z = " << z << endl;

return 0;

Output:
x = 107
y=a
z = 108

Explicit type conversion

Conversions that require user intervention to change the data type of one variable to another, is
called the explicit type conversion. In other words, an explicit conversion allows the
programmer to manually changes or typecasts the data type from one variable to another type.
Hence, it is also known as typecasting. Generally, we force the explicit type conversion to
convert data from one type to another because it does not follow the implicit conversion rule.

The explicit type conversion is divided into two ways:

1. Explicit conversion using the cast operator


2. Explicit conversion using the assignment operator.

Example:
// C++ program to demonstrate

// explicit type casting

#include <iostream>

using namespace std;

int main()

double x = 1.2;

// Explicit conversion from double to int

int sum = (int)x + 1;

cout << "Sum = " << sum;

return 0;

Output:
Sum = 2

Decision Making in C++


Decision-making in C++ involves the usage of conditional statements (also called decision
control statements) to execute specific blocks of code primarily based on given situations and
their results.
So basically, in decision-making, we evaluate the conditions and make a decision about which
part of the code should be executed or not. It allows selective code execution which is crucial
for controlling the flow of a program and making it more dynamic.

Types of Decision-Making Statements in C++

In C++, the following decision-making statements are available:


1. if Statement
2. if-else Statement
3. if-else-if Ladder
4. Nested if Statement
5. switch Statement
6. Conditional Operator
7. Jump Statements: break, continue, go, return

1. if in C++
In C++, the if statement is the simplest decision-making statement. It allows the execution of a
block of code if the given condition is true. The body of the ‘if’ statement is executed only if the
given condition is true.
Syntax of if in C++
if (condition) {
// code to be executed if the condition is true
}
Here if the condition is true then the code inside the if block will be executed otherwise not.
Flowchart of if in C++

Example of if in C++
The below example demonstrates the use of the if statement by finding if the age of a person is
greater than 18 or not. if the condition is true then he/she is allowed to vote.
C++

// C++ program to find if the age of a person id greater


// than 18 or not

#include <iostream>
using namespace std;

int main()
{
int age = 19;
if (age > 18) {
cout << "allowed to vote" << endl;
}
return 0;
}

Output

allowed to vote
2. if-else in C++
The if-else decision-making statement allows us to make a decision based on the evaluation of a
given condition. If the given condition evaluates to true then the code inside the ‘if’ block is
executed and in case the condition is false, the code inside the ‘else’ block is executed.
Syntax of if-else in C++
if (condition) {
// Code to be executed if the condition is true
}
else {
// Code to be executed if the condition is false
}
Flowchart of if-else in C++

Flow diagram of if else

Example of if-else in C
The below example demonstrates the use of an if-else statement to find if the given number is
positive or nonpositive.
C++

// C++ program to find if the given number is positive or


// non positive

#include <iostream>
using namespace std;
int main()
{
int num = 5;

// Using if-else to determine if the number is positive


// or non positive
if (num > 0) {
cout << "number is positive." << endl;
}
else {
cout << "number is non-positive." << endl;
}
return 0;
}

Output

number is positive.

3. if-else if Ladder in C++


The if-else-if statements allow us to include additional situations after the preliminary if
condition. The ‘else if’ condition is checked only if the above condition is not true. , and the
`else` is the statement that will be executed if none of the above conditions is true. If some
condition is true, then no only the associated block is executed.
Syntax if-else-if Ladder
if (condition1) {
// code to be executed if condition1 is true
}
else if (condition2) {
// code to be executed if condition2 is true
}
else {
// code to be executed if both the condition is false
}
We can use multiple else if statements with an if-else pair to specify different conditions.
Flowchart of if-else-if Ladder in C++

flow diagram of the if-else-if ladder

Example of if-else-ladder in C++


The below example demonstrates the use of an if-else-if ladder. In the program, you are given
an age and if the age is less the 13 print child, if the age is between 13 to 18 print the growing
stage, else print adult.
C++

// C++ program to find if the person is child, growing age


// or adult using if else-if ladder

#include <iostream>
using namespace std;

int main()
{
int age = 18;

// if this condition is true child is printed


if (age < 13) {
cout << "child" << endl;
}
// if above above if statement is not true then we check
// this else if condition if it evalutes to true print
// growing age
else if (age >= 1 and age <= 18) {
cout << "Growing stage" << endl;
}

// if none of above condition is true print adult


else {
cout << "adult" << endl;
}
return 0;
}

Output

Growing stage

4. Nested if-else in C++


The Nested if-else statement contains an ‘if’ statement inside another ‘if’ statement. This
structure lets in more complex selection-making by way of comparing multiple conditions. In
this type of statement, multiple conditions are checked, and then the body of the last if
statement is executed.

Syntax of Nested if-else in C++


if (condition1) {
// code to be executed if condition 1 is true
if (condition2) {
// code to be executed when condition 2 is true.
}
else {
// code to be executed if condition1 is true but condition2 is false.
}
}
else {
// code to be executed when condition 1 is false
}

// C++ program to find if an integer is positive, negative or zero


// using nested if statements

#include <iostream>
using namespace std;
int main() {

int num;

cout << "Enter an integer: ";


cin >> num;

// outer if condition
if (num != 0) {

// inner if condition
if (num > 0) {
cout << "The number is positive." << endl;
}
// inner else condition
else {
cout << "The number is negative." << endl;
}
}
// outer else condition
else {
cout << "The number is 0 and it is neither positive nor negative." << endl;
}

cout << "This line is always printed." << endl;

return 0;
}

Output 1

Enter an integer: 35
The number is positive.
This line is always printed.

Output 2
Enter an integer: -35
The number is negative.
This line is always printed.

Output 3

Enter an integer: 0
The number is 0 and it is neither positive nor negative.
This line is always printed.

5. Switch Statement in C++


In C++, the switch statement is used when multiple situations need to be evaluated primarily
based on the value of a variable or an expression. switch statement acts as an alternative to
multiple if statements or if-else ladder and has a cleaner structure and it is easy for handling
multiple conditions.

Syntax of C++ switch


switch (expression) {
case value1:
// code to be executed if the value of expression is value1.
break;
case value2:
// code to be executed if the value of expression is value2.
break;
//…..
default:
// code to be executed if expression doesn't match any case.
}
Flowchart of switch in C++

Flowchart of switch in C++

Example of switch in C++


The below example demonstrates the use of switches in decision-making. In the below
program, we are given a character and you have to give output as per the given condition: if the
given input is A then print Hi!, and if the given input is B print LNCT else print invalid input.
C++

// C++ program to use switch case and print certain output


// based on some conditions

#include <iostream>
using namespace std;

int main()
{
char input = 'B';
switch (input) {
// if the input character is A then print Hi!
case 'A':
cout << "Hi!" << endl;
break;

// if the input character is B then print LNCT


case 'B':
cout << "LNCT" << endl;
break;
default:
// if the input character is invalid then print
// invalid input
cout << "invalid input" << endl;
}
return 0;
}

Output

LNCT

6. Ternary Operator ( ? : ) in C++


The conditional operator is also known as a ternary operator. It is used to write conditional
operations provided by C++. The ‘?’ operator first checks the given condition, if the condition
is true then the first expression is executed otherwise the second expression is executed. It is an
alternative to an if-else condition in C++.
Syntax of Ternary Operator in C++
condition ? expression1 : expression2
Flowchart of Conditional Operator in C++
Flow Diagram of Conditional operator

Example of Ternary Operator in C++


The below program demonstrates the use of a conditional operator to find the maximum of two
numbers.
C++

// C++ program to demonstrate the use of ternary/conditional


// operator to find the max from two numbers

#include <iostream>
using namespace std;

int main()
{
int num1 = 10, num2 = 40;
int max;
// if the condition is true then num1 will be printed
// else num2 will printed
max = (num1 > num2) ? num1 : num2;
cout << max;
return 0;
}

Output

40

7. Jump Statements in C++


Jump statements are used to alter the normal flow of the code. If you want to break the flow of
the program without any conditions then these jump statements are used. C++ provides four
types of jump statements.
 break
 continue
 goto
 return
A) break
break is a control flow statement that is used to terminate the loop and switch statements
whenever a break statement is encountered and transfer the control to the statement just after the
loop.
Syntax
break;
break statement is generally used when the actual number of iterations are not predefined so we
want to terminate the loop based on some conditions.

Flowchart of break

Flow diagram of break

Example
The below example demonstrates the use of breaks to manage the control flow.
C++

// C++ program to use break statement to break the loop when


// it become 3

#include <iostream>
using namespace std;

int main()
{
for (int i = 0; i < 5; i++) {
// if i become 3 then break the loop and move to
// next statement out of loop
if (i == 3) {
break;
}
cout << i << endl;
}
// next statements
return 0;
}

Output

0
1
2

B) continue
The continue statement is used to skip the loop body for the current iteration and continue from
the next iteration. Unlike the break statement which terminates the loop completely, continue
allows us just to skip one iteration and continue with the next iteration.
Syntax
continue;

Example
The below example demonstrates the use of continue to manage the control flow.
C++

// C++ program to use continue statement to continue the


// loop when i become 3

#include <iostream>
using namespace std;

int main()
{
for (int i = 0; i < 5; i++) {
// if i become 3 then skip the rest body of loop and
// move next iteration
if (i == 3) {
continue;
}
cout << i << endl;
}
return 0;
}

Output
0
1
2
4

C) goto
It is a jump statement that is used to transfer the control to another part of the program. It
transfers the control unconditionally to the labeled statement.
Syntax
goto label;
// ...
label:
// Statement or block of code

Example
The below example demonstrates the use of the goto statement.
C++

// C++ program to demonstrate the use of goto statement

#include <iostream>
using namespace std;

int main()
{

int age = 17;


if (age < 18) {
goto Noteligible;
}
else {
cout << "You can vote!";
}
Noteligible:
cout << "You are not eligible to vote!\n";
return 0;
}

Output

You are not eligible to vote!


Note Use of goto is generally avoided in modern programming practices because it may disturb
the readability of the code and make the code error-prone, although it is still valid and used
occasionally.

D) return
The return statement is used to exit the function immediately and optionally returns a value to
the calling function. It returns to the function from where it was called and if it is the ‘main’
function then it marks the end of the execution. So basically, return is a mechanism used to
communicate the results back to the calling function.
Syntax
return expression;
Flowchart of return

Flow diagram of return

Example
The below example demonstrates the use of a return statement to return a value from a function.
C++

// C++ program to use return statement to return the sum


// calculated by a function

#include <iostream>
using namespace std;

// Function to add two numbers and returns the result


int add(int a, int b)
{
int sum = a + b;
return sum; // Return the sum to the calling code
}

int main()
{
int res = add(3, 5);
cout << "The sum is: " << res << endl;

return 0;
}

Output

The sum is: 8


Conclusion
Decision-making is an essential factor of programming in C++, presenting flexibility and
management over program execution. When used correctly, it enhances application
performance and adaptability. However, overuse or mismanagement of decision-making
statements can lead to code complexity, decreased clarity, and protection challenges. Striking a
balance and using those statements properly is essential to enhance your code.

C++ Loops


In Programming, sometimes there is a need to perform some operation more than once or
(say) n number of times. Loops come into use when we need to repeatedly execute a block of
statements.
For example: Suppose we want to print “Hello World” 10 times. This can be done in two ways
as shown below:
Manual Method (Iterative Method)
Manually we have to write cout for the C++ statement 10 times. Let’s say you have to write it
20 times (it would surely take more time to write 20 statements) now imagine you have to write
it 100 times, it would be really hectic to re-write the same statement again and again. So, here
loops have their role.
 C++
// C++ program to Demonstrate the need of loops

#include <iostream>

using namespace std;

int main()

cout << "Hello World\n";

cout << "Hello World\n";

cout << "Hello World\n";

cout << "Hello World\n";

cout << "Hello World\n";

return 0;

Output

Hello World
Hello World
Hello World
Hello World
Hello World
Time complexity: O(1)
Space complexity: O(1)

Using Loops
In Loop, the statement needs to be written only once and the loop will be executed 10 times as
shown below. In computer programming, a loop is a sequence of instructions that is repeated
until a certain condition is reached.
There are mainly two types of loops:
1. Entry Controlled loops: In this type of loop, the test condition is tested before entering the
loop body. For Loop and While Loop is entry-controlled loops.
2. Exit Controlled Loops: In this type of loop the test condition is tested or evaluated at the
end of the loop body. Therefore, the loop body will execute at least once, irrespective of
whether the test condition is true or false. the do-while loop is exit controlled loop.

S.No. Loop Type and Description

while loop
1. – First checks the condition, then executes the
body.

for loop
2. – firstly initializes, then, condition check,
execute body, update.
S.No. Loop Type and Description

do-while

3. loop
– firstly, execute the body then condition
check

For Loop-
A For loop is a repetition control structure that allows us to write a loop that is executed a
specific number of times. The loop enables us to perform n number of steps together in one
line.
Syntax:
for (initialization expr; test expr; update expr)
{
// body of the loop
// statements we want to execute
}
Explanation of the Syntax:
 Initialization statement: This statement gets executed only once, at the beginning of the
for loop. You can enter a declaration of multiple variables of one type, such as int x=0, a=1,
b=2. These variables are only valid in the scope of the loop. Variable defined before the
loop with the same name are hidden during execution of the loop.
 Condition: This statement gets evaluated ahead of each execution of the loop body, and
abort the execution if the given condition get false.
 Iteration execution: This statement gets executed after the loop body, ahead of the next
condition evaluated, unless the for loop is aborted in the body (by break, goto, return or an
exception being thrown.)
NOTES:
 The initialization and increment statements can perform operations unrelated to the
condition statement, or nothing at all – if you wish to do. But the good practice is to only
perform operations directly relevant to the loop.
 A variable declared in the initialization statement is visible only inside the scope of the for
loop and will be released out of the loop.
 Don’t forget that the variable which was declared in the initialization statement can
be modified during the loop, as well as the variable checked in the condition.
Example1:
for(int i = 0; i < n; i++)
{
// BODY
}
Example2:
for(auto element:arr)
{
//BODY
}
Flow Diagram of for loop:

Example1:
 C++

// C++ program to Demonstrate for loop

#include <iostream>

using namespace std;

int main()

{
for (int i = 1; i <= 5; i++) {

cout << "Hello World\n";

return 0;

Output

Hello World
Hello World
Hello World
Hello World
Hello World
Time complexity: O(1)
Space complexity: O(1)

Example2:

 C++

#include <iostream>

using namespace std;

int main() {

int arr[] {40, 50, 60, 70, 80, 90, 100};


for (auto element: arr){

cout << element << " ";

return 0;

Output

40 50 60 70 80 90 100
Time complexity: O(n) n is the size of array.
Space complexity: O(n) n is the size of array.

While Loop-
While studying for loop we have seen that the number of iterations is known beforehand, i.e.
the number of times the loop body is needed to be executed is known to us. while loops are used
in situations where we do not know the exact number of iterations of the loop beforehand. The
loop execution is terminated on the basis of the test conditions.
We have already stated that a loop mainly consists of three statements – initialization
expression, test expression, and update expression. The syntax of the three loops – For, while,
and do while mainly differs in the placement of these three statements.
Syntax:
initialization expression;
while (test_expression)
{
// statements

update_expression;
}
Flow Diagram of while loop:

Example:

#include <iostream>

using namespace std;

int main() {

int i = 1;

// while loop from 1 to 5

while (i <= 5) {

cout << i << " ";

++i;

return 0;
}
 C++

// C++ program to Demonstrate while loop

#include <iostream>

using namespace std;

int main()

// initialization expression

int i = 1;

// test expression

while (i < 6) {

cout << "Hello World\n";

// update expression

i++;

return 0;
}

Output

Hello World
Hello World
Hello World
Hello World
Hello World
Time complexity: O(1)
Space complexity: O(1)
It’s explanation is same as that of the for loop.

Do-while loop
In Do-while loops also the loop execution is terminated on the basis of test conditions. The
main difference between a do-while loop and the while loop is in the do-while loop the
condition is tested at the end of the loop body, i.e do-while loop is exit controlled whereas the
other two loops are entry-controlled loops.
Note: In a do-while loop, the loop body will execute at least once irrespective of the test
condition.
Syntax:
initialization expression;
do
{
// statements
update_expression;
} while (test_expression);
Note: Notice the semi – colon(“;”)in the end of loop.
Flow Diagram of the do-while loop:

Example:
 C++

// C++ program to Demonstrate do-while loop

#include <iostream>

using namespace std;

int main()
{

int i = 2; // Initialization expression

do {

// loop body

cout << "Hello World\n";

// update expression

i++;

} while (i < 1); // test expression

return 0;

Output

Hello World
Time complexity: O(1)
Space complexity: O(1)
In the above program, the test condition (i<1) evaluates to false. But still, as the loop is an exit –
controlled the loop body will execute once.

Now let us take a look at decrementing loops.

Sometimes we need to decrement a variable with a looping condition.


Using for loop

 C++

#include <iostream>

using namespace std;

int main() {

for(int i=5;i>=0;i--)

cout<<i<<" ";

return 0;

Output

543210
Time complexity: O(1)
Space complexity: O(1)

Using while loop.

 C++

#include <iostream>
using namespace std;

int main()

//first way is to decrement in the condition itself

int i=5;

while(i--){

cout<<i<<" ";

cout<<endl;

//second way is to decrement inside the loop till i is 0

i=5;

while(i)

cout<<i<<" ";

i--;

}
return 0;

Output

43210
54321
Time complexity: O(1)
Space complexity: O(1)

Using do-while loop

 C++

#include <iostream>

using namespace std;

int main() {

int i=5;

do{

cout<<i<<" ";

}while(i--);

Output

543210
Advantages :
1. High performance: C++ is a compiled language that can produce efficient and high-
performance code. It allows low-level memory manipulation and direct access to system
resources, making it ideal for applications that require high performance, such as game
development, operating systems, and scientific computing.
2. Object-oriented programming: C++ supports object-oriented programming, allowing
developers to write modular, reusable, and maintainable code. It provides features such as
inheritance, polymorphism, encapsulation, and abstraction that make code easier to
understand and modify.
3. Wide range of applications: C++ is a versatile language that can be used for a wide range
of applications, including desktop applications, games, mobile apps, embedded systems,
and web development. It is also used extensively in the development of operating systems,
system software, and device drivers.
4. Standardized language: C++ is a standardized language, with a specification maintained
by the ISO (International Organization for Standardization). This ensures that C++ code
written on one platform can be easily ported to another platform, making it a popular choice
for cross-platform development.
5. Large community and resources: C++ has a large and active community of developers
and users, with many resources available online, including documentation, tutorials,
libraries, and frameworks. This makes it easy to find help and support when needed.
6. Interoperability with other languages: C++ can be easily integrated with other
programming languages, such as C, Python, and Java, allowing developers to leverage the
strengths of different languages in their applications.

What is Array?
Array is a linear data structure where all elements are arranged sequentially. It is a collection
of elements of same data type stored at contiguous memory locations.

For simplicity, we can think of an array as a flight of stairs where on each step is placed a
value (let’s say one of your friends). Here, you can identify the location of any of your
friends by simply knowing the count of the step they are on.
This makes it easier to calculate the position of each element by simply adding an offset to a
base value, i.e., the memory location of the first element of the array (generally denoted by
the name of the array). The base value is index 0 and the difference between the two indexes
is the offset.
Remember: “Location of next index depends on the data type we use”.

Is the array always of a fixed size?


Arrays at core are of fixed size only, but most of the languages provide dynamic sized arrays
using the underlying fixed sized arrays. For example, vector in C++, ArrayList in Java and
list in Python. In C language, the array has a fixed size meaning once the size is given to it, it
cannot be changed i.e. you can’t shrink it nor can you expand it.

In C++, an array is a data structure that is used to store multiple values of similar data types
in a contiguous memory location.
For example, if we have to store the marks of 4 or 5 students then we can easily store them
by creating 5 different variables but what if we want to store marks of 100 students or say
500 students then it becomes very challenging to create that numbers of variable and manage
them. Now, arrays come into the picture that can do it easily by just creating an array of the
required size.

Properties of Arrays in C++


 An Array is a collection of data of the same data type, stored at a contiguous memory
location.
 Indexing of an array starts from 0. It means the first element is stored at the 0th index, the
second at 1st, and so on.
 Elements of an array can be accessed using their indices.
 Once an array is declared its size remains constant throughout the program.
 An array can have multiple dimensions.
 The size of the array in bytes can be determined by the sizeof operator using which we
can also find the number of elements in the array.
 We can find the size of the type of elements stored in an array by subtracting adjacent
addresses.
Array Declaration in C++
In C++, we can declare an array by simply specifying the data type first and then the name of
an array with its size.
data_type array_name[Size_of_array];
Example
int arr[5];
Here,
 int: It is the type of data to be stored in the array. We can also use other data types such
as char, float, and double.
 arr: It is the name of the array.
 5: It is the size of the array which means only 5 elements can be stored in the array.

Initialization of Array in C++


In C++, we can initialize an array in many ways but we will discuss some most common
ways to initialize an array. We can initialize an array at the time of declaration or after
declaration.
1. Initialize Array with Values in C++
We have initialized the array with values. The values enclosed in curly braces ‘{}’ are
assigned to the array. Here, 1 is stored in arr[0], 2 in arr[1], and so on. Here the size of the
array is 5.
int arr[5] = {1, 2, 3, 4, 5};
2. Initialize Array with Values and without Size in C++
We have initialized the array with values but we have not declared the length of the array,
therefore, the length of an array is equal to the number of elements inside curly braces.
int arr[] = {1, 2, 3, 4, 5};
3. Initialize Array after Declaration (Using Loops)
We have initialized the array using a loop after declaring the array. This method is generally
used when we want to take input from the user or we cant to assign elements one by one to
each index of the array. We can modify the loop conditions or change the initialization values
according to requirements.
for (int i = 0; i < N; i++) {
arr[i] = value;
}
4. Initialize an array partially in C++
Here, we have declared an array ‘partialArray’ with size ‘5’ and with values ‘1’ and ‘2’ only.
So, these values are stored at the first two indices, and at the rest of the indices ‘0’ is stored.
int partialArray[5] = {1, 2};
5. Initialize the array with zero in C++
We can initialize the array with all elements as ‘0’ by specifying ‘0’ inside the curly braces.
This will happen in case of zero only if we try to initialize the array with a different value say
‘2’ using this method then ‘2’ is stored at the 0th index only.
int zero_array[5] = {0};
Accessing an Element of an Array in C++
Elements of an array can be accessed by specifying the name of the array, then the index of
the element enclosed in the array subscript operator []. For example, arr[i].
Example 1: The C++ Program to Illustrate How to Access Array Elements
C++

// C++ Program to Illustrate How to Access Array Elements


#include <iostream>
using namespace std;

int main()
{

int arr[3];

// Inserting elements in an array


arr[0] = 10;
arr[1] = 20;
arr[2] = 30;

// Accessing and printing elements of the array


cout << "arr[0]: " << arr[0] << endl;
cout << "arr[1]: " << arr[1] << endl;
cout << "arr[2]: " << arr[2] << endl;

return 0;
}

Output

arr[0]: 10
arr[1]: 20
arr[2]: 30
Update Array Element
To update an element in an array, we can use the index which we want to update enclosed
within the array subscript operator and assign the new value.
arr[i] = new_value;
Traverse an Array in C++
We can traverse over the array with the help of a loop using indexing in C++. First, we
have initialized an array ‘table_of_two’ with a multiple of 2. After that, we run a for loop
from 0 to 9 because in an array indexing starts from zero. Therefore, using the indices we
print all values stored in an array.
Example 2: The C++ Program to Illustrate How to Traverse an Array
C++

// C++ Program to Illustrate How to Traverse an Array


#include <iostream>
using namespace std;

int main()
{

// Initialize the array


int table_of_two[10]
= { 2, 4, 6, 8, 10, 12, 14, 16, 18, 20 };

// Traverse the array using for loop


for (int i = 0; i < 10; i++) {
// Print the array elements using indexing
cout << table_of_two[i] << " ";
}

return 0;
}

Output

2 4 6 8 10 12 14 16 18 20

Size of an Array in C++


In C++, we do not have the length function as in Java to find array size but we can calculate
the size of an array using sizeof() operator trick. First, we find the size occupied by the
whole array in the memory and then divide it by the size of the type of element stored in the
array. This will give us the number of elements stored in the array.
data_type size = sizeof(Array_name) / sizeof(Array_name[index]);
Example 3: The C++ Program to Illustrate How to Find the Size of an Array
C++

// C++ Program to Illustrate How to Find the Size of an


// Array
#include <iostream>
using namespace std;

int main()
{
int arr[] = { 1, 2, 3, 4, 5 };

// Size of one element of an array


cout << "Size of arr[0]: " << sizeof(arr[0]) << endl;

// Size of array 'arr'


cout << "Size of arr: " << sizeof(arr) << endl;

// Length of an array
int n = sizeof(arr) / sizeof(arr[0]);

cout << "Length of an array: " << n << endl;

return 0;
}

Output

Size of arr[0]: 4
Size of arr: 20
Length of an array: 5

Relation between Arrays and Pointers in C++


In C++, arrays and pointers are closely related to each other. The array name is treated as a
pointer that stored the memory address of the first element of the array. As we have discussed
earlier, In array elements are stored at contiguous memory locations that’s why we can access
all the elements of an array using the array name.
Example 4: Illustrating the Relationship between Array and Pointers
C++

// C++ Program to Illustrate that Array Name is a Pointer


// that Points to First Element of the Array
#include <iostream>
using namespace std;

int main()
{
// Defining an array
int arr[] = { 1, 2, 3, 4 };

// Define a pointer
int* ptr = arr;

// Printing address of the arrary using array name


cout << "Memory address of arr: " << &arr << endl;

// Printing address of the array using ptr


cout << "Memory address of arr: " << ptr << endl;

return 0;
}

Output

Memory address of arr: 0x7fff2f2cabb0


Memory address of arr: 0x7fff2f2cabb0

Explanation:
In the above code, we first define an array “arr” and then declare a pointer “ptr” and assign
the array “arr” to it. We are able to assign arr to ptr because arr is also a pointer. After that,
we print the memory address of arr using reference operator (&) and also print the address
stored in pointer ptr and we can see arr and ptr, both stores the same memory address.
Example 5: Printing Array Elements without Indexing in C++
We generally access and print the array elements using indexing. For example to access the
first element we use array_name[0]. We have discussed above that the array name is a
pointer that stored the address of the first element and array elements are stored at contiguous
locations. Now, we are going to access the elements of an array using the array name only.
C++

// C++ Program to Print Array Elements without Indexing


#include <iostream>
using namespace std;

int main()
{

// Define an array
int arr[] = { 11, 22, 33, 44 };

// Print elements of an array


cout << "first element: " << *arr << endl;
cout << "Second element: " << *(arr + 1) << endl;
cout << "Third element: " << *(arr + 2) << endl;
cout << "fourth element: " << *(arr + 3) << endl;

return 0;
}

Output

first element: 11
Second element: 22
Third element: 33
fourth element: 44

Explanation
In the above code, we first declared an array “arr” with four elements. After that, we are
printing the array elements. Let’s discuss how we do it. We discussed that the array name is a
pointer that stores the address of the first element of an array so, to print the first element we
have dereferenced that pointer (*arr) using dereferencing operator (*) which prints the data
stored at that address.
To print the second element of an array we first add 1 to arr which is equivalent to (address
of arr + size_of_one_element *1) that takes the pointer to the address just after the first one
and after that, we dereference that pointer to print the second element. Similarly, we print rest
of the elements of an array without using indexing.
Passing Array to Function in C++
To use arrays efficiently we should know how to pass arrays to function. We can pass arrays
to functions as an argument same as we pass variables to functions but we know that the
array name is treated as a pointer using this concept we can pass the array to functions as an
argument and then access all elements of that array using pointer.
So ultimately, arrays are always passed as pointers to the function. Let’s see 3 ways to
pass an array to a function that are majorly used.
1. Passing Array as a Pointer
In this method, we simply pass the array name in function call which means we pass the
address to the first element of the array. In this method, we can modify the array elements
within the function.
Syntax
return_type function_name ( data_type *array_name ) {
// set of statements
}
2. Passing Array as an Unsized Array
In this method, the function accepts the array using a simple array declaration with no size as
an argument.
Syntax
return_type function_name ( data_type array_name[] ) {
// set of statements
}
3. Passing Array as a Sized Array
In this method, the function accepts the array using a simple array declaration with size as an
argument. We use this method by sizing an array just to indicate the size of an array.
Syntax
return_type function_name(data_type array_name[size_of_array]){
// set of statements
}
Note: Array will be treated as a pointer in the passed function no matter what method we
use. As the array are passed as pointers, they will loose the information about its size leading
to a phenomenon named as Array Decay.
Example: Illustrating Different Ways to Pass Arrays to a Function
C++

#include <iostream>
using namespace std;

// passing array as a sized array argument


void printArraySized(int arr[3], int n)
{
cout << "Array as Sized Array Argument: ";
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
cout << endl;
}

// passing array as an unsized array argument


void printArrayUnsized(int arr[], int n)
{
cout << "Array as Unsized Array Argument: ";
for (int i = 0; i < n; i++) {
cout << *(arr + i) << " ";
}
cout << endl;
}

// Passing array as a pointer argument


void printArrayPointer(int* ptr, int n)
{
// Print array elements using pointer ptr
// that store the address of array passed
cout << "Array as Pointer Argument: ";
for (int i = 0; i < n; i++) {
cout << ptr[i] << " ";
}
}

// driver code
int main()
{

int arr[] = { 10, 20, 30 };

// Call function printArray and pass


// array and its size to it.
printArraySized(arr, 3);
printArrayUnsized(arr, 3);
printArrayPointer(arr, 3);

return 0;
}

Output

Array as Sized Array Argument: 10 20 30


Array as Unsized Array Argument: 10 20 30
Array as Pointer Argument: 10 20 30
Multidimensional Arrays in C++
Arrays declared with more than one dimension are called multidimensional arrays. The most
widely used multidimensional arrays are 2D arrays and 3D arrays. These arrays are generally
represented in the form of rows and columns.
Multidimensional Array Declaration
Data_Type Array_Name[Size1][Size2]...[SizeN];
where,
 Data_Type: Type of data to be stored in the array.
 Array_Name: Name of the array.
 Size1, Size2,…, SizeN: Size of each dimension.
Two Dimensional Array in C++
In C++, a two-dimensional array is a grouping of elements arranged in rows and columns.
Each element is accessed using two indices: one for the row and one for the column, which
makes it easy to visualize as a table or grid.
Syntax of 2D array
data_Type array_name[n][m];
Where,
 n: Number of rows.
 m: Number of columns

Example: The C++ Program to Illustrate the Two-Dimensional Array


C++

// c++ program to illustrate the two dimensional array


#include <iostream>
using namespace std;

int main()
{
// Declaring 2D array
int arr[4][4];

// Initialize 2D array using loop


for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
arr[i][j] = i + j;
}
}

// Printing the element of 2D array


for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
cout << arr[i][j] << " ";
}
cout << endl;
}

return 0;
}

Output

0123
1234
2345
3456

Explanation
In the above code we have declared a 2D array with 4 rows and 4 columns after that we
initialized the array with the value of (i+j) in every iteration of the loop. Then we are printing
the 2D array using a nested loop and we can see in the below output that there are 4 rows and
4 columns.
Three-Dimensional Array in C++
The 3D array uses three dimensions. A collection of various two-dimensional arrays piled on
top of one another can be used to represent it. Three indices—the row index, column index,
and depth index are used to uniquely identify each element in a 3D array.
Declaration of Three-Dimensional Array in C++
To declare a 3D array in C++, we need to specify its third dimension along with 2D
dimensions.
Data_Type Array_Name[D][R][C];
Where,
 Data_Type: Type of data to be stored in each element.
 Array_Name: Name of the array
 D: Number of 2D arrays or Depth of array.
 R: Number of rows in each 2D array.
 C: Number of columns in each 2D array.
Example
int array[3][3][3];

Example: The C++ Program to Illustrate the 3d Array


C++

// C++ program to illustrate the 3d array


#include <iostream>
using namespace std;

int main()
{

// declaring 3d array
int arr[3][3][3];
// initializing the array
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
for (int k = 0; k < 3; k++) {
arr[i][j][k] = i + j + k;
}
}
}

// printing the array


for (int i = 0; i < 3; i++) {
cout << i << "st layer:" << endl;
for (int j = 0; j < 3; j++) {
for (int k = 0; k < 3; k++) {
cout << arr[i][j][k] << " ";
}
cout << endl;
}
cout << endl;
}

return 0;
}

Output

0st layer:
012
123
234

1st layer:
123
234
345

2st layer:
234
345
456

Explanation
In the above code, we have declared a 3D array and then initialized it using three nested for
loops. After that, we printed all layers of the 3D array again using three nested for loops as
seen in the output.

You might also like