SlideShare a Scribd company logo
1
Array in C++
Ahmad Baryal
Saba Institute of Higher Education
Computer Science Faculty
Nov 04, 2024
2 Table of contents
 Introduction to Array
 Properties of Array
 Declaration of Array
 Initialization of Array
 Accessing an Element of an Array
 Traverse an Array
 Size of an Array
 Relation between Arrays and Pointers in C++
 Multidimensional Arrays
 Two Dimensional Array
3 C++ Arrays
 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.
4 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 number of elements in an array can be determined using the sizeof
operator.
• We can find the size of the type of elements stored in an array by subtracting
adjacent addresses.
5 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.
6 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};
7 Initialization of Array in C++
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};
8 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
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;
9 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
// 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] << " ";
}
10 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
int arr[] = { 1, 2, 3, 4, 5 };
cout << "Size of arr[0]: " << sizeof(arr[0]) << endl;
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;
11 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.
// 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;
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.
12 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.
// 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;
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.
13 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.
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
}
14 Passing Array as a Pointer Example
Explanation:
1.Function Definition:
void modifyArray(int* arr, int size): This function
takes an integer pointer (arr) and the size of the
array as parameters.
2. Array Modification:
arr[i] *= 2;: Inside the function, each element of
the array is modified. In this example, each
element is multiplied by 2.
3. Function Call:
modifyArray(myArray, 5);: The array myArray is
passed to the function modifyArray along with its
size (5).
4. Printing Modified Array:
The main function prints the modified array after
the function call.
15 Passing Array to Function in C++
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 }
Explanation:
1. Function Definition:
void modifyArray(int arr[], int size): This function
takes an integer array (arr) and the size of the
array as parameters.
2. Array Modification:
arr[i] *= 3;: Inside the function, each element of
the array is modified. In this example, each
element is multiplied by 3.
3. Function Call:
modifyArray(myArray, 5);: The array myArray is
passed to the function modifyArray along with its
size (5).
4. Printing Modified Array:
The main function prints the modified array after
the function call.
16 Passing Array to Function in C++
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 }
Explanation:
1. Function Definition:
void modifyArray(int arr[5]): This function takes an
integer array (arr) with a specified size of 5.
2. Array Modification:
arr[i] += 5;: Inside the function, each element of
the array is modified. In this example, each
element is incremented by 5.
3. Function Call:
modifyArray(myArray);: The array myArray is
passed to the function modifyArray. The size is not
explicitly mentioned in the function call because
it is implicitly known from the array declaration.
4. Printing Modified Array:
The main function prints the modified array after
the function call.
17 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.
Example of a 2D Array Declaration:
18 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.
19 Example: Program to Illustrate 2D Array
Explanation:
The provided C++ example initializes a 2D
array named matrix with integer values.
Using nested loops, it iterates through each
element of the array, accessing them with
the syntax matrix[i][j]. A placeholder
variable element is introduced to represent
each value during the iteration. The
program performs a generic print
operation for each element,
demonstrating the process of accessing
and displaying values in a 2D array. Finally,
it moves to a new line after printing each
row. The example aims to illustrate the
fundamental structure of processing and
printing elements in a 2D array in a concise
manner.
20
Any Questions?
Ad

More Related Content

Similar to Array In C++ programming object oriented programming (20)

Arrays_in_c++.pptx
Arrays_in_c++.pptxArrays_in_c++.pptx
Arrays_in_c++.pptx
MrMaster11
 
Arrays
ArraysArrays
Arrays
Chukka Nikhil Chakravarthy
 
Array Data Structure for programing language
Array Data Structure for programing languageArray Data Structure for programing language
Array Data Structure for programing language
deepuranjankumar08
 
Array,string structures. Best presentation pptx
Array,string structures. Best presentation pptxArray,string structures. Best presentation pptx
Array,string structures. Best presentation pptx
Kalkaye
 
Arrays in C++
Arrays in C++Arrays in C++
Arrays in C++
Kashif Nawab
 
Arrays-Computer programming
Arrays-Computer programmingArrays-Computer programming
Arrays-Computer programming
nmahi96
 
Chap 6 c++
Chap 6 c++Chap 6 c++
Chap 6 c++
Venkateswarlu Vuggam
 
Chap 6 c++
Chap 6 c++Chap 6 c++
Chap 6 c++
Venkateswarlu Vuggam
 
Array assignment
Array assignmentArray assignment
Array assignment
Ahmad Kamal
 
Chapter-Five.pptx
Chapter-Five.pptxChapter-Five.pptx
Chapter-Five.pptx
berekethailu2
 
ARRAYS
ARRAYSARRAYS
ARRAYS
muniryaseen
 
Arrays & Strings
Arrays & StringsArrays & Strings
Arrays & Strings
Munazza-Mah-Jabeen
 
Arrays and strings in c++
Arrays and strings in c++Arrays and strings in c++
Arrays and strings in c++
GC University Faisalabad
 
Lecture 9
Lecture 9Lecture 9
Lecture 9
Mohammed Khan
 
Arrays in programming
Arrays in programmingArrays in programming
Arrays in programming
TaseerRao
 
Algo>Arrays
Algo>ArraysAlgo>Arrays
Algo>Arrays
Ain-ul-Moiz Khawaja
 
Data structure array
Data structure  arrayData structure  array
Data structure array
MajidHamidAli
 
2 arrays
2   arrays2   arrays
2 arrays
trixiacruz
 
arraytypes of array and pointer string in c++.pptx
arraytypes of array and pointer string in c++.pptxarraytypes of array and pointer string in c++.pptx
arraytypes of array and pointer string in c++.pptx
harinipradeep15
 
Array 31.8.2020 updated
Array 31.8.2020 updatedArray 31.8.2020 updated
Array 31.8.2020 updated
vrgokila
 
Arrays_in_c++.pptx
Arrays_in_c++.pptxArrays_in_c++.pptx
Arrays_in_c++.pptx
MrMaster11
 
Array Data Structure for programing language
Array Data Structure for programing languageArray Data Structure for programing language
Array Data Structure for programing language
deepuranjankumar08
 
Array,string structures. Best presentation pptx
Array,string structures. Best presentation pptxArray,string structures. Best presentation pptx
Array,string structures. Best presentation pptx
Kalkaye
 
Arrays in C++
Arrays in C++Arrays in C++
Arrays in C++
Kashif Nawab
 
Arrays-Computer programming
Arrays-Computer programmingArrays-Computer programming
Arrays-Computer programming
nmahi96
 
Array assignment
Array assignmentArray assignment
Array assignment
Ahmad Kamal
 
Chapter-Five.pptx
Chapter-Five.pptxChapter-Five.pptx
Chapter-Five.pptx
berekethailu2
 
Arrays in programming
Arrays in programmingArrays in programming
Arrays in programming
TaseerRao
 
Data structure array
Data structure  arrayData structure  array
Data structure array
MajidHamidAli
 
2 arrays
2   arrays2   arrays
2 arrays
trixiacruz
 
arraytypes of array and pointer string in c++.pptx
arraytypes of array and pointer string in c++.pptxarraytypes of array and pointer string in c++.pptx
arraytypes of array and pointer string in c++.pptx
harinipradeep15
 
Array 31.8.2020 updated
Array 31.8.2020 updatedArray 31.8.2020 updated
Array 31.8.2020 updated
vrgokila
 

More from Ahmad177077 (12)

Pointers in C++ object oriented programming
Pointers in C++ object oriented programmingPointers in C++ object oriented programming
Pointers in C++ object oriented programming
Ahmad177077
 
6. Functions in C ++ programming object oriented programming
6. Functions in C ++ programming object oriented programming6. Functions in C ++ programming object oriented programming
6. Functions in C ++ programming object oriented programming
Ahmad177077
 
Operators in c++ programming types of variables
Operators in c++ programming types of variablesOperators in c++ programming types of variables
Operators in c++ programming types of variables
Ahmad177077
 
2. Variables and Data Types in C++ proramming.pptx
2. Variables and Data Types in C++ proramming.pptx2. Variables and Data Types in C++ proramming.pptx
2. Variables and Data Types in C++ proramming.pptx
Ahmad177077
 
Introduction to c++ programming language
Introduction to c++ programming languageIntroduction to c++ programming language
Introduction to c++ programming language
Ahmad177077
 
Selection Sort & Insertion Sorts Algorithms
Selection Sort & Insertion Sorts AlgorithmsSelection Sort & Insertion Sorts Algorithms
Selection Sort & Insertion Sorts Algorithms
Ahmad177077
 
Strassen's Matrix Multiplication divide and conquere algorithm
Strassen's Matrix Multiplication divide and conquere algorithmStrassen's Matrix Multiplication divide and conquere algorithm
Strassen's Matrix Multiplication divide and conquere algorithm
Ahmad177077
 
Recursive Algorithms with their types and implementation
Recursive Algorithms with their types and implementationRecursive Algorithms with their types and implementation
Recursive Algorithms with their types and implementation
Ahmad177077
 
Graph Theory in Theoretical computer science
Graph Theory in Theoretical computer scienceGraph Theory in Theoretical computer science
Graph Theory in Theoretical computer science
Ahmad177077
 
Propositional Logics in Theoretical computer science
Propositional Logics in Theoretical computer sciencePropositional Logics in Theoretical computer science
Propositional Logics in Theoretical computer science
Ahmad177077
 
Proof Techniques in Theoretical computer Science
Proof Techniques in Theoretical computer ScienceProof Techniques in Theoretical computer Science
Proof Techniques in Theoretical computer Science
Ahmad177077
 
1. Introduction to C++ and brief history
1. Introduction to C++ and brief history1. Introduction to C++ and brief history
1. Introduction to C++ and brief history
Ahmad177077
 
Pointers in C++ object oriented programming
Pointers in C++ object oriented programmingPointers in C++ object oriented programming
Pointers in C++ object oriented programming
Ahmad177077
 
6. Functions in C ++ programming object oriented programming
6. Functions in C ++ programming object oriented programming6. Functions in C ++ programming object oriented programming
6. Functions in C ++ programming object oriented programming
Ahmad177077
 
Operators in c++ programming types of variables
Operators in c++ programming types of variablesOperators in c++ programming types of variables
Operators in c++ programming types of variables
Ahmad177077
 
2. Variables and Data Types in C++ proramming.pptx
2. Variables and Data Types in C++ proramming.pptx2. Variables and Data Types in C++ proramming.pptx
2. Variables and Data Types in C++ proramming.pptx
Ahmad177077
 
Introduction to c++ programming language
Introduction to c++ programming languageIntroduction to c++ programming language
Introduction to c++ programming language
Ahmad177077
 
Selection Sort & Insertion Sorts Algorithms
Selection Sort & Insertion Sorts AlgorithmsSelection Sort & Insertion Sorts Algorithms
Selection Sort & Insertion Sorts Algorithms
Ahmad177077
 
Strassen's Matrix Multiplication divide and conquere algorithm
Strassen's Matrix Multiplication divide and conquere algorithmStrassen's Matrix Multiplication divide and conquere algorithm
Strassen's Matrix Multiplication divide and conquere algorithm
Ahmad177077
 
Recursive Algorithms with their types and implementation
Recursive Algorithms with their types and implementationRecursive Algorithms with their types and implementation
Recursive Algorithms with their types and implementation
Ahmad177077
 
Graph Theory in Theoretical computer science
Graph Theory in Theoretical computer scienceGraph Theory in Theoretical computer science
Graph Theory in Theoretical computer science
Ahmad177077
 
Propositional Logics in Theoretical computer science
Propositional Logics in Theoretical computer sciencePropositional Logics in Theoretical computer science
Propositional Logics in Theoretical computer science
Ahmad177077
 
Proof Techniques in Theoretical computer Science
Proof Techniques in Theoretical computer ScienceProof Techniques in Theoretical computer Science
Proof Techniques in Theoretical computer Science
Ahmad177077
 
1. Introduction to C++ and brief history
1. Introduction to C++ and brief history1. Introduction to C++ and brief history
1. Introduction to C++ and brief history
Ahmad177077
 
Ad

Recently uploaded (20)

Vaibhav Gupta BAML: AI work flows without Hallucinations
Vaibhav Gupta BAML: AI work flows without HallucinationsVaibhav Gupta BAML: AI work flows without Hallucinations
Vaibhav Gupta BAML: AI work flows without Hallucinations
john409870
 
Build 3D Animated Safety Induction - Tech EHS
Build 3D Animated Safety Induction - Tech EHSBuild 3D Animated Safety Induction - Tech EHS
Build 3D Animated Safety Induction - Tech EHS
TECH EHS Solution
 
Big Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur MorganBig Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur Morgan
Arthur Morgan
 
Web and Graphics Designing Training in Rajpura
Web and Graphics Designing Training in RajpuraWeb and Graphics Designing Training in Rajpura
Web and Graphics Designing Training in Rajpura
Erginous Technology
 
Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)
Ortus Solutions, Corp
 
Cyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of securityCyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of security
riccardosl1
 
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptxIncreasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Anoop Ashok
 
Linux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdfLinux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdf
RHCSA Guru
 
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
BookNet Canada
 
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep DiveDesigning Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
ScyllaDB
 
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath MaestroDev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
UiPathCommunity
 
Procurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptxProcurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptx
Jon Hansen
 
How analogue intelligence complements AI
How analogue intelligence complements AIHow analogue intelligence complements AI
How analogue intelligence complements AI
Paul Rowe
 
Mastering Advance Window Functions in SQL.pdf
Mastering Advance Window Functions in SQL.pdfMastering Advance Window Functions in SQL.pdf
Mastering Advance Window Functions in SQL.pdf
Spiral Mantra
 
AI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global TrendsAI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global Trends
InData Labs
 
Electronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploitElectronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploit
niftliyevhuseyn
 
MINDCTI revenue release Quarter 1 2025 PR
MINDCTI revenue release Quarter 1 2025 PRMINDCTI revenue release Quarter 1 2025 PR
MINDCTI revenue release Quarter 1 2025 PR
MIND CTI
 
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
organizerofv
 
Heap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and DeletionHeap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and Deletion
Jaydeep Kale
 
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-UmgebungenHCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
panagenda
 
Vaibhav Gupta BAML: AI work flows without Hallucinations
Vaibhav Gupta BAML: AI work flows without HallucinationsVaibhav Gupta BAML: AI work flows without Hallucinations
Vaibhav Gupta BAML: AI work flows without Hallucinations
john409870
 
Build 3D Animated Safety Induction - Tech EHS
Build 3D Animated Safety Induction - Tech EHSBuild 3D Animated Safety Induction - Tech EHS
Build 3D Animated Safety Induction - Tech EHS
TECH EHS Solution
 
Big Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur MorganBig Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur Morgan
Arthur Morgan
 
Web and Graphics Designing Training in Rajpura
Web and Graphics Designing Training in RajpuraWeb and Graphics Designing Training in Rajpura
Web and Graphics Designing Training in Rajpura
Erginous Technology
 
Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)
Ortus Solutions, Corp
 
Cyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of securityCyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of security
riccardosl1
 
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptxIncreasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Anoop Ashok
 
Linux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdfLinux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdf
RHCSA Guru
 
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
BookNet Canada
 
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep DiveDesigning Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
ScyllaDB
 
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath MaestroDev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
UiPathCommunity
 
Procurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptxProcurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptx
Jon Hansen
 
How analogue intelligence complements AI
How analogue intelligence complements AIHow analogue intelligence complements AI
How analogue intelligence complements AI
Paul Rowe
 
Mastering Advance Window Functions in SQL.pdf
Mastering Advance Window Functions in SQL.pdfMastering Advance Window Functions in SQL.pdf
Mastering Advance Window Functions in SQL.pdf
Spiral Mantra
 
AI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global TrendsAI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global Trends
InData Labs
 
Electronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploitElectronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploit
niftliyevhuseyn
 
MINDCTI revenue release Quarter 1 2025 PR
MINDCTI revenue release Quarter 1 2025 PRMINDCTI revenue release Quarter 1 2025 PR
MINDCTI revenue release Quarter 1 2025 PR
MIND CTI
 
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
organizerofv
 
Heap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and DeletionHeap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and Deletion
Jaydeep Kale
 
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-UmgebungenHCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
panagenda
 
Ad

Array In C++ programming object oriented programming

  • 1. 1 Array in C++ Ahmad Baryal Saba Institute of Higher Education Computer Science Faculty Nov 04, 2024
  • 2. 2 Table of contents  Introduction to Array  Properties of Array  Declaration of Array  Initialization of Array  Accessing an Element of an Array  Traverse an Array  Size of an Array  Relation between Arrays and Pointers in C++  Multidimensional Arrays  Two Dimensional Array
  • 3. 3 C++ Arrays  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.
  • 4. 4 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 number of elements in an array can be determined using the sizeof operator. • We can find the size of the type of elements stored in an array by subtracting adjacent addresses.
  • 5. 5 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.
  • 6. 6 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};
  • 7. 7 Initialization of Array in C++ 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};
  • 8. 8 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 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;
  • 9. 9 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 // 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] << " "; }
  • 10. 10 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 int arr[] = { 1, 2, 3, 4, 5 }; cout << "Size of arr[0]: " << sizeof(arr[0]) << endl; 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;
  • 11. 11 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. // 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; 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.
  • 12. 12 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. // 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; 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.
  • 13. 13 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. 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 }
  • 14. 14 Passing Array as a Pointer Example Explanation: 1.Function Definition: void modifyArray(int* arr, int size): This function takes an integer pointer (arr) and the size of the array as parameters. 2. Array Modification: arr[i] *= 2;: Inside the function, each element of the array is modified. In this example, each element is multiplied by 2. 3. Function Call: modifyArray(myArray, 5);: The array myArray is passed to the function modifyArray along with its size (5). 4. Printing Modified Array: The main function prints the modified array after the function call.
  • 15. 15 Passing Array to Function in C++ 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 } Explanation: 1. Function Definition: void modifyArray(int arr[], int size): This function takes an integer array (arr) and the size of the array as parameters. 2. Array Modification: arr[i] *= 3;: Inside the function, each element of the array is modified. In this example, each element is multiplied by 3. 3. Function Call: modifyArray(myArray, 5);: The array myArray is passed to the function modifyArray along with its size (5). 4. Printing Modified Array: The main function prints the modified array after the function call.
  • 16. 16 Passing Array to Function in C++ 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 } Explanation: 1. Function Definition: void modifyArray(int arr[5]): This function takes an integer array (arr) with a specified size of 5. 2. Array Modification: arr[i] += 5;: Inside the function, each element of the array is modified. In this example, each element is incremented by 5. 3. Function Call: modifyArray(myArray);: The array myArray is passed to the function modifyArray. The size is not explicitly mentioned in the function call because it is implicitly known from the array declaration. 4. Printing Modified Array: The main function prints the modified array after the function call.
  • 17. 17 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. Example of a 2D Array Declaration:
  • 18. 18 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.
  • 19. 19 Example: Program to Illustrate 2D Array Explanation: The provided C++ example initializes a 2D array named matrix with integer values. Using nested loops, it iterates through each element of the array, accessing them with the syntax matrix[i][j]. A placeholder variable element is introduced to represent each value during the iteration. The program performs a generic print operation for each element, demonstrating the process of accessing and displaying values in a 2D array. Finally, it moves to a new line after printing each row. The example aims to illustrate the fundamental structure of processing and printing elements in a 2D array in a concise manner.