PoP Arrays 2023
PoP Arrays 2023
PoP Arrays 2023
MODULE -3 ARRAYS
INTRODUCTION
•An array is a collection of similar data elements.
•These data elements have the same data type.
•The elements of the array are stored in consecutive memory locations and are
referenced by an index (also known as the subscript).
•Declaring an array means specifying three things:
The data type- what kind of values it can store ex, int, char, float
Name- to identify the array
The size- the maximum number of values that the array can hold
•Arrays are declared using the following syntax:
type name[size];
1 Dept. of CSE,CBIT,KOLAR
Principles of Programming using C 2023
Traversing an Array
Traversing an array means accessing each and every element of the array for a
specific purpose.
3 Dept. of CSE,CBIT,KOLAR
Principles of Programming using C 2023
Variables used:
i : Loop counter or counter variable for the for loop.
arr : Array name.
LB : Lower bound. [ The index value or simply index of the first element of an array is
called its lower bound ]
UB : Upper bound. [ The index of the last element is called its upper bound ]
4 Dept. of CSE,CBIT,KOLAR
Principles of Programming using C 2023
Implementation in C:
writing a program in C to perform traverse operation in array
void main()
{
int i, size;
int arr[] = {1, -9, 17, 4, -3}; //declaring and initializing array "arr"
5 Dept. of CSE,CBIT,KOLAR
Principles of Programming using C 2023
}
Output:
The array elements are:
arr[0]= 1
arr[1]= -9
arr[2]= 17
arr[3]= 4
arr[4]= -3
void main()
{
int i,n,a[100];
printf("element - %d : ",i);
scanf("%d",&a[i]);
}
printf("\nThe values store into the array are : \n");
for(i=0;i<n;i++)
{
printf("% 5d",a[i]);
}
7 Dept. of CSE,CBIT,KOLAR
Principles of Programming using C 2023
8 Dept. of CSE,CBIT,KOLAR
Principles of Programming using C 2023
9 Dept. of CSE,CBIT,KOLAR
Principles of Programming using C 2023
10 Dept. of CSE,CBIT,KOLAR
Principles of Programming using C 2023
Step 1:Input the size of the array arr[] using num, and then declare the pos variable to
define the position, and i represent the counter value.
Step 2: Use a loop to insert the elements in an array until (i < num) is satisfied.
Step 3:Now, input the position of the particular element that the user or programmer
wants to delete from an array.
11 Dept. of CSE,CBIT,KOLAR
Principles of Programming using C 2023
Step 4:Compare the position of an element (pos) from the total no. of elements (num+1).
If the pos is greater than the num+1, the deletion of the element is not possible and jump
to step 7.
Step 5:Else removes the particular element and shift the rest elements' position to the left
side in an array.
Step 6: Display the resultant array after deletion or removal of the element from an array.
int main ()
{
// declaration of the int type variable
int arr[50];
int pos, i, num; // declare int type variable
printf (" \n Enter the number of elements in an array: \n ");
scanf (" %d", &num);
Output:
Enter the number of elements in an array:
8
13 Dept. of CSE,CBIT,KOLAR
Principles of Programming using C 2023
In the above program, we input 8 elements for an array arr[] from the user. After
that, the user enters the position of the particular element is 5.
And then, we checked the defined position by the If statement (if (pos > num + 1));
Here, 5 is less than the (num+1). So the condition is false, and it executes the else
block to remove the 5th position of the element is 10 using for loop and then prints
the resultant array.
The following algorithm deletes a data element from a specific position pos (position specified
by the programmer) of a linear array ‘a‘.
14 Dept. of CSE,CBIT,KOLAR
Principles of Programming using C 2023
It’s only because, When you shift an element one position backward (left), the element
that already present in that position (position where you are shifting the element) gets
changed. And the value that you are shifting towards left gets copied or overwritten at
that position.
Subsequently, after shifting all such values which are present right to the element which
we wish to delete, When we reach to the position from where we have to delete the
element then, we don’t shift the element which is present at that position or all such
elements which are present left from that position to the left of it backward.
And, since we are shifting only those elements which are present ahead (right) from that
position.
So at the end, the value of that position will change and the value next to it will come at
that position. And in that case the already existing value will be removed .
As a result, the size of the array will now be reduced by one, due to the removal of one
element from the array.
15 Dept. of CSE,CBIT,KOLAR
Principles of Programming using C 2023
Visual Representation
16 Dept. of CSE,CBIT,KOLAR
Principles of Programming using C 2023
size = sizeof(a)/sizeof(a[0]);
printf("\nEnter the position from where you wish to delete the element: ");
scanf("%d", &pos);
size = size - 1;
}
Output:
The array elements before deletion operation:
a[0] = 2
a[1] = 4
a[2] = 6
a[3] = 8
a[4] = 12
Enter the position from where you wish to delete the element: 3
a[1] = 4
a[2] = 8
a[3] = 12
Write a C program to merge two sorted array elements into a single array.
Problem Solution
1. Create two arrays of some fixed size and define their elements in sorted fashion.
2. Take two variables i and j, which will be at the 0th position of these two arrays.
3. Elements will be compared one by one using i and j in for loop, and whichever element is
smaller than the other, that element will get inserted to final array and the position(either i or j)
will move by one, whereas the other array’s track position will remain in that same place.
4. Above work will be done till we reach the end of either array. After that, one of the array
whose elements are still to be added, its elements will get straightaway added to the final array.
Method 1: Merge Two Sorted Arrays in C using For Loop (Naive Approach)
In this approach, we will use a for loop to iterate through the array and merge the two arrays.
Example:
First Array = [12, 18, 23]
Second Array = [13, 19, 27]
Merged Array = [12, 13, 18, 19, 23, 27]
18 Dept. of CSE,CBIT,KOLAR
Principles of Programming using C 2023
Output
1 2 3 4 5 6 7 8 9 10
19 Dept. of CSE,CBIT,KOLAR
Principles of Programming using C 2023
Example:
First Array = [12, 18, 23]
Second Array = [13, 19, 27]
Merged Array = [12, 13, 18, 19, 23, 27]
/*
* C Program to merge two sorted arrays using for loop
*/
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int i, n, j, k;
printf("Enter the size of the first array: ");
scanf("%d", &n);
int arr1[n];
printf("Enter the elements of the first array: \n");
for (i = 0; i < n; i++)
{
scanf("%d", &arr1[i]);
}
printf("Enter the size of the second array: ");
scanf("%d", &k);
int arr2[k];
printf("Enter the elements of the second array: \n");
for (j = 0; j < k; j++)
{
scanf("%d", &arr2[j]);
}
int arr3[n + k];
i = j = 0;
int in;
for (in = 0; in < n + k; in ++)
{
if (i < n && j < k)
{
if (arr1[i] < arr2[j])
{
arr3[in] = arr1[i];
20 Dept. of CSE,CBIT,KOLAR
Principles of Programming using C 2023
i++;
}
else
{
arr3[in] = arr2[j];
j++;
}
}
else if (i < n)
{
arr3[in] = arr1[i];
i++;
}
else
{
arr3[in] = arr2[j];
j++;
}
}
printf("The merged array is: \n");
for (in = 0; in < n + k; in++)
{
printf("%d ", arr3[in]);
}
printf("\n");
return 0;
}
Output:
Enter the size of the first array: 3
Enter the elements of the first array:
12
18
23
Enter the size of the second array: 3
Enter the elements of the second array:
13
19
27
The merged array is:
12 13 18 19 23 27
21 Dept. of CSE,CBIT,KOLAR
Principles of Programming using C 2023
Linear Search
A linear search or sequential search is a method for finding an element within a list. It
sequentially checks each element of the list until a match is found or the whole list has been
searched.
Or
Linear search is a very basic and simple search algorithm. In Linear search, we search an
element or value in a given array by traversing the array from the starting, till the desired
element or value is found.
#include<stdio.h>
#include<stdlib.h>
void main( )
{
int n, a[100], i, key,loc;
loc=-1;
printf("Enter the size of the array\n");
scanf("%d",&n);
printf("Enter the elements of array in sorted order\n");
for(i=0;i<n;i++)
22 Dept. of CSE,CBIT,KOLAR
Principles of Programming using C 2023
scanf("%d",&a[i]);
printf("Enter the key element to be searched\n");
scanf("%d",&key);
for(i=0;i<n;i++)
{
if(key == a[i]
{
loc=i+1;
break;
}
if(loc>=0)
printf("The element %d is found at %d \n",ele,loc);else
printf("The search is unsuccessful\n");
}
Binary Search
Binary search works only on a sorted set of elements.To use binary search on a
collection, the collection must first be sorted.
The array is divided into two parts,compared with middle element if it is not successful,
then it is compared whether it is lesser or greater than middle element. If it is lesser,
search is done towards left part else right part.
#include<stdio.h>
#include<stdlib.h>
void main( )
{
int n, a[100], i, key, loc, high, low, mid; loc=-1;
printf("Enter the size of the array\n"); scanf("%d",&n);
printf("Enter the elements of array in sorted order\n"); for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("Enter the key element to be searched\n"); scanf("%d",&key);
low=0; high=n-1;
while(low<=high)
{
mid=(low+high)/2;
if(key==a[mid])
{
loc = mid+1; break;
23 Dept. of CSE,CBIT,KOLAR
Principles of Programming using C 2023
}
else
{
if(ele<a[mid])
high=mid-1;
else
low=mid+1;
}
}
if(loc>=0)
printf("The element %d is found at %d \n",ele,loc); else
printf("The search is unsuccessful\n");
}
Two-Dimensional Arrays: A list of items can be given one variable name using two
subscripts and such a variable is called a single subscripted variable or one dimensional
array.
It consists of both rows and columns. Ex: Matrix.
Declaration of Two-Dimensional Array: Here is general syntax for array declaration along
with examples.
24 Dept. of CSE,CBIT,KOLAR
Principles of Programming using C 2023
1. Compile-time initialization
2. Run-time initialization
Note: in the above examples we are storing values in marks array and
temperature array respectively. The pictorial representation is also given
below
After initialization the arrays appear as follows:
29.5 30.5
marks 1 2 3 4 city_temp
35.6 45.7
5 6 7 8
25 Dept. of CSE,CBIT,KOLAR
Principles of Programming using C 2023
012 1234
a b
345 5678
67 8 9 10 11 12
{
for(j=0; j<2; j++)
printf("%d ", arr[i][j]);
printf("\n");
}
getch();
return 0;
}
Output:
Output:
Enter Row Size of Array(max.10): 2
Enter column Size of Array(max.10): 4
Enter 10 Array Elements:
1 2 3 4 5 6 7 8 9 10
The Array is
1 2 3 4
5 6 7 8
Two dimentsional arrays can be used to implement the mathematical concept of matrices.
The following operations can be performed on m x n matrix
Sum:Two matrices that are compatible (matching with number of rows and columns) with
each other can be added together thereby storing the result in the third matrix.
Ci,j=Ai,j + Bi,j
Difference: Two matrices that are compatible (matching with number of rows and columns)
with each other can be subtracted thereby storing the result in the third matrix.
Ci,j=Ai,j - Bi,j
Product : Two matrices can be multiplied with each othr if the number of columns in the first
matrix is equal to the number of rows in the second matrix.
Therefore m x n martrix A can be multiplied with a p xq matrix if n=p elements of the matrics
can be multipled by writing
Write a program to input two mxn matrices and the calculate the sum of their corresponding elements
and store it in a third m x n matrix.
#include <stdio.h>
void main()
{
int arr1[50][50],brr1[50][50],crr1[50][50],i,j,n;
for(j=0;j<n;j++)
crr1[i][j]=arr1[i][j]+brr1[i][j];
printf("\nThe Addition of two matrix is : \n");
for(i=0;i<n;i++){
printf("\n");
for(j=0;j<n;j++)
printf("%d\t",crr1[i][j]);
}
printf("\n\n");
}
Sample Output:
Addition of two Matrices :
------------------------------
Input the size of the square matrix (less than 5): 2
Input elements in the first matrix :
element - [0],[0] : 1
element - [0],[1] : 2
element - [1],[0] : 3
element - [1],[1] : 4
Input elements in the second matrix :
element - [0],[0] : 5
element - [0],[1] : 6
element - [1],[0] : 7
element - [1],[1] : 8
Consider above example, first element in resulting matrix prod[0,0] can be computed by multiplying first row of
first matrix i.e. (1, 3, 2) with first column of second matrix i.e. (2, 1, 1) and finally sum all the product of
elements i.e. (1*2) + (3*1) + (2*1) = 7. Similarly, second entry prod[0,1] can be computed by multiplying the
first row of the first matrix with the second column of the second matrix and sum all the product.
Two matrices can be multiplied if and only if they satisfy the following condition:
The number of columns present in the first matrix should be equal to the number of rows present in
the second matrix.
Suppose dimension of matrix A is p × q and matrix B is q × r, then the dimension of resulting matrix
will be p × r. Matrix multiplication can be represented as
Cij = Σ AikBkj
#include<stdio.h>
#include<stdlib.h>
int main( )
{
int m,n,p,q,row,col,k,a[3][3],b[3][3],c[3][3];
printf("Enter the order of matrix A\n");
scanf("%d%d",&m,&n);
printf("enter order of matrix B\n");
scanf("%d%d",&p,&q);
if(n!=p)
{
printf("Matrix Multiplication is not possible\n");exit(0);
printf("\n");
}
printf("The elements of matrix B are\n");
for(row=0;row<p;row++)
{
for(col=0;col<q;col++)
{
printf("%3d",b[row][col]);
}
printf("\n");
}
printf("Product of Matrix A and B is\n");
for(row=0;row<m;row++)
{
for(col=0;col<q;col++)
{
printf("%3d",c[row][col]);
}
printf("\n");
}
}
Output:
3 4
Elements of matrix B are
5 6
7 8
Let us take an example program that uses a function square( ) to calculate square of
numbers stored in an array. In this program each array element is passed one by one.
Example-1 cont’d:
Example-1 void square(int no )
int square(int);void
{
main( )
int sq;
{
sq=no*no; /*square is calculated*/
int num[5], i;
square(num[i]);
} Output:
This diagram clearly illustrates how each individual element of array num[ ] is passed to
function square through parameter no.
3 4 8 9 10
0 1 2 3 4 num[3]=9 no
num[1]=4 copied no
num[0]=3 copied to no
num[2]=8 no
Next program illustrates how to pass an entire array to a function average( ) and
calculate average marks. First sum of all the elements of array marks
avg1=average(marks); sum=sum+score[i];
printf(“average=%f”, avg1) }
} avg=sum/5;
return (avg);
}
Output:
average=71.000000
In the above example each value of array marks[ ] is copied to array scores[ ] as shown
below:
marks[0]=35 copied to scores[0]
71.000000
Multi Dimensional Arrays: Multidimensional arrays can have three, four ormore
dimensions.
A three-dimension array is an array of two dimensional arrays. It has row, column
and depth associated with it.
Declaring multidimensional arrays
int table[3][5][4];
#include <stdio.h>
int main(void)
{
38 Dept. of CSE, CBIT,KOLAR
Principles of Programming using C 2023
Applications of Arrays
Arrays are widely used to implement mathematical vectors, matrices and other kinds of
rectangular tables.
Many databases include one dimensional arrays whose elements are records.
Arrays are also used to implement other data structures such as strings , stacks queues , heaps,
and hash tables.
Arrays can be used for sorting elements in ascending or descending order.