Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Arrays

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 21

ARRAYS

Dept. of Computer Science and Engineering


National Institute of Technology, Durgapur
WHY ARRAYS
#include <stdio.h>
Consider a situation where we need to store five integer numbers. If we use programming's simple variable and data
int main() { OUTPUT type concepts, then we need five variables of int data type and the program will be as follows −
int number1;
int number2; number1: 10 It was simple, because we had to store just five integer numbers. Now let's assume we have to store 5000 integer
int number3; number2: 20 numbers. Are we going to use 5000 variables?
int number4; number3: 30
int number5; To handle such situations, almost all the programming languages provide a concept called array. An array is a
number4: 40 data structure, which can store a fixed-size collection of elements of the same data type. An array is used to store
number1 = 10;
number2 = 20;
number5: 50 a collection of data, but it is often more useful to think of an array as a collection of variables of the same type.
number3 = 30; Instead of declaring individual variables, such as number1, number2, ..., number99, you just declare one array
number4 = 40;
number5 = 50; variable number of integer type and use number1[0], number1[1], and ..., number1[99] to represent individual
printf( "number1: %d\n", number1); variables. Here, 0, 1, 2, .....99 are index associated with var variable and they are being used to represent
printf( "number2: %d\n", number2); individual elements available in the array.
printf( "number3: %d\n", number3);
printf( "number4: %d\n", number4);
We can use normal variables (v1, v2, v3, ..) when we have a small number of objects, but if we want to store a
printf( "number5: %d\n", number5); 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.
An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type. It is better and convenient
way of storing the data of same datatype with same size.
Array is particularly useful when we are dealing with lot of variables of the same type. For example, lets say we need to store the marks in math subject of 100
students. To solve this particular problem, either I have to create the 100 variables of int type or create an array of int type with the size 100. Obviously the second
option is best, because keeping track of all the 100 different variables is a tedious task. On the other hand, dealing with array is simple and easy, all 100 values can
be stored in the same array at different indexes (0 to 99).
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 base value is index 0 and the
difference between the two indexes is the offset.
• For simplicity, we can think of an array as a fleet of stairs where on each step is placed a value (let’s say one of your friends). Here, you can identify the location of any of your friends by simply
knowing the count of the step they are on. Remember: “Location of next index depends on the data type we use”.
• An array in C is a collection of items stored at contiguous memory locations and elements can be accessed randomly using indices of an array. They are used to store similar type of elements as
in the data type must be the same for all elements. They can be used to store collection of primitive data types such as int, float, double, char, etc of any particular type. To add to it, an array in C
or C++ can store derived data types such as the structures, pointers etc.
• In computer science, an array data structure, or simply an array, is a data structure consisting of a collection of elements, each identified by at least one array index or key.
• An array is a data structure that contains a group of elements. Typically these elements are all of the same data type, such as an integer or character also called string. Arrays are commonly used
in computer programs to organize data so that a related set of values can be easily sorted or searched.
• An Array is a sequential collection of elements, of the same data type. They are stored sequentially in memory. An Array is a data structure that holds a similar type of elements.
• All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element.
ARRAYS
• ARRAY DECLARATION
• To create an array variable in C, a programmer specifies the type of the elements and the number of elements to be stored in that array. Given below is a simple syntax to
create an array in C programming −
Datatype arrayName[arraySize];
• This is called a single-dimensional array. The arraySize must be an integer constant greater than zero and type can be any valid C data type. We have a data type that can
be any of the basic data types like int, float or double. Array Name is the name of the array and we declare the size of the array.
• For example, now to declare a 10-element array called number of type int, use this statement −
int number[10];
Here, number is a variable array, which is sufficient to hold up to 10 integer numbers.
• ARRAY SIZE:
• Array size is given at the time of declaration of the array. Once the size of the array is given it cannot be changed. The compiler then allocates that much memory space to
the array.
Consider the Example:
int test[20];
In the example above, we have an array test, of type int. We have given the array size to be 20. This means that 20 consecutive memory locations will be left free for
the array in the memory.
• ARRAY INDEX
• A number associated with each position in an array and this number is called the array index. Its starts from 0 and to the last element, that is the size of the array minus
one. The minus one is there because we start counting from zero and not one. Array indices always begin from zero.
• We can access elements of an array by indices.
• Each location of an element in an array has a numerical index which is used to identify the element.
• 0 (zero-based indexing): The first element of the array is indexed by a subscript of 0
• 1 (one-based indexing): The first element of the array is indexed by the subscript of 1
• n (n-based indexing): The base index of an array can be freely chosen. Usually, programming languages allowing n-based indexing also allow negative index values,
and other scalar data types like enumerations, or characters may be used as an array index.
• All arrays have 0 as the index of their first element which is also called the base index and the last index of an array will be the total size of the array minus 1.
ARRAYS
• ARRAY INITIALIZATION
• We can initialize array in C either one by one or using a single statement as follows:
• double balance[5] = {1000.0, 2.0, 3.4, 7.0, 50.0};
• The number of values between braces { } can not be larger than the number of elements that we declare for the array between square brackets [ ].
• If we omit the size of the array, an array just big enough to hold the initialization is created.
• Therefore, if we write: double balance[] = {1000.0, 2.0, 3.4, 7.0, 50.0}; we will create exactly the same array as we did in the previous example.
• Following is an example to assign a single element of the array: balance[4] = 50.0;
• The above statement assigns element number 5th in the array with a value of 50.0.
• All arrays have 0 as the index of their first element which is also called base index and last index of an array will be total size of the array minus 1
• It is possible to initialize an array during declaration. For example,
• int mark[5] = {19, 10, 8, 17, 9};
• You can also initialize an array like this.
• int mark[] = {19, 10, 8, 17, 9};
• Here, we haven't specified the size. However, the compiler knows its size is 5 as we are initializing it with 5 elements.
• Array declaration by specifying size
• int arr1[10];
• we can also declare an array of user specified size
• int n = 10;
• int arr2[n];
• 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
• 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}"
ARRAYS
• 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.
• An element is accessed by indexing the array name. This is done by placing the index of the element within square brackets after the name of the array.
• For example: int var = number[9];
• The above statement will take the 10th element from the array and assign the value to var variable. The following example uses all the above-mentioned
three concepts viz. creation, assignment, and accessing arrays −

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


int main () { int main ()
int number[10]; /* number is an array of 10 integers */ OUTPUT {
int i = 0; int n[ 10 ]; /*n is an array of 10 integers
/* Initialize elements of array n to 0 */ number[0] = 100 */
number[1] = 101
while( i < 10 ) { number[2] = 102 int i,j;
/* Set element at location i to i + 100 */ number[3] = 103 /* initialize elements of array n to 0 */
number[ i ] = i + 100; number[4] = 104
i = i + 1; number[5] = 105 for ( i = 0; i < 10; i++ )
} number[6] = 106 {
number[7] = 107 number[0] = 100
/* Output each array element's value */ number[8] = 108 /* set element at location i to i + 100 */ number[1] = 101
i = 0; n[ i ] = i + 100; number[2] = 102
number[9] = 109 number[3] = 103
while( i < 10 ) { } number[4] = 104
printf("number[%d] = %d\n", i, number[i] ); /* output each array element's value */ number[5] = 105
i = i + 1; for (j = 0; j < 10; j++ ) number[6] = 106
} { number[7] = 107
return 0; printf("Element[%d] = %d\n", number[8] = 108
} j, n[j] ); number[9] = 109
}

r
ARRAYS
• Why does Array Indexing start with 0?
• Let's try to understand this by taking one example. Assume, we can declare an array of size
10 as int a[10];
• Here a itself is a pointer which contains the memory location of the first element of the
array. Now for accessing the first element, we will write a[0] which is internally decoded by
the compiler as *(a + 0).
• In the same way, the second element can be accessed by a[1] or *(a + 1). As a contains the
address of the first element so for accessing the second element we have to add 1 to it.
That's why here we have written *(a +1). In an array, the index describes the offset from the
first element, i.e. the distance from the first element.
• Now let's assume that array indexing starts at 1 instead of 0. In this case for accessing the
first element, we have to write a[1] which is internally decoded as *(a + 1 – 1).
• Observe here that we have to perform one extra operation i.e. subtraction by 1. This extra
operation will greatly decrease the performance when the program is big. That's why to
avoid this extra operation and improve the performance, array indexing starts at 0 and not at
1.

ARRAYS
• To Read & Print Elements Of Array
• An array is a collection or a sequential order to various elements, with or without a particular order. Arrays
usually consist of information that is stored at respective pointers in C programming
• Read the size of an array and store that value into the variable n.
• scanf() function reads the entered element and initialize that element to a[i] until all iterations of for loop
as scanf(“%d”,&a[i]) using for loop for(i=0;i<n;i++).
• printf(“%d”,a[i]) it prints the elements of an array from i=0 to i<n using for loop. Print the array elements
of a[] using for loop which iterates i=0 to i<size of an array.
#include <stdio.h>
int main()
• As we can see, in this array, the size of
{ the array is defined at first.
int a[1000],i,n; • The size of this array is 5.
printf("Enter size of array: ");
scanf("%d",&n); • After that, the elements are entered
printf("Enter %d elements in the array : ", n); accordingly for the array.
• The elements entered in this array are
for(i=0;i<n;i++)
{ as follows:
scanf("%d", &a[i]); • 1, 2, 3, 4 and 5.
} •
printf("\nElements in array are: ");
Hence, after it is given a command to
print the elements, all the five elements
for(i=0;i<n;i++) will be printed as per the order they
{
printf("%d ", a[i]); were entered into the array.
}
return 0;
}
ARRAYS
• Array Memory Allocation in C
• An array is a collection of homogeneous (same type) data items stored in contiguous memory locations. For example if an array is of type
“int”, it can only store integer elements and cannot allow the elements of other types such as double, float, char etc.
• The following diagram represents an integer array that has 12 elements. The index of the array starts with 0, so the array having 12
elements has indexes from 0 to 11.
ARRAYS
• Array Memory Allocation in C

• It has been already discussed that whenever an array is declared in the program, contiguous memory to it elements are allocated.
• Initial address of the array – address of the first element of the array is called base address of the array.
• Each element will occupy the memory space required to accommodate the values for its type, i.e.; depending on elements datatype, 1, 4 or 8 bytes of memory is
allocated for each elements.
• Next successive memory address is allocated to the next element in the array. This process of allocating memory goes on till the number of element in the array gets
over.

• One Dimensional Array


• Below diagram shows how memory is allocated to an integer array of N elements.
• Its base address – address of its first element is 10000.
• Since it is an integer array, each of its element will occupy 4 bytes of space.
• Hence first element occupies memory from 10000 to 10003. Second element of the array occupies immediate next memory address in the memory, i.e.; 10004 which
requires another 4 bytes of space. Hence it occupies from 10004 to 10007. In this way all the N elements of the array occupies the memory space.

• If the array is a character array, then its elements will occupy 1 byte of memory each.
• If it is a float array then its elements will occupy 8 bytes of memory each.
• But this is not the total size or memory allocated for the array.
• They are the sizes of individual elements in the array. If we need to know the total size of the array, then we need to multiply the number of elements with the size of
individual element.

• i.e.; Total memory allocated to an Array = Number of elements * size of one element
• Total memory allocated to an Integer Array of N elements
= Number of elements * size of one element
= N * 4 bytes
= 10 * 4 bytes = 40 Bytes, where N = 10
= 500 * 4 bytes = 2000 Bytes, where N = 500
• Total memory allocated to an character Array of N elements
= Number of elements * size of one element
= N * 1 Byte
= 10 * 1 Byte = 10 Bytes, where N = 10
= 500 * 1 Byte = 500 Bytes, where N=500
ARRAY OPERATIONS
• There are a number of operations that can be performed on an array which are:
• Traversal, Copying, Reversing, Sorting
• Insertion, Deletion, Searching, Merging
• 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.
• In the first step we initialise the index for our array elements and it will
• Algorithm: Consider A[]is the array: be incremented until last index ( step 4) to traverse all array elements.
• Step 1: Initialise counter c = lower_bound_index
• Step 2: Repeat steps 3 to 4 while c < upper_bound
• Step 2 specifies the condition that traversal will continue till upper
• Step 3: Apply the specified operation on A[c] bound of array is reached.
• Step 4: Increment counter : C = C + 1 [Loop Ends] • Step 3 we perform the operation using each array element in every
• Step 5: Exit iteration.

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

#include<stdio.h> #include<conio.h>
int main()
{ clrscr(); Output:
int i, marks[5], n, sum = 0;
float avg; Enter the no.of subjects: 5
printf("Enter the no.of subjects:\n"); scanf("%d",&n); Enter the marks obtained in your 5
printf("Enter the marks obtained in your %d subjects\n", n);
for(i=0;i<n;i++) subjects 10 14 15 18 16
{ scanf("%d", &marks[i]);
}
for(i=0;i<n;i++)
Average of marks is : 14.00
{ sum = sum + marks[i];
}
avg = (sum / n);
printf("Average of marks is : %.2f \n", avg); return 0; }
ARRAY OPERATIONS
• 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:(We are using integer array)
• 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 #include<stdio.h>
• int main()
STOP {
int arr1[20], arr2[20], 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++) {
Output: arr2[i] = arr1[i];
}
Enter the no of elements in the array :6 //Printing of all elements of array
Enter the array elements :7 8 9 10 11 12 printf("The copied array is as follows:");
The copied array is as follows: arr2[0] = 7 arr2[1] = 8 arr2[2] = 9 for (i = 0; i < num; i++)
printf("\narr2[%d] = %d", i, arr2[i]);
arr2[3] = 10 arr2[4] = 11 arr2[5] = 12 return (0);
}
ARRAY OPERATIONS
• Reversing elements of an array
• Reversing an array means that the sequence of elements of array will be reversed.
• Reversing an array means that the sequence of elements of array will be reversed.
• For instance if your array ‘A’ has two elements : A[0] = 1; A[1] = 2; then after reversal A[0] = 2 and A[1] = 1.
• There are two methods to perform reversal of array.

• ALGORITHM 1: Using Array B to store the reverse array. #include <stdio.h>


int main()
• START {
int n, i, j, a[20], b[20];
• Take input from user into array A.
printf("Enter the number of elements in array\n");
• Store value of element of A in B, starting with last element of A and scanf("%d", &n);
placing it as first element in B.
printf("Enter array elements\n");
• Loop for each value of A. for (i = 0; i < n ; i++)
• Store each value of element B into A as it is. (Copying the reversed scanf("%d", &a[i]);
array back to source array). //Copying elements into array b starting from end of array
• Loop for each value of B. a
• STOP 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;
}
ARRAY OPERATIONS
• Sorting elements of an array:
• Sorting elements of 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. #include <stdio.h>
• Approach using Bubble Sort: (Ascending Order) int main()
{
int i, j, temp, n, arr[30];
• Create an array of fixed size. printf("Enter the number of elements in your array: \n");
• Take n, a variable which stores the number of elements of the scanf("%d", &n);
array, less than maximum capacity of array. printf("Enter the array elements: \n");
• Iterate via for loop to take array elements as input, and print for (i = 0; i < n; ++i)
them. scanf("%d", &arr[i]);
for (i = 0; i < n; ++i)
• The array elements are in unsorted fashion, to sort them, make a {
nested loop. for (j = i + 1; j < n; ++j)
• In the nested loop, the each element will be compared to all the {
elements below it. if (arr[i] > arr[j]) //to check if current element greater than i+1th element, if yes; perform swap.
• In case the element is greater than the element present below it, {
then they are interchanged. temp = arr[i];
arr[i] = arr[j];
• After executing the nested loop, we will obtain an array in arr[j] = temp;
ascending order arranged elements. }
}
}
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;
}
ARRAY OPERATIONS
• Insertion of an element into the array
• Insertion of an element in the array, could either be at the start , at the end or anywhere in between as well.
• We take the location at which the user wants to insert the element into the array.
• Next, we check if the position entered is valid or not. For the user the position would start from number 1. Thus in terms of
array index, actual array index position is position – 1
• If the position is invalid same is communicated to the user and program is terminated.
• The position is invalid if position is < 1 i.e. less than starting of array and position > n+1 , i.e. if your array has 4
elements; the user might want to insert element at 4th position which is nth position, else also insert it as the n+1th
element i.e. 5th element or after the current arrays end.
• If position is valid, the element is inserted at required location and resultant array is displayed.
#include <stdio.h>
int main()
{
int array[100], position, i, n, value;
printf("Enter number of elements in array\n"); Output:
scanf("%d", &n);
printf("Enter array elements:\n", n);
for (i = 0; i < n; i++)
scanf("%d", &array[i]); Case 1: Insertion location valid
printf("Enter the location where you wish to insert an element\n");
scanf("%d", &position); Enter number of elements in array 6
if(position > n+1 || position < 1) Enter array elements: 12 13 14 15 16 17
{
}
printf("The position entered is invalid\n"); Enter the location where you wish to insert an element 3
else Enter the value to insert 20
{
printf("Enter the value to insert\n");
scanf("%d", &value); Resultant array is: 12 13 20 14 15 16 17
for (i = n - 1; i >= position - 1; i--)
array[i+1] = array[i];
array[position-1] = value; //inserting value at the required location
printf("Resultant array is:\n");
for (i = 0; i <= n; i++)
printf("%d\n", array[i]);
}
return 0;
}
ARRAY OPERATIONS
• Deletion of an element from the array
• For deletion of an element from the array, we need to accept the location from which user wishes to delete the element.
• When the location is entered by user, we store it in a variable – position.
• For user location starts from position : 1. However array index starts from 0. Hence, when we delete the element we need
to delete element present at location = position -1.
• What we essentially do is, shift the element next to the element to be deleted to the location = position -1, i.e. the next
element is placed in position of deleted element and so on we keep shifting the remaining elements by one position to the
left.
• If an invalid location is entered, deletion is not possible an the same is conveyed to the user.
#include <stdio.h>
int main()
{
int array[100], position, i, n, num;
printf("Enter number of elements in array\n");
scanf("%d", &n);
printf("Enter array elements:\n");
for (i = 0; i < n; i++) Output:
scanf("%d", &array[i]); Case 1: Entered location is valid
printf("Enter the location from where you wish to delete the element:\n");
scanf("%d", &position); Enter number of elements in array 5
num = array[position-1]; Enter array elements: 14 15 16 17 18
if (position >= n+1 || position < 0) /*n+1, since user will count element as position 1 Enter the location from where you wish to delete the element: 3
onwards. Internally though indexing starts from 0, which user would not know.*/ Resultant array after deletion of element 16 from location 3: 14 15 17 18
printf("Deletion not possible as entered location is invalid.\n");
else
{
for (i = position - 1; i < n - 1; i++) //since array index starts from 0; thus position in terms of array index
is position-1
array[i] = array[i+1];
printf("Resultant array after deletion of element %d from location %d:\n", num, position);
for (i = 0; i < n - 1; i++)
printf("%d\n", array[i]);
}
return 0;
}
ARRAY OPERATIONS
• Searching element of an Array
• Searching an element of an array is to check if a user entered element is present in the array or not. If present we display
the position at which the element was found in the array.
• There are various searching techniues that can be used to find an array element.
• We are going to learn to implement the same using Linear Search.
• Linear search is not efficient as it scans for each element sequentially, however it is the easiest to understand and
implement for beginners. #include <stdio.h>
int main()
• Approach {
int array[100], num, i, n;
• We accept the array input from user. printf("Enter number of elements in array\n");
• The user will enter the element that needs to be searched in the array. scanf("%d", &n);
• We scan the entire array sequentially to search for entered element printf("Enter array elements: \n");
‘num‘.
• On discovering the element in the array at location i, we display it to for (i = 0; i < n; i++)
the user. scanf("%d", &array[i]);
• If the element occurs at more than one place as well, the search printf("Enter a number to search\n");
continues until end of array is reached. scanf("%d", &num);
• Once end of array is reached, loop is exited. for (i = 0; i < n; i++)
• If even after scanning entire array element is not found, ( i==n) then {
same is conveyed to user.
if (array[i] == num) /* When required element is found */
{
printf("The element: %d is present at location %d.\n", num, i+1);
Output: if(i == n-1) //if end of array then exit search
Case 1: Element present in array break;
Enter number of elements in array 10 }
Enter array elements: 10 20 30 40 50 60 20 10 30 10 Enter a number to }
search 10 if (i == n)
The element: 10 is present at location 1. printf("The element %d is not present in the array.\n", num);
The element: 10 is present at location 8. return 0;
The element: 10 is present at location 10. }
ARRAY OPERATIONS
• Merging of two arrays
• Two arrays are taken as input from the user in order to merge them into a resultant array ‘res‘.
• The arrays can be sorted or unsorted.
• We can either after taking the input from the user, sort the array else after merging sort the array.
• In our case, we first merge the array and then sort them.
• For sorting, we use the basic bubble sort technique to sort the array.
• However, if the array input by user is already sorted then
• the merge function alone would suffice the need.
• The function, compares the elements of the two arrays
• and inserts the elements in the ascending order into res array.
• Since, we do not know if user will always enter a sorted array,
• we sort the resultant array res post merging as well.
ARRAY OPERATIONS
• Merging of two array - Code
#include<stdio.h>
void merge(int arr1[20], int arr2[20], int n1, int n2) //merging arrays void sort(int arr[20], int n) //to sort the resultant array
{ {
int i, j, k; int i, j, swap;
int res[40]; for (i = 0 ; i < n - 1; i++)
i = 0; {
= 0;
k = 0; for (j= 0 ; j < n - i - 1; j++)
// Merging starts {
while (i < n1 && j < n2) if (arr[j] > arr[j+1]) /* For decreasing order use < */
{ {
if (arr1[i] <= arr2[j]) swap = arr[j];
{ arr[j] = arr[j+1];
res[k] = arr1[i]; arr[j+1] = swap;
i++;
k++; }
} }
else }
{ }
res[k] = arr2[j]; int main()
k++; {
j++; int arr1[20], arr2[20];
} int i, n1, n2;
}
/* Some elements in array 'arr1' are still remaining where as array 'arr2' is printf("Enter no of elements in 1st array :\n");
exhausted */ scanf("%d", &n1);
while (i < n1) printf("Enter elements of 1st array : \n");
{ for (i = 0; i < n1; i++)
res[k] = arr1[i]; {
i++; scanf("%d", &arr1[i]);
k++; }
}
/* Some elements in array 'arr2' are still remaining where as array 'arr1' is printf("\nEnter no of elements in 2nd array :\n");
exhausted */ scanf("%d", &n2);
while (j < n2) printf("Enter elements of 2nd array : \n");
{ for (i = 0; i < n2; i++)
res[k] = arr2[j]; {
k++; scanf("%d", &arr2[i]);
j++; }
}
sort(res, (n1+n2)); merge(arr1, arr2, n1, n2);
//Displaying elements of array 'res' return 0;
printf("\nMerged array is :"); }
for (i = 0; i < n1 + n2; i++)
printf("\n%d", res[i]);
}
ADVANTAGES, DISADVANTAGES AND APPLICATIONS
OF ARRAY
• Advantages of Arrays
• Arrays represent multiple data items of the same type using a single name.
• In arrays, the elements can be accessed randomly by using the index number.
• Arrays allocate memory in contiguous memory locations for all its elements. Hence there is no chance of extra memory being allocated in case of
arrays. This avoids memory overflow or shortage of memory in arrays.
• Disadvantages of Arrays
• The number of elements to be stored in an array should be known in advance.
• An array is a static structure (which means the array is of fixed size). Once declared the size of the array cannot be modified. The memory which is
allocated to it cannot be increased or decreased.
• Insertion and deletion are quite difficult in an array as the elements are stored in consecutive memory locations and the shifting operation is costly.
• Allocating more memory than the requirement leads to wastage of memory space and less allocation of memory also leads to a problem.
• Applications of Arrays
• Array stores data elements of the same data type.
• Maintains multiple variable names using a single name. Arrays help to maintain large data under a single variable name. This avoid the confusion of
using multiple variables.
• Arrays can be used for sorting data elements. Different sorting techniques like Bubble sort, Insertion sort, Selection sort etc use arrays to store and sort
elements easily.
• Arrays can be used for performing matrix operations. Many databases, small and large, consist of one-dimensional and two-dimensional arrays whose
elements are records.
• Arrays can be used for CPU scheduling.
• Lastly, arrays are also used to implement other data structures like Stacks, Queues, Heaps, Hash tables etc.
THANK YOU !!

You might also like