Array in CPP
Array in CPP
Topperworld.in
Array In C++
⚫ In C++, an array is a variable that can store multiple values of the same type.
⚫ A collection of related data items stored in adjacent memory places is
referred to as an array in the C++ programming language or any other
programming language for that matter.
⚫ Elements of an array can be accessed arbitrarily using its indices. They can
be used to store a collection of any type of primitive data type, including int,
float, double, char, etc.
⚫ An array in C++ can also store derived data types like structures, pointers,
and other data types, which is an addition.
❖ Types of Array
There are 2 types of arrays in C++ programming:
©Topperworld
C++ Programming
Example:
#include <iostream>
int main() {
// Declare and initialize a single-dimensional array
int numbers[5] = {10, 20, 30, 40, 50};
// Access and print elements of the array
std::cout << "Array elements: ";
for (int i = 0; i < 5; ++i) {
std::cout << numbers[i] << " ";
}
return 0;
}
Output:
Array elements: 10 20 30 40 50
©Topperworld
C++ Programming
➢ Multi-dimensional array
• A two-dimensional array is the most basic type of multidimensional array;
it also qualifies as a multidimensional array. There are no restrictions on
the array's dimensions.
©Topperworld
C++ Programming
Example:
#include <iostream>
int main() {
// Declare and initialize a 2D array
int matrix[3][3] = {{1, 2, 3},
{4, 5, 6},
{7, 8, 9}};
return 0;
}
Output:
Matrix elements:
123
456
789
©Topperworld
C++ Programming
©Topperworld
C++ Programming
❖ Applications of Arrays:
• 2D Arrays are used to implement matrices.
• Arrays can be used to implement various data structures like
a heap, stack, queue, etc.
• They allow random access.
• They are cache-friendly.
©Topperworld