C C++ JAVA PYTHON SQL HTML CSS DSA Robotics AWS CODING INTERVIEW PREPARATION

Made with  & Code

# Array operations in C – Part 1

Written By -

Operation on Arrays in C – Part 1

There are a number of operations that can be performed on an array which are:

1. Traversal
2. Copying
3. Reversing
4. Sorting
5. Insertion
6. Deletion
7. Searching
8. Merging

We shall see traversal, copying, reversing and sorting in this section.

1. Traversal:
• Traversal means accessing each array element for a specific purpose, either to perform an operation on them , counting the total number of elements or else using those values to calculate some other result.
• Since array elements is a linear data structure meaning that all elements are placed in consecutive blocks of memory it is easy to traverse them.
• Algorithm: Consider A[]is the array:
``````Step 1: Initialise counter c = lower_bound_index

Step 2: Repeat steps 3 to 4 while c < upper_bound

Step 3: Apply the specified operation on A[c]

Step 4: Increment counter : C = C + 1

[Loop Ends]

Step 5: Exit``````

In the first step we initialise the index for our array elements and it will be incremented until last index ( step 4) to traverse all array elements. Step 2 specifies the condition that traversal will continue till upper bound of array is reached. Step 3 we perform the operation using each array element in every iteration.

• Example: Write a program to calculate the average marks of a particular student:

``````#include<stdio.h>

#include<conio.h>

int main()

{

clrscr();

int i, marks, n, sum = 0;

float avg;

printf("Enter the no.of subjects:\n");

scanf("%d",&n);

printf("Enter the marks obtained in your %d subjects\n", n);

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

{

scanf("%d", &marks[i]);

}

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

{

sum = sum + marks[i];

}

avg = (sum / n);

printf("Average of marks is : %.2f \n", avg);

return 0;

}``````

Output:

``````Enter the no.of subjects:

5

Enter the marks obtained in your 5 subjects

10

14

15

18

16

Average of marks is : 14.00``````
1. Copying elements of an array:
• Copying array elements to another array will yield an array of the same length and elements as the original one.
• In order to so, we need to know the length of original array in advance.
• The destination array should also be of the same or greater size as that of original array in order to hold the array contents.
• The copying of elements would be done on index by index basis.

ALGORITHM:

``````START

Step 1 : Take two arrays A, B

Step 2 : Store values in A

Step 3 : Loop for each value of A

Step 4 : Copy each index value to B array at the same index location

STOP

```Code: We are using integer array for example.```
``````#include<stdio.h>

int main()

{

int arr1, arr2, i, num;

printf("\nEnter the no of elements in the array :");

scanf("%d", &num);

//Accepting values into Array

printf("\nEnter the array elements :");

for (i = 0; i < num; i++) {

scanf("%d", &arr1[i]);

}

// Copying data from source array A to destination array 'b

for (i = 0; i < num; i++) {

arr2[i] = arr1[i];

}

//Printing of all elements of array

printf("The copied array is as follows:");

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

printf("\narr2[%d] = %d", i, arr2[i]);

return (0);

}``````

Output:

``````Enter the no of elements in the array :6

Enter the array elements :7

8

9

10

11

12

The copied array is as follows:

arr2 = 7

arr2 = 8

arr2 = 9

arr2 = 10

arr2 = 11

arr2 = 12``````

1. Reversing elements of an array:
• Reversing an array means that the sequence of elements of array will be reversed.
• For instance if your array ‘A’ has two elements : A = 1; A = 2; then after reversal A = 2 and A = 1.
• There are two methods to perform reversal of array.
• For the below two approaches using same logic you can later try incorporating functions and pointers.
• Let us now see the two basic approaches.

ALGORITHM 1: Using Array B to store the reverse array.

``````START

Take input from user into array A.
Store value of element of A in B, starting with last element of A and placing it as first element in B.
Loop for each value of A.
Store each value of element B into A as it is. (Copying the reversed array back to source array).
Loop for each value of B.

STOP``````

Code:

``````#include <stdio.h>

int main()

{

int n, i, j, a, b;

printf("Enter the number of elements in array\n");

scanf("%d", &n);

printf("Enter array elements\n");

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

scanf("%d", &a[i]);

//Copying elements into array b starting from end of array a

for (i = n - 1, j = 0; i >= 0; i--, j++)

b[j] = a[i];

//Copying reversed

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

a[i] = b[i];

printf("Reversed array is\n");

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

printf("%d\n", a[i]);

return 0;

}``````

Output:

``````Enter the number of elements in array

5

Enter array elements

41

42

43

44

45

Reversed array is

45

44

43

42

41``````

ALGORITHM 2: Without using a second array.

``````START

Take input from user into array A.
Store value of element of A in temp.
Starting from index n -1 i.e end of array store value of A[n-i] into A[i].
Store value of temp into A[n-i].
Loop for each value of A until mid of array is reached. ( Since we swapping nth and ith element, hence traversing till mid will ensure all swaps have been completed successfully.)
Display reversed array A.
STOP``````

Code:

``````#include <stdio.h>

int main()

{

int array, n, i, temp, end;

printf("Enter length of array:\n");

scanf("%d", &n);

end = n - 1;

printf("Enter array elements: \n");

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

{

scanf("%d", &array[i]);

}

for (i = 0; i < n/2; i++)

{

temp      = array[i];

array[i]   = array[end];

array[end] = temp;

end--;

}

printf("\nReversed array elements are:\n");

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

{

printf("%d\n", array[i]);

}

return 0;

}``````

Output:

1. ``````Enter length of array:

5

Enter array elements:

80

20

10

40

60

Reversed array elements are:

60

40

10

20

80``````

Sorting elements of an array:

• Sorting elements if array means to order the elements in ascending or descending order – usually in ascending order.
• There are a number of algorithms or techniques available for sorting arrays in C, however we shall do the basic technique here.
• Sorting techniques in depth will be covered under data structures as complete separate module.
• The basic approach to sorting is Bubble sort method where in nested loop is used to sort elements of array.
• It is not an efficient approach however is the basic building block to understand sorting of arrays. We will be sorting the array in ascending order.

Approach using Bubble Sort: (Ascending Order)

``````Create an array of fixed size.
Take n, a variable which stores the number of elements of the array, less than maximum capacity of array.
Iterate via for loop to take array elements as input, and print them.
The array elements are in unsorted fashion, to sort them, make a nested loop.
In the nested loop, the each element will be compared to all the elements below it.
In case the element is greater than the element present below it, then they are interchanged.
After executing the nested loop, we will obtain an array in ascending order arranged elements.``````

Code:

``````#include <stdio.h>

int main()

{

int i, j, temp, n, arr;

printf("Enter the number of elements in your array: \n");

scanf("%d", &n);

printf("Enter the array elements: \n");

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

scanf("%d", &arr[i]);

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

{

for (j = i + 1; j < n; ++j)

{

if (arr[i] > arr[j]) //to check if current element greater than i+1th element, if yes; perform swap.

{

temp =  arr[i];

arr[i] = arr[j];

arr[j] = temp;

}

}

}

printf("\nThe array sorted in ascending order is as given below: \n");

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

printf("%d\n", arr[i]);

return 0;

}``````

Output:

``````Enter the number of elements in your array:

5

Enter the array elements:

23

65

10

20

87

The array sorted in ascending order is as given below:

10

20

23

65

87``````

Related Posts:

Online Compilers