C Arrays: Definition, Types, and Operations
C Arrays: Definition, Types, and Operations
ARRAYS
Basic concepts:
Introduction:
Arrays are the special type of data structure in C. They are the derived data types that
can store the primitive type of data such as int, char, double, float, etc. For example, if
we want to store the marks of a student in 6 subjects, then we don't need to define a
different variable for the marks in different subjects. Instead, we can define an array
that can store the marks in each subject at the contiguous memory locations.
Definition: Array is a linear data structure and it is defined as the collection of similar
types of data items (Homogeneous) stored at contiguous memory locations. It is one
of the simplest data structures where each data element can be randomly accessed
by using its index number.
[Link]
Initialization in C is the process to assign some initial value to the variable. When the
array is declared or allocated memory, the elements of the array contain some
garbage value. So, we need to initialize the array to some meaningful value. There
are multiple ways in which we can initialize an array in C.
Operations on Array:
Following are the basic operations supported by an array.
1. Traverse − print all the array elements one by one.
2. Insertion − Adds an element at the given index.
3. Deletion − Deletes an element at the given index.
4. Search − Searches an element using the given index or by the value.
5. Update − Updates an element at the given index.
1. Traverse:
This operation is performed to traverse through the array elements. It prints all
array elements one after another. Traversal is the process in which we visit every
element of the data structure atleast once. For C array traversal, we use loops to
iterate through each element of the array .
Example program:
#include <stdio.h>
void main()
{
int Arr[5] = {18, 30, 15, 70, 12};
int i;
printf("Elements of the array are:\n");
for(i = 0; i<5; i++)
{
printf("Arr[%d] = %d, ", i, Arr[i]);
}
getch();
}
Output:
[Link] operation:
This operation is performed to insert one or more elements into the array. As per the
requirements, an element can be added at the beginning, end, or at any index of the
array.
Example program:
#include <stdio.h>
int main()
{
int arr[20] = { 18, 30, 15, 70, 12 };
int i, x, pos, n = 5;
printf("Array elements before insertion\n");
for (i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");
x = 50; // element to be inserted
pos = 4;
n++;
for (i = n-1; i >= pos; i--)
arr[i] = arr[i - 1];
arr[pos - 1] = x;
printf("Array elements after insertion\n");
for (i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");
return 0;
}
Output:
[Link] operation:
As the name implies, this operation removes an element from the array and then
reorganizes all of the array elements.
Example program:
#include <stdio.h>
void main() {
int arr[] = {18, 30, 15, 70, 12};
int k = 30, n = 5;
int i, j;
while( j < n) {
arr[j-1] = arr[j];
j = j + 1;
}
n = n -1;
Output:
[Link] operation:
This operation is performed to search an element in the array based on the value or
index.
Example program:
#include <stdio.h>
void main() {
int arr[5] = {18, 30, 15, 70, 12};
int item = 70, i, j=0 ;
printf("Given array elements are :\n");
j = j + 1;
}
Output:
[Link] operation:
This operation is performed to update an existing array element located at the given
index.
Example program:
#include <stdio.h>
void main()
{
int arr[5] = {18, 30, 15, 70, 12};
int item = 50, i, pos = 3;
printf("Given array elements are :\n");
Output:
Types of Arrays in C:
There are two types of arrays based on the number of dimensions it has. They are as
follows:
1. One Dimensional Arrays (1D Array)
2. Multidimensional Arrays
array_name [size];
// C Program to illustrate the use of 1D array
#include <stdio.h>
int main()
{
// 1d array declaration
int arr[5];
return 0;
}
Output:
Elements of Array: 1 0 1 4 9
int main()
{
// printing string
int i = 0;
while (arr[i]) {
printf("%c", arr[i++]);
}
return 0;
}
Output:
Geeks
2. Multidimensional Array:
Multi-dimensional Arrays in C are those arrays that have more than one
dimension(subscript). Some of the popular multidimensional arrays are 2D arrays
and 3D arrays. We can declare arrays with more dimensions than 3d arrays but they
are avoided as they get very complex and occupy a large amount of space.
A. Two-Dimensional Array
array_name[size1] [size2];
Here,
size1: Size of the first dimension.
size2: Size of the second dimension .
int main()
{
printf("2D Array:\n");
// printing 2d array
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
printf ("%d ", arr[i][j]);
}
printf("\n");
}
return 0;
}
Output:
2D Array:
10 20 30
40 50 60
B. Three-Dimensional Array
Another popular form of a multi-dimensional array is Three-Dimensional Array or 3D
Array. A 3D array has exactly three dimensions (Three subscripts). It can be
visualized as a collection of 2D arrays stacked on top of each other to create the
third dimension.
Syntax of 3D Array in C:
int main()
{
// 3D array declaration
int arr[2][2][2] = { 10, 20, 30, 40, 50, 60 };
// printing elements
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
for (int k = 0; k < 2; k++) {
printf("%d ", arr[i][j][k]);
}
printf("\n");
}
printf("\n \n");
}
return 0;
}
Output:
10 20
30 40
50 60
0
As per the above illustration, there are some of the following important points -
4. Delete (index) – To delete an element with the help of an index in the given
array.
5. Search (n) – To check whether the given element is present or not in an array.
6. Get (index) – It will return the element which presents on the given index.
7. Set (index, x) – It will change the element with the new element at a particular
index.
8. Max () / Min () – These will return the max and min element in the given array.
[Link] () – It will shift the whole elements either on the left or right side by the
given number.
Sorting:
Sorting is the process of arranging the array elements in a particular order i.e either
ascending (Increasing)or descending (Decreasing) order.
Example:
Sorting algorithms:
Bubble sort:
Bubble Sort (sinking sort) is the simplest sorting algorithm that works by repeatedly
swapping the adjacent elements if they are in the wrong order. This algorithm is not
suitable for large data sets as its average and worst-case time complexity is quite high.
Working of Bubble sort Algorithm:
Bubble sort works on the repeatedly swapping of adjacent elements until they are not
in the intended order. It is called bubble sort because the movement of array
elements is just like the movement of air bubbles in the water. Bubbles in water rise
up to the surface; similarly, the array elements in bubble sort move to the end in each
iteration.
To understand the working of bubble sort algorithm, let's take an unsorted array. We
are taking a short and accurate array, as we know the complexity of bubble sort
is O(n2).
Example,
Here, 32 is greater than 13 (32 > 13), so it is already sorted. Now, compare 32 with 26.
Here, 26 is smaller than 36. So, swapping is required. After swapping new array will
look like -
Here, 35 is greater than 32. So, there is no swapping required as they are already
sorted.
Here, 10 is smaller than 35 that are not sorted. So, swapping is required. Now, we
reach at the end of the array. After first pass, the array will be -
Now, move to the second iteration.
Second Pass
The same process will be followed for second iteration.
Here, 10 is smaller than 32. So, swapping is required. After swapping, the array will be
-
Third Pass
The same process will be followed for third iteration.
Here, 10 is smaller than 26. So, swapping is required. After swapping, the array will be
-
Now, move to the fourth iteration.
Fourth pass
Similarly, after the fourth iteration, the array will be -
Algorithm:
1. begin BubbleSort(arr)
2. for all array elements
3. if arr[i] > arr[i+1]
4. swap(arr[i], arr[i+1])
5. end if
6. end for
7. return arr
8. end BubbleSort
Selection sort:
Selection sort is a simple and efficient sorting algorithm that works by repeatedly
selecting the smallest (or largest) element from the unsorted portion of the list and
moving it to the sorted portion of the list.
The algorithm repeatedly selects the smallest (or largest) element from the unsorted
portion of the list and swaps it with the first element of the unsorted part. This
process is repeated for the remaining unsorted portion until the entire list is sorted
Working of Selection sort Algorithm:
To understand the working of the Selection sort algorithm, let's take an unsorted
array. It will be easier to understand the Selection sort via an example.
Now, for the first position in the sorted array, the entire array is to be scanned
sequentially.
At present, 12 is stored at the first position, after searching the entire array, it is
found that 8 is the smallest value.
So, swap 12 with 8. After the first iteration, 8 will appear at the first position in the
sorted array.
For the second position, where 29 is stored presently, we again sequentially scan the
rest of the items of unsorted array. After scanning, we find that 12 is the second
lowest element in the array that should be appeared at second position.
Now, swap 29 with 12. After the second iteration, 12 will appear at the second
position in the sorted array. So, after two iterations, the two smallest values are
placed at the beginning in a sorted way.
The same process is applied to the rest of the array elements. Now, we are showing a
pictorial representation of the entire sorting process.
Now, the array is completely sorted.
Algorithm:
#include <stdio.h>
void main()
{
int i, j, n, temp, pos, a[25];
clrscr();
printf ("Enter the number of elements\n");
scanf ("%d",&n);
printf ("Enter the %d elements\n", n);
for (i = 0; i < n ; i++)
{
scanf ("%d", &a[i]);
}
for (i = 0; i < n - 1; i++)
{
pos =I ;
for (j = i+1; j < n; j++)
{
if (arr[pos] > arr[j])
{
pos=j;
}
if(pos!=i)
{
temp = arr[i];
arr[i] = arr[pos];
arr[pos] = temp;
}
}
printf("Sorted elements\n"):
for (i = 0; i < n ; i++)
{
printf("%d",a[i]);
}
getch();
}
Quick sort:
Sorting is a way of arranging items in a systematic manner. Quicksort is the widely
used sorting algorithm that makes n log n comparisons in average case for sorting an
array of n elements.
It is a faster and highly efficient sorting algorithm. This algorithm follows the divide
and conquer approach. Divide and conquer is a technique of breaking down the
algorithms into subproblems, then solving the subproblems, and combining the
results back together to solve the original problem.
• Divide: In Divide, first pick a pivot element. After that, partition or rearrange
the array into two sub-arrays such that each element in the left sub-array is less
than or equal to the pivot element and each element in the right sub-array is
larger than the pivot element.
• Conquer: Recursively, sort two subarrays with Quicksort.
• Combine: Combine the already sorted array.
Quicksort picks an element as pivot, and then it partitions the given array around the
picked pivot element. In quick sort, a large array is divided into two arrays in which
one holds values that are smaller than the specified value (Pivot), and another array
holds the values that are greater than the pivot.
After that, left and right sub-arrays are also partitioned using the same approach. It
will continue until the single element remains in the sub-array.
To understand the working of quick sort, let's take an unsorted array. It will
make the concept clearer and more understandable.
In the given array, we consider the leftmost element as pivot. So, in this case,
a[left] = 24, a[right] = 27 and a[pivot] = 24.
Since, pivot is at left, so algorithm starts from right and move towards left.
Now, a[pivot] < a[right], so algorithm moves forward one position towards left, i.e.
-
Because, a[pivot] > a[right], so, algorithm will swap a[pivot] with a[right], and
pivot moves to right, as -
Now, a[left] = 19, a[right] = 24, and a[pivot] = 24. Since, pivot is at right, so
algorithm starts from left and moves to right.
Now, a[left] = 9, a[right] = 24, and a[pivot] = 24. As a[pivot] > a[left], so algorithm
moves one position to right as -
Now, a[left] = 29, a[right] = 24, and a[pivot] = 24. As a[pivot] < a[left], so, swap
a[pivot] and a[left], now pivot is at left, i.e. -
Since, pivot is at left, so algorithm starts from right, and move to left. Now, a[left]
= 24, a[right] = 29, and a[pivot] = 24. As a[pivot] < a[right], so algorithm moves
one position to left, as -
Now, a[pivot] = 24, a[left] = 24, and a[right] = 14. As a[pivot] > a[right], so, swap
a[pivot] and a[right], now pivot is at right, i.e. -
Now, a[pivot] = 24, a[left] = 14, and a[right] = 24. Pivot is at right, so
the algorithm starts from left and move to right.
Now, a[pivot] = 24, a[left] = 24, and a[right] = 24. So, pivot, left and right
are pointing the same element. It represents the termination of
procedure.
Element 24, which is the pivot element is placed at its exact position.
Elements that are right side of element 24 are greater than it, and the
elements that are left side of element 24 are smaller than it.
3
Tunga mahavidyalaya, thirthahalli
1
Algorithm:
Insertion sort:
3
Tunga mahavidyalaya, thirthahalli
2
Insertion sort works similar to the sorting of playing cards in hands. It is
assumed that the first card is already sorted in the card game, and then we
select an unsorted card. If the selected unsorted card is greater than the first
card, it will be placed at the right side; otherwise, it will be placed at the left
side. Similarly, all unsorted cards are taken and put in their exact place.
The simple steps of achieving the insertion sort are listed as follows
(Algorithm):
Here, 31 is greater than 12. That means both elements are already in
ascending order. So, for now, 12 is stored in a sorted sub-array.
Here, 25 is smaller than 31. So, 31 is not at correct position. Now, swap 31
with 25. Along with swapping, insertion sort will also check it with all
elements in the sorted array.
For now, the sorted array has only one element, i.e. 12. So, 25 is greater
than 12. Hence, the sorted array remains sorted after swapping.
3
Tunga mahavidyalaya, thirthahalli
4
Now, two elements in the sorted array are 12 and 25. Move forward to the
next elements that are 31 and 8.
Now, the sorted array has three items that are 8, 12 and 25. Move to the
next items that are 31 and 32.
3
Tunga mahavidyalaya, thirthahalli
5
Hence, they are already sorted. Now, the sorted array includes 8, 12, 25 and
31.
3
Tunga mahavidyalaya, thirthahalli
6
Merge sort:
Merge sort is similar to the quick sort algorithm as it uses the divide and
conquer approach to sort the elements. It is one of the most popular and
efficient sorting algorithm. It divides the given list into two equal halves,
calls itself for the two halves and then merges the two sorted halves. We
have to define the merge() function to perform the merging.
The sub-lists are divided again and again into halves until the list cannot be
divided further. Then we combine the pair of one element lists into two-
element lists, sorting them in the process. The sorted two-element pairs is
merged into the four-element lists, and so on until we get the sorted list.
3
Tunga mahavidyalaya, thirthahalli
7
According to the merge sort, first divide the given array into two equal
halves. Merge sort keeps dividing the list into equal parts until it cannot be
further divided.
As there are eight elements in the given array, so it is divided into two
arrays of size 4.
Now, again divide these two arrays into halves. As they are of size 4, so
divide them into new arrays of size 2.
Now, again divide these arrays to get the atomic value that cannot be
further divided.
In combining, first compare the element of each array and then combine
them into another array in sorted order.
So, first compare 12 and 31, both are in sorted positions. Then compare 25
and 8, and in the list of two values, put 8 first followed by 25. Then
compare 32 and 17, sort them and put 17 first followed by 32. After that,
compare 40 and 42, and place them sequentially.
3
Tunga mahavidyalaya, thirthahalli
8
In the next iteration of combining, now compare the arrays with two data
values and merge them into an array of found values in sorted order.
Now, there is a final merging of the arrays. After the final merging of above
arrays, the array will look like -
Algorithm:
In the following algorithm, arr is the given array, beg is the starting
element, and end is the last element of the array.
3
Tunga mahavidyalaya, thirthahalli
9
The important part of the merge sort is the MERGE function. This function
performs the merging of two sorted sub-arrays that are A[beg…
mid] and A[mid+1…end], to build one sorted array A[beg…end]. So, the inputs
of the MERGE function are A[], beg, mid, and end.
Searching:
Types of Searching:
• Linear search
• Binary search
• Interpolation search
• Hashing
• Tree based searching
• Ternary searching
• Jump Searching
• Exponential searching etc.
[Link] search:
4
Tunga mahavidyalaya, thirthahalli
0
traversed. It is suitable for small-sized or unsorted lists, but its time complexity
is O(n) in the worst case.
4
Tunga mahavidyalaya, thirthahalli
1
To understand the working of linear search algorithm, let's
take an unsorted array. It will be easy to understand the working of
linear search with an example. Let the elements of array are -
Now, start from the first element and compare K with each
element of the array.
The value of K, i.e., 41, is not matched with the first element of the
array. So, move to the next element. And follow the same process
until the respective element is found.
4
Tunga mahavidyalaya, thirthahalli
2
Now, the element to be searched is found. So algorithm will return the index of
the element matched.
2) Binary search:
Binary search is the search technique that works efficiently on sorted lists.
Hence, to search an element into some list using the binary search technique,
we must ensure that the list is sorted.
Binary search follows the divide and conquer approach in which the list is
divided into two halves, and the item is compared with the middle element of
the list. If the match is found then, the location of the middle element is
returned. Otherwise, we search into either of the halves depending upon the
result produced through the match.
4
Tunga mahavidyalaya, thirthahalli
3
To understand the working of the Binary search algorithm, let's
take a sorted array. It will be easy to understand the working of Binary
search with an example.
Iterative method
Recursive method
1) Iteration Method
binarySearch (arr, x, low, high)
repeat till low = high mid =
(low + high)/2 if (x ==
arr[mid]) return mid
else if (x > arr[mid])
low = mid + 1 else
high = mid - 1
4
Tunga mahavidyalaya, thirthahalli
4
2) Recursive Method (The recursive method follows the divide and conquers
approach)
We have to use the below formula to calculate the mid of the array -
Now, the element to search is found. So algorithm will return the index
of the element matched.
4
Tunga mahavidyalaya, thirthahalli
6
Binary_Search (a, lower_bound, upper_bound, val)
Step 1: set beg = lower_bound, end = upper_bound, pos = - 1
Step 2: repeat steps 3 and 4 while beg <=end
Step 3: set mid = (beg + end)/2
Step 4: if a[mid] = val
set pos = mid
print pos
go to step 6
else if a[mid] > val
set end = mid - 1
else
set beg = mid + 1
[end of if]
[end of loop]
Step 5: if pos = -1
print "value is not present in the array"
[end of if]
Step 6: exit
Sparse Matrix:
4
Tunga mahavidyalaya, thirthahalli
8
A matrix can be defined as a two-dimensional array having 'm' rows and 'n'
columns. A matrix with m rows and n columns is called m × n matrix. It is a set
of numbers that are arranged in the horizontal or vertical lines of entries.
Sparse matrices are those matrices that have the majority of their elements
equal to zero. In other words, the sparse matrix can be defined as the matrix
that has a greater number of zero elements than the non-zero elements.
4
Tunga mahavidyalaya, thirthahalli
9
Representation of the sparse matrix:
The non-zero elements in the sparse matrix can be stored using triplets that
are rows, columns, and values. There are two ways to represent the sparse
matrix that are listed as follows -
Array representation
Linked list representation
Consider an example,
5
Tunga mahavidyalaya, thirthahalli
0
Array representation,
5
Tunga mahavidyalaya, thirthahalli
1
2. Column - It represents the index of the column where the non-zero
element is located.
3. Value - It is the value of the non-zero element that is located at the
index (row, column).
4. Next node - It stores the address of the next node.
Consider an Example:
5
Tunga mahavidyalaya, thirthahalli
2
5
Tunga mahavidyalaya, thirthahalli
3