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

Unit 2 Array

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 18

UNIT II ARRAYS AND STRINGS

Introduction to Arrays: Declaration, Initialization – One dimensional array – Example


Program: Computing Mean, Median and Mode - Two dimensional arrays – Example
Program: Matrix Operations (Addition, Scaling, Determinant and Transpose) – String
operations: length, compare, concatenate, copy – Selection sort, linear and binary search.

INTRODUCTION TO ARRAYS:
An array is a collection of similar data items that are stored under a common name.
Array is defined as finite ordered collection of similar data, stored in contiguous
(continues) memory locations.
It is a derived data type in C.
What is the use of array?
A single variable cannot store multiple values . But an array can store multiple values of
same data type in one single name.
Example where arrays are used,
 to store roll numbers of the students in a class
 to store marks of a students
 to store list of names of employees etc..

Array can store integer, float and double values which is said to be integer array.
Array that is used to store characters are said to be Character array.
Features of array:
Array might be belonging to any of the data types
Array size must be a constant value.
Array index starts with 0 and ends with n-1.
Element of an array is accessed using index or subscript.
Always, Contiguous (adjacent) memory locations are used to store array elements in
memory.
It is a best practice to initialize an array to zero or null while declaring, if we don’t
assign any values to array.
Advantage of array:
 Code Optimization: Less code is required, one variable can store numbers of
value.
 Easy to traverse data: By using array easily retrieve the data of array.
 Easy to sort data: Easily sort the data using swapping technique.
 Random Access: With the help of array index you can randomly access any
elements from array.
Types of an array:
1. Single dimensional array
2. Multi dimensional array
Single(one)dimensional array:
 Array having only one subscript [ ] variable is called One-Dimensional array.
 It is also called as Single Dimensional Array or Linear Array or list.
 The elements of one dimensional array is also called as linear array
Declaring Array:
data_type array_name[size];
Example:
int roll_num[100];
char name[50];
double balance[10];
Initialization of an Array:
 After an array is declared it must be initialized.
 An array can be initialized in 2 ways (i) Compile time initialization
(ii)Run time initialization
(i) Compile time Array initialization:
- Compile time initialization of array elements is same as ordinary variable
initialization.
Syntax:
data type array_name[size] = { list of values };
Example:
int marks[4]={ 67, 87, 56, 77 }; //integer array initialization
float area[5]={ 23.4, 6.8, 5.5 }; //float array initialization
double balance[10]={1000.0,20.0,3.4,7.2,50.0}
char str[10]={‘H’,‘a’,‘i’}; // character array
Accessing Array Elements:
We can access array elements with the help of index value of element.
Example:
int marks[50]={10,20,30,15,12}
here, marks is the array name and [50] is the maximum number of elements the array can
hold.
Printing array of numbers(Compile time initialization) Output:
#include<stdio.h> the elements in the
int main() array are
{ 95
int arr[40]={95,58,45,78}; 58
int i; 45
printf("the elements in the array are\n"); 78
for(i=0;i<=3;i++)
{
printf("%d\n", arr[i]);
}
return(0);
}
Note: [40] is the maximum size the array can hold.
(ii)Runtime Array initialization:
- An array can also be initialized at runtime using scanf() function.
- This approach is usually used for initializing large array elements , or to
initialize array by getting the input from the user.
Syntax:

for(i=0;i<n;i++)
{
scanf(“%d”,&arr[i]);
}
Reading and Printing array of elements( Run Time Output:
initialization) enter the size of an
#include<stdio.h> array
int main() 5
{ enter the elements of
int arr[100],n,i; an array
printf("enter the size of an array\n"); 45
scanf("%d",&n); 45
printf("enter the elements of an array\n"); 78
for(i=0;i<=n-1;i++) 4
{ 12
scanf("%d",&arr[i]); the elements are
} 45
printf("the elements are\n"); 45
for(i=0;i<=n-1;i++) 78
{ 4
printf("%d\n",arr[i]); 12
}
return(0);
}
Operations on 1D array:
1. Subscripting an 1D array
It is an action of selecting an element from an array.
printf(“%d”, a[5]);
2. Assigning an array to another array
A variable can be assigned to another variable but array can’t be assigned to
another array directly.
Output:
#include<stdio.h> //compilation error
int main()
{
int a[3], b[3]={1,2,3};
a[3]=b[3];
printf(“%d”, a[0]);eturn(0);
}

Example Programs: (using One Dimensional Array)


C program to find sum of array of elements: Output:
#include<stdio.h> Enter the size of
int main() array:
{ 4
int i, arr[20], n, sum=0; Enter the values:
printf("Enter the size of array:\n"); 2
scanf("%d",&n); 5
printf("Enter the values:\n"); 1
for(i=0;i<n;i++) 12
{
scanf("%d",&arr[i]);
}
for(i=0;i<n;i++)
{
sum=sum+arr[i];
}
printf("the sum of the array is %d",sum);
return(0);
}
C Program to find the largest element in an array: Output:
#include<stdio.h> enter the size of an
int main() array :3
{ enter the elements of
int arr[10]; an array
int large,i,n; 23
printf("enter the size of an array :"); 2
scanf("%d",&n); 15
printf("enter the elements of an array\n"); largest element is: 23
for(i=0;i<=n-1;i++)
{
scanf("%d",&arr[i]); Note:
} Can also try the size
large=arr[0]; of array and
for(i=1;i<=n-1;i++) elements of array by
{ getting input from
if(arr[i]>large) user.
large=arr[i];
}
printf("largest element is: %d\n",large);
return(0);
}
Note:
(Same can be done to find the smallest element also. use < to
find smallest element)
Program to insert an element in an array at specific position Output:
#include<stdio.h> enter the position
int main() where the new
{ element to be inserted
int arr[50]={10,20,30,40,50},i,pos,element; 2
printf("enter the position where the new element to be enter the new element
inserted\n"); to be inserted
scanf("%d",&pos); 25
printf("enter the new element to be inserted\n"); after
scanf("%d",&element); insertion ,elements
for(i=4;i>=pos;i--) are
{ 10
arr[i+1]=arr[i]; //moving the elements 20
} 25
arr[pos]=element; 30
printf("after insertion ,elements are\n"); 40
for(i=0;i<=5;i++) 50
{
printf("%d\n",arr[i]);
}
return(0);
}
C program to delete an element in an array: Output:
#include<stdio.h> Enter the size of an
int main() array
{ 4
int n, a[10],i,pos; Enter the array
printf("Enter the size of an array\n"); elements
scanf("%d",&n); 23
printf("Enter the array elements\n"); 12
for(i=0;i<n;i++) 5
{ 47
scanf("%d",&a[i]); Enter the position to
} be deleted
printf("Enter the position to be deleted\n"); 1
{ After deletion:
scanf("%d",&pos); 23
} 5
if(pos>=n) 47
{
printf("deletion is not possible");
}
else
{
for(i=pos;i<n-1;i++)
{
a[i]=a[i+1];
}
}
printf("After deletion:\n");
for(i=0;i<n-1;i++)
{
printf("%d\n",a[i]);
}
return(0);
}
C program to display elements in Descending order: Output:
#include <stdio.h> Enter the size of
int main() array: 5
{ Enter the elements of
int arr[50],n,i,j; array:
int temp; 2
printf("Enter the size of array: "); 6
scanf("%d",&n); 8
printf("Enter the elements of array:\n"); 9
for(i=0;i<=n-1;i++) 1
scanf("%d",&arr[i]); Array elements after
sorting:
for(i=0;i<=n-1;i++) 9
{ 8
for(j=i+1;j<=n-1;j++) 6
{ 2
if(arr[i]<arr[j]) //sort array 1
{
temp =arr[i];
arr[i] =arr[j];
arr[j] =temp;
}
}
}
printf("\nArray elements after sorting:\n");
for(i=0;i<=n-1;i++)
{
printf("%d\n",arr[i]);
}
return 0;
}

Illustrative Programs:
Searching: Searching is a process of finding a particular element in a given list.
Types:
1. Linear search
2. Binary search
Linear Search
- It is a process of finding an element in the list from the beginning and continues till
the end of the list.
Concept of linear Search:
i. To search an element we want, we start with the first element in the list. If this is the
required element, our search is over.
ii. Else, we take up the second element and see if this is the element we search for.
iii. If this is too not the element, we pick up the third element and compare.
iv. This process continues until the element we search for is found.
Advantages:
 The linear search is simple - It is very easy to understand and implement;
 It does not require the data in the array to be stored in any particular order.
Disadvantages:
The linear search is inefficient(takes more time) if the list has more number of elements.
C program to perform Linear Search:
#include<stdio.h> Output:
int main() Enter the number of
{ elements in array
int array[100], item, i, n, found=0; 4
printf("Enter the number of elements in array\n"); Enter the elements
scanf("%d",&n); 6
printf("Enter the elements \n", n); 12
for (i = 0; i < n; i++) 5
scanf("%d", &array[i]); 8
Enter the element to
printf("Enter the element to search\n"); search
scanf("%d", &item); 5
5 is present in array and
for (i = 0; i <=n-1; i++) position is 2
{
if (array[i] == item) // if required element found
{
found=1;
break;
}
}
if (found==1)
printf("%d is present in array and position is %d\n", item,i);
else
printf("%d is not present in array.\n", item);
return 0;
}
Binary Search:
 Binary search is an algorithm used to find an element in an sorted array by using the
divide and conquer concept.
 This method can be applied only if list is in sorted order.
 List is divided into two halves separated by middle element.
Left half Middle Right half
Concept of Binary search:
i. Find the middle element
ii. Check the middle element with the element to be found
iii. If the middle element is equal to that element, then it will provide the output.
iv. If the value is not same, then it will check whether the middle element value is less
than or greater than the element to be found.
v. If the value is less than that element, then the search will start with the elements next
to the middle element.
vi. If the value is high than that element, then the search will start with the elements
before to the middle element.
vii. This process continues, until that particular element has been found.
Example: Consider the following set of elements in array where 31 is the element to be
searched.

Middle =(First+Last)/2 =>(0+9)/2 =4.5=>4

Now we compare the value stored at location 4, with the value being searched, i.e. 31. We
find that the value at location 4 is 27, which is not a match. As the value is greater than 27
and we have a sorted array, so we also know that the target value must be in the upper
portion of the array.

We change our low to mid + 1 and find the new mid value again.
Like this searching continues until we find the desired element.

Advantages:
 Faster than linear search.
Disadvantages :
 Binary search algorithm can work only with the sorted array (either ascending or
descending order).
 It is time consuming and waste of memory allocation.
If the element to be identified occurs more than once, then it will show the occurrence of the first one.
Program for Binary search: Output:
#include <stdio.h>
int main() enter size of array
{ 6
int i, first, last, middle, n, item, arr[50]; enter the elements
printf("enter size of array"); 5
scanf("%d",&n); 12
printf("enter the elements\n"); 4
for (i = 0; i <=n-1; i++) 7
{ 18
scanf("%d",&arr[i]); 240
} Enter element to find
printf("Enter element to find\n"); 18
scanf("%d", &item); 18 found at location 4
first = 0;
last = n - 1;
middle = (first+last)/2;
while (first <= last)
{
if (arr[middle] < item)
{
first = middle + 1;
}
else if (arr[middle] == item)
{
printf("%d found at location %d.\n", item, middle);
break;
}
else
{
last = middle - 1;
middle = (first + last)/2;
}
if (first > last)
printf("%d is not present in the list\n", item);
return (0);
}
Selection Sort:
The selection sort algorithm sorts an array by repeatedly finding the minimum element
(considering ascending order) from unsorted part and putting it at the beginning.
The algorithm maintains two subarrays in a given array.
1) The subarray which is already sorted.
2) Remaining subarray which is unsorted.
In every iteration of selection sort, the minimum element (considering ascending order)
from the unsorted subarray is picked and moved to the sorted subarray.
Consider the following example:

Program to perform selection sorting (ascending order) Output:


#include <stdio.h> Enter the size of array: 5
int main() Enter the elements of array:
{ 1
int arr[50],n,i,j; 6
int temp; 4
printf("Enter the size of array: "); 6
scanf("%d",&n); 1
printf("Enter the elements of array:\n"); Array elements after sorting:
for(i=0;i<=n-1;i++) 1
scanf("%d",&arr[i]); 1
4
for(i=0;i<=n-1;i++) 6
{ 6
for(j=i+1;j<=n-1;j++)
{
if(arr[i]>arr[j]) //sort array
{
temp =arr[i];
arr[i] =arr[j];
arr[j] =temp;
}
}
}
printf("\nArray elements after sorting:\n");
for(i=0;i<=n-1;i++)
{
printf("%d\n",arr[i]);
}
return (0);
}
Computing Mean, Median
Mean: The average of a set of numbers.
The mean is the usual average, so I'll add and then divide:
(13 + 18 + 13 + 14 + 13 + 16 + 14 + 21 + 13) ÷ 9 = 15
Median: The middlemost number in a set of number arranged in order.
The median is the middle value, so first I'll have to rewrite the list in numerical order:
13, 13, 13, 13, 14, 14, 16, 18, 21
There are nine numbers in the list, so the middle one will be the (9 + 1) ÷ 2 = 10 ÷ 2 = 5th
number:
13, 13, 13, 13, 14, 14, 16, 18, 21
So the median is 14.
Mode: Mode is the number that is repeated more often than any other, so 13 is the mode.

C program to create mean and median of array of Output:


elements enter size of array
#include <stdio.h> 5
int main() enter the elements
{ 6
int i,j,a[20], sum=0,n,temp,b[20]; 4
float mean=0.0, median=0.0; 3
printf("enter size of array\n"); 2
scanf("%d",&n); 4
printf("enter the elements\n"); mean value is
for (i = 0; i <=n-1; i++) 3.800000median is 4.000000
{
scanf("%d",&a[i]);
sum=sum+a[i]; //Calculating mean
}
mean=(float)sum/(float)n;
printf("mean value is %f",mean);
for(i=0;i<=n-1;i++)
{
for(j=i+1;j<=n-1;j++) //calculating median
{
if(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
if(n%2==0)
median=(float)(a[n/2]+a[(n-1)/2])/2;
else
median=a[(n-1)/2];
printf("median is %f",median);
}
Two dimensional Arrays:( Multidimensional Arrays
- In 2-dimentional array, elements are arranged in row and column format.
- An array with two subscripts[ ][ ] is termed as two dimensional arrays.
- A two dimensional array enables us to store multiple rows of elements, in form of
matrix.
Array Declaration Syntax:
data_type arr_name [num_of_rows][num_of_column];

Example:
int arr[2][2];
- this array can hold 2*2=4 elements totally.
Array Initialization:
(i) Compile time Initialization
Array Initialization Syntax:
data_type arr_name[2][2] = {{0,0},{0,1},{1,0},{1,1}};
Example:
int arr[2][2] = {1,2, 3, 4};
int arr[2][3] = { {0,0,0}, {1,1,1} };
int arr[2][3] = { 0,0,0, 1,1,1 };
Array accessing syntax:
arr_name[index];
Example:
int arr[2][2] = {1,2, 3, 4};
arr [0] [0] = 1;
arr [0] ]1] = 2;
arr [1][0] = 3;
arr [1] [1] = 4;
Invalid initializations:
Following initializations are wrong and invalid.
int arr[2][ ]={1,2,3,4}; // We need to mention the column size.
Otherwise compiler do not know where the first row size ends.
ii) Run Time initialization:
Syntax:
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
scanf(“%d”,a[i][j]);
}
}
Programs on two dimensional arrays:
C Program To read and display 2 dimensional matrix Output:
#include <stdio.h> enter the size of row and
int main() column
{ 3
int a[10][10]; 3
int i,j,m,n; enter the elements of
printf("enter the size of row and column\n"); matrix
scanf("%d%d",&m,&n); 5
printf("enter the elements of matrix\n"); 2
for(i=0;i<=m-1;i++) 5
{ 2
for(j=0;j<=n-1;j++) 5
{ 2
scanf("%d",&a[i][j]); 5
} 2
} 5
printf("the elements are\n"); the elements are
for(i=0;i<=m-1;i++) 5 2 5
{ 2 5 2
for(j=0;j<=n-1;j++) 5 2 5
{
printf("%d\t",a[i][j]);
}
printf("\n");
}
return(0);
}
Program for Matrix Addition: Output:
#include <stdio.h> Enter the size of row and
int main() column
{ 2
int a[10][10], b[10][10]; // array declaration for matrix a&b 2
int c[10][10]={0}; // c matrix initialized to 0 Enter the elements of A
int i,j,m,n; matrix
printf("Enter the size of row and column\n"); 1
scanf("%d%d",&m,&n); //reading size or row and column 3
printf("Enter the elements of A matrix\n"); 2
for(i=0;i<=m-1;i++) 5
{ Enter the elements of B
for(j=0;j<=n-1;j++) matrix
{ 1
scanf("%d",&a[i][j]); //getting the elements of A matrix 5
} 5
} 6
printf("Enter the elements of B matrix\n"); Sum of two matrices:-
for(i=0;i<=m-1;i++) 2 8
{ 7 11
for(j=0;j<=n-1;j++)
{
scanf("%d", &b[i][j]); //getting the elements of B matrix
}
}
printf("Sum of two matrices:-\n");
for(i = 0;i<=m-1;i++)
{
for(j=0;j<=n-1;j++)
{
c[i][j] = a[i][j] + b[i][j]; // addition of A and B matrix
printf("%d\t", c[i][j]);
}
printf("\n");
}
return(0);
}
Same program can be written for matrix subtraction with - sign c[i][j] = a[i][j] - b[i][j];

Matrix multiplication: Output:


#include<stdio.h> enter the size
int main() 2
{ 2
int i, j, k,m,n; Enter A matrix
int a[10][10], b[10][10]; 2
int c[10][10]={0}; 2
printf("enter the size"); 2
scanf("%d%d",&m,&n); 2
printf("Enter A matrix\n"); Enter B matrix
for (i = 0; i <=m-1; i++) 2
{ 2
for (j = 0; j <=n-1; j++) 2
{ 2
scanf("%d", &a[i][j]); The product of matrix is
} 8 8
} 8 8
printf("Enter B matrix\n");
for (i = 0; i <= m-1; i++)
{
for (j = 0; j <=n-1; j++)
{
scanf("%d", &b[i][j]);
}
}
printf("The product of matrix is\n");
for (i = 0; i <=m-1; i++)
{
for (j = 0; j <=n-1; j++)
{
for (k = 0; k <=m-1; k++)
{
c[i][j] = c[i][j] + a[i][k]*b[k][j];
}
printf("%d\t", c[i][j]);
}
printf("\n");
}
return(0);
}
C Program to perform scalar multiplication: Enter Rows and Columns of
#include <stdio.h> Matrix
int main() 2
{ 2
int a[50][50]; enter the elements of matrix
int m, n, i, j, scalar; 2
printf("Enter Rows and Columns of Matrix\n"); 1
scanf("%d %d", &m, &n); 3
5
printf("enter the elements of matrix\n"); Enter a scalar number to
for(i = 0; i <=m-1; i++) multiply with matrix
for(j = 0; j <=n-1; j++) 5
scanf("%d", &a[i][j]); Product Matrix is
10 5
printf("Enter a scalar number to multiply with matrix \n"); 15 25
scanf("%d", &scalar);
/* Multiply each element of matrix with scalar*/
for(i = 0; i <= m-1; i++)
{
for(j = 0; j <=n-1; j++)
{
a[i][j] = a[i][j]*scalar;
}
}

printf("Product Matrix is\n");


for(i= 0; i <=m-1; i++)
{
for(j = 0; j<=n-1; j++)
printf("%d ", a[i][j]);
}
printf("\n");
return(0);
}
C Program to TRANSPOSE a matrix: Output:
#include <stdio.h> Enter the SIZE of the matrix
int main() 2
{ 3
int a[10][10], i, j, m, n; Enter the ELEMENTS of the
printf("Enter the SIZE of the matrix \n"); matrix
scanf("%d %d", &m, &n); 2
printf("Enter the ELEMENTS of the matrix\n"); 1
for (i = 0; i <= m-1; i++) 5
{ 3
for (j = 0; j<= n-1; j++) 7
{ 8
scanf("%d", &a[i][j]); The given matrix is
} 215
} 378
printf("The given matrix is \n"); Transpose of matrix is
for (i = 0; i <=m-1; ++i) 23
{ 17
for (j = 0; j <= n-1; ++j) 58
{
printf(" %d", a[i][j]);
}
printf("\n");
}
printf("Transpose of matrix is \n");
for (j = 0; j <=n-1; j++) //interchanging rows and
columns
{
for (i = 0; i <=m-1; i++)
{
printf(" %d", a[i][j]);
}
printf("\n");
} return(0);
}
C program to find determinant of 2*2 Matrix :
#include<stdio.h>
int main()
{ Example:
int a[2][2],i,j; Output:
long determinant;
printf("Enter the elements of matrix:\n "); Enter the elements of matrix:
for(i=0;i<2;i++) 8
for(j=0;j<2;j++) 3
scanf("%d",&a[i][j]); 2
1
printf("\nThe matrix is\n"); The matrix is
for(i=0;i<2;i++) 8 3
{ 2 1
printf("\n"); Determinant is :2
for(j=0;j<2;j++)
printf("%d\t",a[i][j]);
}
determinant = a[0][0]*a[1][1] - a[1][0]*a[0][1];
printf("\nDeterminant is :%ld",determinant);
return(0);
}
Determinant of 3*3 matrix Enter the elements of
#include<stdio.h> matrix: 1
int main() 5
{ 4
int a[3][3],i,j; 2
int determinant=0; 1
printf("Enter the elements of matrix: "); 2
for(i=0;i<3;i++) 1
for(j=0;j<3;j++) 2
scanf("%d",&a[i][j]); 1
printf("\nThe First matrix is\n");
for(i=0;i<3;i++) The First matrix is
{
printf("\n"); 1 5 4
for(j=0;j<3;j++) 2 1 2
printf("%d\t",a[i][j]); 1 2 1
} Determinant of matrix is: 9
for(i=0;i<3;i++)
determinant = determinant + (a[0][i]*(a[1]
[(i+1)%3]*a[2][(i+2)%3] - a[1][(i+2)%3]*a[2][(i+1)%3]));
printf("\nDeterminant of matrix is: %d",determinant);
return(0);
}
Three Dimensional array:
Total number of elements that can be stored in a multidimensional array can be calculated
by multiplying the size of all the dimensions.
Example:
int arr[5][10][20] can store total (5*10*20) = 1000 elements totally.

Disadvantages of an array:
 The elements in an array must be same data type.
 The size of an array is fixed. we can’t expand the size in run time.
 The insertion and deletion operations in an array require shifting of
elements which takes more time.

You might also like