Introduction
Data structures help implement physical forms of abstract data types. Data structures serve as building blocks of the software development process.
Data structures are divided into two categories: Linear data structure. Non-linear data structure. The most popular data structures are arrays, linked lists, trees, graphs, and records.
In this article, we will discuss linear arrays and record in detail. We will also discuss what the difference between linear array and a record is.
Linear Arrays
An array is a collection of elements of the same type. The elements are placed in contiguous memory locations that are individually referenced. We use an index to reference an array element.
Initialization of Arrays
There are the following methods used to initialize Array in C++:
Passing No Value
We initialize an array without passing any value to its elements. We define the array size here.
SYNTAX:
int arr[ 10 ] = { };
Passing Values
We initialize by passing the values of the elements. We define the array size here.
SYNTAX:
int arr[ 3 ] = { 1, 2, 3 };
Passing values, not size
We initialize by passing the values of the elements. We do not define the array size here.
SYNTAX:
int arr[ ] = { 1, 2, 3, 4, 6};
Different Array Operations
We can perform the following operations on an array:
Inserting the elements
Array provides us with random access. Therefore, we can insert an element at a given index using the assignment operator.
For an 1D array, C++ Code is:
#include <iostream>
using namespace std;
int main() {
int arr[5];
arr[0] = 1;
arr[1] = 2;
arr[2] = 3;
arr[3] = 4;
arr[4] = 5;
for (int i = 0; i < 5; i++) {
cout << arr[i] << " ";
}
return 0;
}
OUTPUT:
1 2 3 4 5
Accessing the elements
Array provides us with random access. Therefore, we can access an element at a given index.
For a 1D array, C++ Code is
#include <iostream>
using namespace std;
int main() {
int arr[5];
arr[0] = 1;
arr[1] = 2;
arr[2] = 3;
arr[3] = 4;
arr[4] = 5;
cout << arr[2] << " ";
cout << arr[4] << " ";
return 0;
}
OUTPUT:
3 5
Searching an element
We can traverse the array in linear time(1 D array) to search for an element.
For a 1D array, C++ Code is
#include <iostream>
using namespace std;
int main() {
int arr[5];
arr[0] = 1;
arr[1] = 2;
arr[2] = 3;
arr[3] = 4;
arr[4] = 5;
for (int i = 0; i < 5; i++) {
if (arr[i] == 4) {
cout << "Element is present ";
return 0;
}
}
cout << "Element is not present ";
return 0;
}
OUTPUT:
Element is present