Oop 1
Oop 1
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.
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>
class Person {
public:
// Data members
string name;
int age;
void introduce() {
cout << "Hi, my name is " << name << " and I am " << age << " years old." << endl;
};
int main() {
Person person1;
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:
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.
Examples: C, FORTRAN, Pascal, Basic, etc. Examples: C++, Java, Python, C#, etc.
Objects may communicate with each other through a function called messaging.
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.
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.
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.
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.
- Object
- Class
- Method
- Encapsulation
- Information Hiding
- Inheritance
- Polymorphism
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.
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.
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.
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
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.
Macro Constants
Name Expresses
Name Expresses
LLONG_MIN The minimum value for an object of type long long int
ULLONG_MAX Maximum value for an object of type Unsigned long long int
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.
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
#include <iostream>
int main()
// value of 'a' is 97
x = x + y;
// x is implicitly converted to float
float z = x + 1.0;
return 0;
Output:
x = 107
y=a
z = 108
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.
Example:
// C++ program to demonstrate
#include <iostream>
int main()
double x = 1.2;
return 0;
Output:
Sum = 2
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.
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++
#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++
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++
#include <iostream>
using namespace std;
int main()
{
int num = 5;
Output
number is positive.
#include <iostream>
using namespace std;
int main()
{
int age = 18;
Output
Growing stage
#include <iostream>
using namespace std;
int main() {
int 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;
}
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.
#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;
Output
LNCT
#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
Flowchart of break
Example
The below example demonstrates the use of breaks to manage the control flow.
C++
#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++
#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++
#include <iostream>
using namespace std;
int main()
{
Output
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
Example
The below example demonstrates the use of a return statement to return a value from a function.
C++
#include <iostream>
using namespace std;
int main()
{
int res = add(3, 5);
cout << "The sum is: " << res << endl;
return 0;
}
Output
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>
int main()
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.
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++
#include <iostream>
int main()
{
for (int i = 1; i <= 5; i++) {
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>
int main() {
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>
int main() {
int i = 1;
while (i <= 5) {
++i;
return 0;
}
C++
#include <iostream>
int main()
// initialization expression
int i = 1;
// test expression
while (i < 6) {
// 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++
#include <iostream>
int main()
{
do {
// loop body
// update expression
i++;
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.
C++
#include <iostream>
int main() {
for(int i=5;i>=0;i--)
cout<<i<<" ";
return 0;
Output
543210
Time complexity: O(1)
Space complexity: O(1)
C++
#include <iostream>
using namespace std;
int main()
int i=5;
while(i--){
cout<<i<<" ";
cout<<endl;
i=5;
while(i)
cout<<i<<" ";
i--;
}
return 0;
Output
43210
54321
Time complexity: O(1)
Space complexity: O(1)
C++
#include <iostream>
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”.
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.
int main()
{
int arr[3];
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++
int main()
{
return 0;
}
Output
2 4 6 8 10 12 14 16 18 20
int main()
{
int arr[] = { 1, 2, 3, 4, 5 };
// Length of an array
int n = sizeof(arr) / sizeof(arr[0]);
return 0;
}
Output
Size of arr[0]: 4
Size of arr: 20
Length of an array: 5
int main()
{
// Defining an array
int arr[] = { 1, 2, 3, 4 };
// Define a pointer
int* ptr = arr;
return 0;
}
Output
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++
int main()
{
// Define an array
int arr[] = { 11, 22, 33, 44 };
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;
// driver code
int main()
{
return 0;
}
Output
int main()
{
// Declaring 2D array
int arr[4][4];
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];
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;
}
}
}
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.