Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 16

Arrays:

An array is a collection of items stored at contiguous memory locations. The idea is to store
multiple items of the same type together. 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 above image can be looked as a top-level view of a staircase where you are at the base of the
staircase. Each element can be uniquely identified by their index in the array (in a similar way as
you could identify your friends by the step on which they were on in the above example).

Why do we need arrays?


We can use normal variables (v1, v2, v3, ..) when we have a small number of
objects, but if we want to store a large number of instances, it becomes
difficult to manage them with normal variables. The idea of an array is to
represent many instances in one variable.
Array declaration in C/C++:
In above image int a[3]={[0…1]=3}; this kind of declaration has been obsolete.

There are various ways in which we can declare an array. It can be done by specifying its type and
size, by initializing it or both.

Array declaration by specifying size

// Array declaration by specifying size

int arr1[10];

// With recent C/C++ versions, we can also

// declare an array of user specified size

int n = 10;

int arr2[n];

Array declaration by initializing elements


 C

// Array declaration by initializing elements


int arr[] = { 10, 20, 30, 40 }

// Compiler creates an array of size 4.


// above is same as "int arr[4] = {10, 20, 30, 40}"

Array declaration by specifying size and initializing elements


 C
// Array declaration by specifying size and initializing
// elements.
int arr[6] = { 10, 20, 30, 40 }

// Compiler creates an array of size 6, initializes first


// 4 elements as specified by user and rest two elements as
// 0. above is same as "int arr[] = {10, 20, 30, 40, 0, 0}"

Advantages of an Array in C/C++:


1. Random access of elements using array index.
2. Use of less line of code as it creates a single array of multiple
elements.
3. Easy access to all the elements.
4. Traversal through the array becomes easy using a single loop.
5. Sorting becomes easy as it can be accomplished by writing less
line of code.
Disadvantages of an Array in C/C++:
1. Allows a fixed number of elements to be entered which is decided
at the time of declaration. Unlike a linked list, an array in C is not
dynamic.
2. Insertion and deletion of elements can be costly since the elements
are needed to be managed in accordance with the new memory
allocation.
Facts about Array in C/C++:
 Accessing Array Elements:
Array elements are accessed by using an integer index. Array index
starts with 0 and goes till size of array minus 1.
 Name of the array is also a pointer to the first element of array.

Example:
 C

 C++

#include <iostream>
using namespace std;

int main()
{
int arr[5];
arr[0] = 5;
arr[2] = -10;

// this is same as arr[1] = 2


arr[3 / 2] = 2;
arr[3] = arr[0];

cout << arr[0] << " " << arr[1] << " " << arr[2] << " "
<< arr[3];

return 0;
}

utput
5 2 -10 5
No Index Out of bound Checking:
There is no index out of bounds checking in C/C++, for example, the
following program compiles fine but may produce unexpected output when
run.
// This C++ program compiles fine
// as index out of bound
// is not checked in C.

#include <iostream>
using namespace std;

int main()
{
int arr[2];

cout << arr[3] << " ";


cout << arr[-2] << " ";

return 0;
}
Output
-449684907 4195777
The elements are stored at contiguous memory locations
Example:

// C++ program to demonstrate that array elements


// are stored contiguous locations

#include <iostream>
using namespace std;

int main()
{
// an array of 10 integers.
// If arr[0] is stored at
// address x, then arr[1] is
// stored at x + sizeof(int)
// arr[2] is stored at x +
// sizeof(int) + sizeof(int)
// and so on.
int arr[5], i;

cout << "Size of integer in this compiler is "


<< sizeof(int) << "\n";

for (i = 0; i < 5; i++)


// The use of '&' before a variable name, yields
// address of variable.
cout << "Address arr[" << i << "] is " << &arr[i]
<< "\n";

return 0;
}

Output
Size of integer in this compiler is 4
Address arr[0] is 0x7ffe75c32210
Address arr[1] is 0x7ffe75c32214
Address arr[2] is 0x7ffe75c32218
Address arr[3] is 0x7ffe75c3221c
Address arr[4] is 0x7ffe75c32220

Another way to traverse the array

 C++

#include<bits/stdc++.h>
using namespace std;

int main()
{
int arr[6]={11,12,13,14,15,16};
// Way -1
for(int i=0;i<6;i++)
cout<<arr[i]<<" ";

cout<<endl;
// Way 2
cout<<"By Other Method:"<<endl;
for(int i=0;i<6;i++)
cout<<i[arr]<<" ";

cout<<endl;

return 0;
}

Output
11 12 13 14 15 16
By Other Method:
11 12 13 14 15 16

Difference between Array and Pointer: Difference between Arrays and


pointers

 An array is a collection of elements of similar data type whereas the pointer


is a variable that stores the address of another variable.
 An array size decides the number of variables it can store whereas; a pointer
variable can store the address of only one variable in it.
 Arrays can be initialized at the definition, while pointers cannot be
initialized at the definition.
 Arrays are static in nature which means once the size of the array is
declared, it cannot be resized according to user’s requirement. Whereas
pointers are dynamic in nature, which means the memory allocated can be
resized later at any point in time.
 Arrays are allocated at compile time while pointers are allocated at runtime.
Let's look at the differences between the array and linked list in a
tabular form.

Array Linked list

An array is a collection of elements of a similar A linked list is a collection of objects known as a


data type. node where node consists of two parts, i.e., data
and address.

Array elements store in a contiguous memory Linked list elements can be stored anywhere in
location. the memory or randomly stored.

Array works with a static memory. Here static The Linked list works with dynamic memory.
memory means that the memory size is fixed Here, dynamic memory means that the memory
and cannot be changed at the run time. size can be changed at the run time according to
our requirements.

Array elements are independent of each other. Linked list elements are dependent on each other.
As each node contains the address of the next
node so to access the next node, we need to
access its previous node.

Array takes more time while performing any Linked list takes less time while performing any
operation like insertion, deletion, etc. operation like insertion, deletion, etc.

Accessing any element in an array is faster as Accessing an element in a linked list is slower as it
the element in an array can be directly accessed starts traversing from the first element of the
through the index. linked list.

In the case of an array, memory is allocated at In the case of a linked list, memory is allocated at
compile-time. run time.

Memory utilization is inefficient in the array. For Memory utilization is efficient in the case of a
example, if the size of the array is 6, and array linked list as the memory can be allocated or
consists of 3 elements only then the rest of the deallocated at the run time according to our
space will be unused. requirement.
Search, insert and delete in an
unsorted array
In an unsorted array, the search operation can be performed by linear
traversal from the first element to the last element.

/ C++ program to implement linear


// search in unsorted array
#include<bits/stdc++.h>
using namespace std;

// Function to implement search operation


int findElement(int arr[], int n,
int key)
{
int i;
for (i = 0; i < n; i++)
if (arr[i] == key)
return i;

return -1;
}

// Driver Code
int main()
{
int arr[] = {12, 34, 10, 6, 40};
int n = sizeof(arr) / sizeof(arr[0]);

// Using a last element as search element


int key = 40;
int position = findElement(arr, n, key);

if (position == - 1)
cout << "Element not found";
else
cout << "Element Found at Position: "
<< position + 1;

return 0;
}
Output:
Element Found at Position: 5

Insert at the end


In an unsorted array, the insert operation is faster as compared to a sorted
array because we don’t have to care about the position at which the element
is to be placed.

// C++ program to implement insert


// operation in an unsorted array.
#include <iostream>
using namespace std;

// Inserts a key in arr[] of given capacity.


// n is current size of arr[]. This
// function returns n + 1 if insertion
// is successful, else n.
int insertSorted(int arr[], int n,
int key,
int capacity)
{

// Cannot insert more elements if n is


// already more than or equal to capacity
if (n >= capacity)
return n;

arr[n] = key;

return (n + 1);
}

// Driver Code
int main()
{
int arr[20] = {12, 16, 20, 40, 50, 70};
int capacity = sizeof(arr) / sizeof(arr[0]);
int n = 6;
int i, key = 26;
cout << "\n Before Insertion: ";
for (i = 0; i < n; i++)
cout << arr[i]<< " ";

// Inserting key
n = insertSorted(arr, n, key, capacity);

cout << "\n After Insertion: ";


for (i = 0; i < n; i++)
cout << arr[i] << " ";

return 0;
}

// This code is contributed by SHUBHAMSINGH10

Output:
Before Insertion: 12 16 20 40 50 70
After Insertion: 12 16 20 40 50 70 26
Delete Operation
In the delete operation, the element to be deleted is searched using
the linear search, and then delete operation is performed followed by shifting
the elements.

// C++ program to implement delete operation in a


// unsorted array
#include <iostream>
using namespace std;

// To search a key to be deleted


int findElement(int arr[], int n,
int key);

// Function to delete an element


int deleteElement(int arr[], int n,
int key)
{
// Find position of element to be deleted
int pos = findElement(arr, n, key);

if (pos == - 1)
{
cout << "Element not found";
return n;
}

// Deleting element
int i;
for (i = pos; i < n - 1; i++)
arr[i] = arr[i + 1];

return n - 1;
}

// Function to implement search operation


int findElement(int arr[], int n, int key)
{
int i;
for (i = 0; i < n; i++)
if (arr[i] == key)
return i;

return - 1;
}

// Driver code
int main()
{
int i;
int arr[] = {10, 50, 30, 40, 20};

int n = sizeof(arr) / sizeof(arr[0]);


int key = 30;

cout << "Array before deletion\n";


for (i = 0; i < n; i++)
cout << arr[i] <<" " ;

n = deleteElement(arr, n, key);

cout << "\n\nArray after deletion\n";


for (i = 0; i < n; i++)
cout << arr[i] << " ";

return 0;
}

// This code is contributed by shubhamsingh10

Output:
Array before deletion
10 50 30 40 20
Array after deletion
10 50 40 20

Search Operation
In a sorted array, the search operation can be performed by using binary
search.

// C++ program to implement binary search in sorted array


#include <bits/stdc++.h>
using namespace std;

int binarySearch(int arr[], int low, int high, int key)


{
if (high < low)
return -1;
int mid = (low + high) / 2; /*low + (high - low)/2;*/
if (key == arr[mid])
return mid;
if (key > arr[mid])
return binarySearch(arr, (mid + 1), high, key);
return binarySearch(arr, low, (mid - 1), key);
}

/* Driver code */
int main()
{
// Let us search 3 in below array
int arr[] = { 5, 6, 7, 8, 9, 10 };
int n, key;

n = sizeof(arr) / sizeof(arr[0]);
key = 10;

cout << "Index: " << binarySearch(arr, 0, n - 1, key)


<< endl;
return 0;
}

// This code is contributed by NamrataSrivastava1

Output
Index: 5
Insert Operation
In a sorted array, a search operation is performed for the possible position of
the given element by using Binary search and then insert operation is
performed followed by shifting the elements. And in an unsorted array, the
insert operation is faster as compared to the sorted array because we don’t
have to care about the position at which the element to be placed.

// C++ program to implement insert operation in


// an sorted array.
#include <iostream>
using namespace std;

// Inserts a key in arr[] of given capacity. n is current


// size of arr[]. This function returns n+1 if insertion
// is successful, else n.
int insertSorted(int arr[], int n, int key, int capacity)
{
// Cannot insert more elements if n is already
// more than or equal to capacity
if (n >= capacity)
return n;

int i;
for (i = n - 1; (i >= 0 && arr[i] > key); i--)
arr[i + 1] = arr[i];

arr[i + 1] = key;

return (n + 1);
}

/* Driver code */
int main()
{
int arr[20] = { 12, 16, 20, 40, 50, 70 };
int capacity = sizeof(arr) / sizeof(arr[0]);
int n = 6;
int i, key = 26;

cout<< "\nBefore Insertion: ";


for (i = 0; i < n; i++)
cout << arr[i] << " ";

// Inserting key
n = insertSorted(arr, n, key, capacity);

cout << "\nAfter Insertion: ";


for (i = 0; i < n; i++)
cout << arr[i]<< " ";

return 0;
}

// This code is contributed by SHUBHAMSINGH10

Output
Before Insertion: 12 16 20 40 50 70
After Insertion: 12 16 20 26 40 50 70
Time Complexity of Insert Operation: O(n) [In the worst case all elements
may have to be moved]

Delete Operation
In the delete operation, the element to be deleted is searched using binary
search and then delete operation is performed followed by shifting the
elements.
// C++ program to implement delete operation in a
// sorted array
#include <iostream>
using namespace std;

// To search a ley to be deleted


int binarySearch(int arr[], int low, int high, int key);

/* Function to delete an element */


int deleteElement(int arr[], int n, int key)
{
// Find position of element to be deleted
int pos = binarySearch(arr, 0, n - 1, key);

if (pos == -1)
{
cout << "Element not found";
return n;
}

// Deleting element
int i;
for (i = pos; i < n - 1; i++)
arr[i] = arr[i + 1];

return n - 1;
}

int binarySearch(int arr[], int low, int high, int key)


{
if (high < low)
return -1;
int mid = (low + high) / 2;
if (key == arr[mid])
return mid;
if (key > arr[mid])
return binarySearch(arr, (mid + 1), high, key);
return binarySearch(arr, low, (mid - 1), key);
}
// Driver code
int main()
{
int i;
int arr[] = { 10, 20, 30, 40, 50 };

int n = sizeof(arr) / sizeof(arr[0]);


int key = 30;

cout << "Array before deletion\n";


for (i = 0; i < n; i++)
cout << arr[i] << " ";

n = deleteElement(arr, n, key);

cout << "\n\nArray after deletion\n";


for (i = 0; i < n; i++)
cout << arr[i] << " ";
}

// This code is contributed by shubhamsingh10

Output
Array before deletion
10 20 30 40 50

Array after deletion


10 20 40 50
Time Complexity of Delete Operation: O(n) [In the worst case all elements
may have to be moved]

 Linear search is an algorithm to find an element in a list by


sequentially checking the elements of the list until finding the
matching element. Binary search is an algorithm that finds the
position of a target value within a sorted array. Thus, this is the
main difference between linear search and binary search.

You might also like