We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 10
Arrays in C++
What are arrays ?
• In C++, an array is a data structure that allows you to store multiple
values of the same data type in a contiguous block of memory. • Each value in the array is called an element, and each element is identified by its index or position in the array. Arrays provide a way to efficiently organize and access a collection of data. • 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. Array Declaration in C++
• data_type array_name[Size_of_array]; • int arr[5]; Initialization of Array in C++
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};
Initialization of Array in C++
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};
Initialization of Array in C++
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; } Accessing an Element of an Array in C++ •Write a C++ program to search an element in an array using linear search