Unit 2 C
Unit 2 C
UNIT II – ARRAYS AND STRINGS The size of the array is a constant and must have a value at
Introduction to Arrays: Declaration, Initialization – One dimensional compilation time.
array – Example Program: Computing Mean, Median and Mode - Eg: int marks[5];
Two dimensional arrays – Example Program: Matrix Operations Explanation:
(Addition, Scaling, Determinant and Transpose) - String operations: The above statement declares marks to be an array containing 5
length, compare, concatenate, copy – Selection sort, linear and elements. In C, the array index (also known as subscript) starts from
binary search zero.
This means that the array marks will contain 5 elements in all. The
2.1 INTRODUCTION first element will be stored in marks [0], the second element in
marks[1],and so on.
To process large amount of data, we need a data structure known as Therefore, the last element, i.e., the 5th element will be stored in
array. marks [4].Note that 0, 1,2,3,4 written within square brackets are
An array is a collection of similar data elements. subscripts/index.
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).
Subscript is an ordinal number which is used to identify an
element of the array. The size of an array as a symbolic constant as the following code.
Eg: List of employees in a company, List of students in a class, List
Eg:
of customers. #include <stdio.h>
#include<conio.h>
2.2 DECLARATION OF ARRAYS #define N 100
main()
An array must be declared before being used. Declaring an array {
means specifying three things: int arr [N];
Data type-what kind of values it can store, for example int, char, }
float, double. The size of the array can be specified using an expression.
Name-to identify the array. However, the components of the expression must be available for
Size-the maximum number of values that the array can hold. evaluation of the expression when the program is compiled.
Arrays are declared using the following syntax: type name [size]; Eg:
Here the type can be either int, float, double, char or any other #include <stdio.h>
valid data type. #include<conio.h>
The number within brackets indicates the size of the array, i.e., #define N 100
the maximum number of elements that can be stored in the array. main()
1
CS8251-Programming in C
{ In the for loop, first the value of marks[0] is set to -1, then the value
int i=10; of the index (i) is incremented and the next value, i.e., marks [1] is set
int arr[N+10],my_arr[i-5*10] to-1.
……………….. The procedure is continued until all the 10 elements of the array are
} set to -1.
C array indices start from 0. So for an array with N elements, the There is no single statement that can read, access, or print all the
index of the last element is N-1. elements of the array.
To do this, we have to do it using a for/while/do-while loop to
2.3ACCESSING THE ELEMENTS OF AN ARRAY execute the same statement with different index values.
For accessing an individual element of the array, the array 2.3.1 Calculating the Address of Array Elements
subscript must be used.
For example, to access the fourth element of the array, we must write Array name is a symbolic reference to the address of the first byte
arr[3]. of the array.
The subscript or the index represents the offset from the beginning
of the array to the element being referenced.
With just the array name and the index, C can calculate the
address of any element in the array.
Since an array stores all its data elements in consecutive memory
Although storing the related data items in a single array enables the locations, storing just the base address, i.e, the address of the first
programmers to develop concise and efficient programs. element in the array is sufficient.
To access all the elements of the array, we must use a loop. That is, The address of other data elements can simply be calculated using
we can access all the elements of the array by varying the value of the the base address.
subscript into the array. The formula for doing this calculation is:
The subscript must be an integral value or an expression that Address of data element, A[k] = BA(A) + w(k-lower_bound)
evaluates to an integral value. Here, A is the array, k is the index of the element for which we have
Eg: To process all the elements of the array we will use a loop to calculate the address, BA is the base address of the array A, w is
int i, marks[10]; the word size of one element in memory (for example, size of int is
for(i=0;i<10;i++) 2), and lower_bound is the index of the first element in the array.
marks[i] = -1;
Explanation: 2.3.2 Calculating the length of an array
The code accesses every individual element of the array and set its
value to -1. Length of the array is given by the number of elements stored in
it. The general formula to calculate the length of the array is:
2
CS8251-Programming in C
Length = upper_bound - lower_bound + 1 where upper_bound is Eg:2
the index of the last element and lower_bound is the index of the
first element in the array.
Usually, lower_bound is zero but this is not a compulsion as we can
have, an array whose index may start from any non-zero value.
Eg :1
Eg:3
3
CS8251-Programming in C
Eg:
int marks[5]={90,82,78,95, 88};
int marks[3] = {1,2,3,4};//error
Explanation:
2.4 STORING VALUES IN ARRAYS An array with name marks is declared that has enough space to store
5 elements.
When we declare an array, we are just allocating space for the The first element, i.e., marks[0] is assigned with the value 90.
elements; no values are stored in the array.
Similarly, the second element of the array, i.e., marks [1] is assigned
To store values in the array, there are three ways-
82, and so on.
first, to initialize the array element at the time of declaration;
While initializing the array at the time of declaration, the
second, to input value for every individual element at the run time;
programmer may omit the size of the array.
third to assign values to the individual elements.
Eg:
int marks [ ]={98, 97, 90};
Here, the compiler will allocate enough space for all initialized
elements.
4
CS8251-Programming in C
2.4.2 Inputting Values from the Keyboard Eg:
int i, arr1[10], arr2[10];
An array can be filled by inputting values from the keyboard. arr1[10]={0, 1, 2 , 3, 4, 5 , 6, 7,8,9} ;
In this method, a while/do-while or for loop is executed to input for(i=0;i<10;i++)
the value for each element of the array by using scanf statement. arr2[i]=arr1[i];
9
CS8251-Programming in C
A, the array from which the element has to be deleted, N the number for(i=pos;i<n-1;i++)
of elements in the array , POS the position from which the element arr[i]=arr[i+1];
has to be deleted n--;
Step 1: [INITIALIZATION] SET I = POS printf(“ \n The array after deletion is: ”);
Step 2: Repeat Steps 3 and 4 while I <= N - 1 for(i=0;i<n;i++)
Step 3: SET A[I] = A[I + 1] printf("\t %d",i,arr[i]);
Step 4: SET I = I + 1 getch();
[ENDOF LOOP] return 0;
Step 5: SET N = N - 1 }
Step 6: EXIT o/p:
Enterthe number of elements in the array: 5
Explanation: Enterthe elements: 1 2 3 4 5
We first initialize i with the position from which the element has to be Enter the position from which the number has to be deleted:3
deleted. The arrayafter deletion is:1 2 3 5
In Step 2, a while loop is executed which will move all the elements
that have index greater than POS one location towards left to occupy Eg:\\ to delete a number from an array that is already sorted in
the location vacated by the deleted element. ascending order.
In Step 5, we decrement the total number of elements in the array by
1. #include<stdio.h>
#include<conio.h>
Eg:\\ to delete a number from a given location in an array. int main()
{
#include<stdio.h> int i, n, j, num, arr[10];
#include<conio.h> clrscr();
int main() printf("\n Enter the number of elements in the array : ");
{ scanf("%d", &n);
int i, n, pos, arr[10]; printf("\n Enter the elements :”);
clrscr(); for(i=0;i<n;i++)
printf("\n Enter the number of elements in the array : "); scanf(“%d”,&arr[i]);
scanf("%d", &n); printf("\n Enter the number to be deleted: ”);
printf("\n Enter the elements :”); scanf (“%d ",&num);
for(i=0;i<n;i++) for(i=0;i<n;i++)
scanf(“%d”,&arr[i]); {
printf("\n Enter the position from which the number has to be deleted: ”); if(arr[i] == num)
scanf (“%d ",&pos); {
10
CS8251-Programming in C
for(j=i; j<n-1;j++) If we have two sorted arrays and the resultant merged array also
arr[j] = arr[j+1]; needs to be a sorted one, then the task of merging the arrays becomes
} a little difficult
}
printf(“ \n The array after deletion is: ”);
for(i=0;i<n-1;i++)
printf("\t%d", arr[i]);
getch();
return 0;
}
o/p:
Enter the number of elements in the array: 5
Enter the elements: 1 2 3 4 5 Explanation:
Enter the number to be deleted: 3 The merged array is formed using two sorted arrays. Here, we first
The array after deletion is:1 2 4 5 compare the 1st element of array 1 with the 1st element of array 2, put
the smaller element in the merged array.
2.5.4 Merging two arrays Since 20 > 15,we put 15 as the first element in the merged array.
We then compare the 2nd element of the second array with the
Merging two arrays in a third array means first copying the contents 1stelement of the first array. Since 20 < 22,now 20 is stored as the
of the first array into the third array and then copying the second element of the merged array.
contents of the second array into the third array. Next, 2nd element of the first array is compared with the 2nd element
Hence, the merged array contains contents of the first array followed of the second array.
by the contents of the second array. Since 30 > 22,we store 22 as the third element of the merged array.
If the arrays are unsorted then merging the arrays is very simple as Now, we will compare the 2nd element of the first array with 3rd
one just needs to copy the contents of one array into another element of the second array.
As 30 <31,we store 30 as the 4th element of the merged array. This
Merging of two unsorted arrays procedure will be repeated until elements of both the arrays are placed
in the right location in the merged array.
#include<stdio.h>
#include<conio.h>
int main()
{
11
CS8251-Programming in C
int arr1[10] , arr2[10] , arr3[20]; The merged array is Arr[0] = 10Arr[l] = 20Arr[2] = 30Arr[3] = 15 Arr[4]
int i, n1, n2, m, index=0; = 25 Arr[5] = 35
clrscr();
printf("\n Enter the number of elements in array1: "); Eg:\\ to merge two sorted arrays
scanf ("%d", &n1);
printf(“ \n\n Enter the elements of the first array “); #include<stdio.h>
for(i=0; i<n1;i++) #include<conio.h>
scanf(“%d”,&arr1[i]); int main()
printf("\n Enter the number of elements in array2: "); {
scanf ("%d", &n2); int arr1[10] , arr2[10] , arr3[20];
printf(“ \n\n Enter the elements of the second array “); int i, n1, n2, m, index=0;
for(i=0;i<n2;i++) int index_first=0, index_second=0;
scanf(“%d”,&arr2[i]); clrscr();
m=n1+n2; printf("\n Enter the number of elements in array 1: ");
for(i=0;i<n1;i++) scanf ("%d", &n1);
{ printf(“ \n\n Enter the elements of the first array “);
arr3[index]=arr1[i]; for(i=0; i<n1;i++)
index++; scanf(“%d”,&arr1[i]);
} printf("\n Enter the number of elements in array 2: ");
for(i=0;i<n2;i++) scanf ("%d", &n2);
{ printf(“ \n\n Enter the elements of the second array “);
arr3[index] = arr2[i]; for(i=0;i<n2;i++)
index++; scanf(“%d”,&arr2[i]);
} m=n1+n2;
printf (“ \n\nThe merged array is ”); while (index_first< n1 &&index_second< n2)
for(i=0;i<m;i++) {
printf("\t Arr[%d] = %d", i, arr3[i]); if (arr1[index_first]<arr2[index_second])
getch (); {
return 0; arr3[index) = arr1[index_first];
} index_first++;
o/p: }
Enter the number of elements in array1: 3 else
Enter the elements of the first array 10 20 30 {
Enter the number of elements in array2 : 3 arr3[index] = arr2[index_second];
Enter the elements of the second array 15 25 35 index_second++;
12
CS8251-Programming in C
} 2.5.5 Searching for a value in an array
index++;
} Searching means to find whether a particular value is present in
if(index_first == n1) the array or not.
{ If the value is present in the array then searching is said to be
while (index_second<n2) successful and the searching process gives the location of that value
{ in the array.
arr3[index] = arr2[index_second]; Otherwise, if the value is not present in the array, the searching
index_second++; process displays the appropriate message and in this case searching is
index++; said to be unsuccessful.
} There are two popular methods for searching the array elements. One
} is linear search and the second is binary search.
else if (index_second == n2)
{ Linear Search
while (index_first<n1)
{ Linear search, also called sequential search, is a very simple method
arr3[index] = arr1[index_first]; used for searching an array for a particular value.
index_first++; It works by comparing every element of the array one by one in
index++; sequence until a match is found.
} Linear search is mostly used to search an unordered list of elements
} (array in which data elements are not sorted).
printf ("\n\n The contents of the merged array are") ;
for(i=0;i<m;i++) Algorithm for linear search
printf ("\n Arr[%d] = %d”,i,arr3[i]); LINEAR_SEARCH(A,N,VAL)
getch(); STEP 1: [INITIALIZE] SET POS = -1
return 0; STEP 2: [INITIALIZE] SET I = 1
} STEP 3: REPEAT STEP 4 while I<=N
o/p: STEP 4: IF A[I]=VAL
Enter the number of elements in array 1: 3 SET POS=I
Enter the elements of the first array 10 20 30 PRINT POS
Enter the number of elements in array 2 : 3 Goto Step 6
Enter the elements of the second array 15 25 35 [END OF IF]
The merged array is Arr[0] = 10Arr[l] = 15Arr[2] = 20Arr[3] = 25 Arr[4] [END OF LOOP]
= 30 Arr[5] = 35 STEP 5: IF POS=-1
PRINT “ VALUE IS NOT PRESENT IN THE ARRAY ”
13
CS8251-Programming in C
[END IF] Explanation
STEP 6: EXIT if an array A[ ] is declared and initialized as
Explanation: int A[ ] = { 10, 8, 2, 7, 3, 4, 9, 1, 6, 5};
In Step 1and Step 2 of the algorithm, we initialize the value of POS and the value to be searched is VAL = 7, then searching to find
and I. whether the value ‘7’ is present in the array or not.
In Step 3, a while loop is executed that would be executed until I is If yes, then the search is successful and it returns the position of
less than N (total number of elements in the array). occurrence of VAL. Here, POS = 3 (index starting from0).
In Step 4, a check is made to see if a match found between the current Obviously, the best case of linear search is when VAL is to the first
array element and VAL. element of the array.
If a match is found, then the position of the array element is printed The worst case will happen when either VAL present in the array or it
else the value of I is incremented to match the next element with is equal to the last element of the array.
VAL.
However, if all the array elements have been compared with VAL, Eg:\\ Linear Search
and no match is found then it means that VAL is not present in the
array. #include <stdio.h>
For example, #include <conio.h>
int main()
{
int arr[10], num, i , n , found = 0, pos=-1;
clrscr ();
printf("\n Enter the number of elements in the array : ");
scanf("%d", &n);
printf (" \n Enter the elements:");
for(i=0;i<n;i++)
scanf ("%d", &arr[i]);
printf("\n Enter the number that has to be searched : ");
scanf ("%d", &num);
for(i=0;i<n;i++)
{
if(arr[i] == num)
{
found =1;
pos=i;
14
CS8251-Programming in C
printf("\n %d is found in the array at position = %d",
num,i); If a match is found then value of POS is printed and the algorithm
break; exits.
}
} However, if a match is not found and if the value of a A[MID] is
if(found == 0) greater than VAL, then the value of END is modified otherwise if A
printf("\n %d does not exist in the array", num); [MID] is less than VAL, then value of BEG is altered.
getch();
return 0; In Step 5, if the value of POS = -1, then it means VAL is not present
} in the array and an appropriate message is printed on the screen
o/p: before the algorithm exits.
Enter the number of elements in the array:5
Enter the elements: 1 2 3 4 5
Enter the number that has to be searched: 7
7 does not exist in the array
Binary search
Sorting means arranging the elements of the array in some relevant order #include<stdio.h>
which may be either ascending or descending. #include<conio.h>
There are types of sorting: void main()
Internal sorting: Sorting the data stored in computers memory. {
External sorting: Sorting the data stored in files. int a[100],n,i,j,min,temp;
clrscr();
Technique: printf("\n Enter the Number of Elements: ");
scanf("%d",&n);
Consider an array ARR with N elements. printf("\n Enter %d Elements: ",n);
The selection sort makes N-1 passes to sort the entire array. for(i=0;i<n;i++)
First find the smallest value in the array and place it in the first position. {
Then find the second smallest value in the array and place it in the second scanf("%d",&a[i]);
position. }
Repeat this procedure until the entire array is sorted. for(i=0;i<n-1;i++)
In pass 1, find the position POS of the smallest value in the array and {
then swap ARR[POS] and ARR[0]. Thus, ARR[0] is sorted. min=i;
In pass 2, find the position POS of the smallest value in sub-array of N-1 for(j=i+1;j<n;j++)
elements. Swap ARR[POS] with ARR[1]. Now A[0] and A[1] is sorted. {
In pass 3, find the position POS of the smallest value in sub-array of N-2 if(a[min]>a[j])
elements. Swap ARR[POS] with ARR[2]. Now ARR[1] and ARR[2] is min=j;
sorted. }
In pass N-1, find the position POS of the smaller of the elements ARR[N- if(min!=i)
2] so that ARR[0],ARR[1].....,ARR[N-1] is sorted. {
temp=a[i];
17
CS8251-Programming in C
a[i]=a[min]; Eg:
a[min]=temp;
} #include<stdio.h>
} main()
printf("\n The Sorted array in ascending order: "); {
for(i=0;i<n;i++) int i,j,a[20]={0},sum=0,n,t,b[20]={0},k=0,c=1,max=0,mode;
{ float x=0.0, y=0.0;
printf("%d ",a[i]); printf(“ \n Enter the limit ”);
} scanf(“%d”,&n);
getch(); printf(“ Enter the set of numbers \n”);
}
o/p: for(i=0;i<n;i++)
Enter the number of elements : 5 {
Enter 5 elements : scanf(“%d”,&a[i]);
23 sum=sum+a[i];
12 }
89
32 x=(float)sum/(float)/n;
56 printf(“ Mean \t=%f”,x);
The sorted array in ascending order: 12 23 32 56 89 for(i=0;i<n;i++)
{
Example program: To compute Mean, Median and Mode for(j=j+1;j<n;j++)
{
Mean: Mean is same as average. The mean is found by adding up all of the if(a[i]>a[j])
given data and dividing by the number of elements. {
Eg: Mean of 1,2,3,4,5 is (1+2+3+4+5)/5=3 t=a[i];
a[i]=a[j];
Median: The median is the middle number in an ordered list( ascending a[j]=t;
order or descending order). }
Eg: Median of 1,2,3,4,5 is 3. }
}
Mode: if(n%2==0)
Mode is the element which happens most number of times in the list. y=(float)(a[n/2]+a[(n-1)/2])/2;
Eg: Mode of 1,2,1,3,1,4,5 is 1. else
y=a[(n-1)/2];
18
CS8251-Programming in C
printf(“ \n Median \t=%f”,y); printf(“%d”,b[i]);}}
for(i=0;i<n-1;i++) o/p:
{ Enter the limit: 5
mode=0; Enter the set of numbers 1 2 3 4 5
for(j=j+1; j<n;j++) Mean = 3.0000
{ Median = 3.0000
if(a[i]==a[j]) There is no mode.
{
mode++; 2.6 PASSING ARRAYS TO FUNCTIONS
}
} Like variables of other data types, we can also pass an array to a function.
if(mode>max)&&(mode!=0)) While in some situations, you may want to pass individual elements of
{ the array, and in other situations you may want to pass the entire array
k=0;
max=mode;
b[k]=a[i];
k++;
}
else if(mode==max)
{
b[k]=a[i]
k++; .
}
} 2.6.1 Passing Individual elements
for(i=0;i<n-1;i++)
{ The individual elements of an array can be passed to a function by
if(a[i]==b[j]) passing either their addresses or their data values.
c++;
} 2.6.2 Passing Data Values
if(c==n)
printf(“ \n There is no mode”); The individual elements can be passed in the same manner as we pass
else variables of any other data type.
{ The condition is just that the data type of the array element must
printf(“\n Mode \t=”); match with the type of the function parameter.
for(i=0;i<k;i++)
19
CS8251-Programming in C
In the fig given below, only one element of the array ispassed to the
called function. This is done by using the index expression. So arr[3]
actually evaluates to a single integer value.
The called function hardly bothers whether a normal integer variable
is passed to it or an array value is passed.
rows_sum=rows1; return 0;
cols_sum=colsl; }
printf("\n Enter the elements of the first matrix"); o/p:
printf("\n *************************"); Enter the number of rows in the first matrix: 2
Enter the number of columns in the first matrix:2
for(i=0; i<rows1; i++)
Enter the number of rows in the second matrix:2
{
Enter the number of columns in the second matrix:2
for(j=0; j<cols1; j++)
Enter the elements of the first matrix:
scanf("%d",&mat1[i][j] );
*********************************
}
1234
25
CS8251-Programming in C
Enter the elements of the second matrix: for(j=0;j<size;j++)
********************************* a[i][j]=n*a[i][j];
5678
The elements of the product matrix are printf(“ \n Resultant Matrix ”);
*********************************** for(i=0;i<size;i++)
6 8 {
10 12 for(j=0;j<size;j++)
{
2.8.2 Scalar product of a Matrix printf(“%d\t”,a[i][j]);
}
Scalar Multiplication of a matrix is defined by(cA)ij=c.Aij(where printf(“\n”);
1<=i<=m and 1<=j<=n) }
For eg: getch();
}
o/p:
Enter elements of matrix:
Eg: 1 2 3
4 5 6
#include<stdio.h> 7 8 9
void main() Enter any number to multiply
{ 3
intsize=3; Resultant matrix is
intn,i,j; 3 6 9
inta[size][size]; 12 15 18
21 24 27
printf(“\n Enterelements ofmatrix:\n");
for(i=0;i<size;i++)
for(j=0;j<size;j++)
scanf(“%d”,&a[i][j]);
2.8.3 Determinant of a Matrix
printf(“\n Enter any number to multiply ”);
scanf(“%d”,&n); The Determinant of a matrix is a special number that can be
calculated from the elementsof a square matrix.
for(i=0;i<size;i++) The determinant of a matrix A is denoted by det(A), det A or [A]
26
CS8251-Programming in C
0
3
-1
Eg: 2
#include<stdio.h> 0
void main() 7
{ The given matrix is
int a[3][3],i,j; 5 2 1
0 3 1
int deter=0; 2 0 7
printf(“\n Enter the 9 elements of matrix “);
for(i=0;i<3;i++) 2.8.4 Transpose of a matrix
for(j=0;j<3;j++)
scanf(“%d”,&a[i][j]); The transpose of a matrix is obtained by interchanging rows and
columns of a matrix. For example if a matrix is,
printf(“\n The given matrix is:\n”); 1 2
for(i=0;i<3;i++) 3 4
{ 5 6
printf(“\n”); Then, transpose of above matrix will be
for(j=0;j<3;j++) 1 3 5
printf(“%d\t”,a[i][j]); 2 4 6
}
Eg:
for(i=0;i<3;i++)
deter=deter+(a[0][i]*(a[1][(i+1)%3]*a[2][(i+2)%3] #include<stdio.h>
a[1][(i+2)%3]*a[2][(i+1)%3)); #include<conio.h>
printf(“\n Determinant of matrix is:%d”,deter); int main()
inti,j,mat[3][3], transposed_matrix[3][3];
clrscr();
o/p: printf("\n Enter the elements of the matrix");
Enter the 9 elements' of matrix: printf("\n *************************");
5
for(i=0; i<3; i++)
-2
{
1
27
CS8251-Programming in C
for(j=0; j<3; j++) return 0;
{ }
scanf("%d", &mat[i][j] );
} o/p:
} Enter the elements of the matrix:
*********************************
printf("\n The elements of the matrix are "); 123456789
printf("\n *************************"); The elements of the matrix are:
for(i=0; i<3; i++) *********************************
{ 123
printf(“\n”); 456
for(j=0; j<3; j++) 789
{ The elements of the transposed matrix are:
printf("\t%d",mat[i][j] ); *********************************
} 147
} 258
369
for(i=0; i<3; i++)
{ 2.8.5 Matrix Multiplication
for(j=0; j<3; j++)
{ To multiply two matrices, the number of columns of first matrix
transposed_mat[i][j]=mat[j][i]; should be equal to number of rows to the second matrix.
}
} Eg:
printf ("\n The elements of the transposed matrix are ”); #include<stdio.h>
printf ("\n *************** ** ****** **"); #include<conio.h>
for(i=0; i<3; i++) int main()
{ {
printf(“\n”); inti,j,k;
for(j=0; j<3; j++) int rows1,colsl, rows2, cols2, res_rows, res_cols;
printf ("\t %d", transposed_mat[i][j]); int mat1[5][5], mat2[5][5], res[5][5];
} clrscr();
getch();
28
CS8251-Programming in C
printf("\n Enter the number of rows in the first matrix:”); {
scanf("%d",&rows1) ; for(j=0; j<cols2; j++)
scanf("%d",&mat2[i][j] );
printf("\n Enter the number columns in the first matrix: "); }
scanf("%d",&cols1) ;
for(i = 0;i <res_rows;i++)
printf("\n Enter the number of rows in the second matrix: "); {
scanf ("%d" ,&rows2) ; j=0;
for(j= 0; j <res_cols; j++)
printf("\n Enter the number of columns in the second matrix: ”); {
scanf ("%d" ,&cols2); res[i][j] =0;
for(k=0; k<res_cols; k++)
if(cols1!=rows2) res[i][j] += matl[i][k] *mat2[k][j] ;
{ }
printf ("\n The number of columns in the first matrix must equal to the }
number of rows in the second matrix");
getch(); printf ("\n The elements of the product matrix are ”);
exit(); printf ("\n *************** ** ****** **");
} for(i = 0; i<res_rows;i++)
{
res_rows=rows1; printf ("\n");
res_cols = cols2; for(j = 0; j <res_cols;j++)
printf("\n Enter the elements of the first matrix"); printf("\t %d",res[i][j]);
printf("\n *************************"); }
return 0;
for(i=0; i<rows1; i++) }
{
for(j=0; j<cols1; j++) o/p:
scanf("%d",&mat1[i][j] ); Enter the number of rows in the first matrix: 2
} Enter the number of columns in the first matrix:2
Enter the number of rows in the second matrix:2
printf(" \n Enter the elements of the second matrix"); Enter the number of columns in the second matrix:2
printf(" \n *** ** *** *** *** ** *** *** ***"); Enter the elements of the first matrix:
*********************************
for(i=0; i<rows2; i++) 1234
29
CS8251-Programming in C
Enter the elements of the second matrix:
*********************************
5678
The elements of the product matrix are
***********************************
19 22
43 50
2.10 STRINGS
Fig: Two dimensional arrays for inter-function communication In C language, a string is a null-terminated character array.
This means that after the last character, a null character ('\0') is stored
2.9.1Passing a Row to signify the end of the character array.
A row of a two-dimensional array can be passed by indexing the array For example, if we write
name with the row number. char str [] = "HELLO";
When we send a single row of a two-dimensional array, then the We are declaring a character array that has five usable characters
called function receives a one-dimensional array. namely, H, E, L, L, and O.
Apart from these characters, a null character ('\0') is stored at the
end of the string.
30
CS8251-Programming in C
So, the internal representation of the string becomes HELLO' \ 0'. To Figure shows how str[] is stored in memory. We see that a string is a
store a string of length 5, we need 5 + 1 locations (1 extra for the sequence of characters. In Figure 1000, 1001, 1002, and so on are the
null character). memory addresses of individual characters. From the figure, we see
The name of the character array (or the string) is a pointer to the that H is stored at memory location 1000 but in reality the ASCII
beginning of the string. codes of characters are stored in memory and not the character itself,
i.e., at address 1000, 72 will be stored since the ASCII code for His
72.
The general form of declaring a string is char str[size];
When we declare the string in this way, we can store size-1 characters
in the array because the last character would be the null character.
For example, char msg[100]; can store a maximum of 99 usable
characters.
The other way to initialize a string is to initialize it as an array of
characters, like
When the compiler assigns a character string to a character array, it char str[] = { ‘H’, ‘E’, ‘L’, ‘L’ , ‘O’, ‘\0’};
automatically appends a null character to the end of the string. We have not mentioned the size of the string (or the character array).
The size of the string should be equal to maximum number of Here, the compiler will automatically calculate the size based on the
characters in the string plus one. number of elements initialized. So, in this example 6 memory slots
We use subscripts (also known as index) to access the elements of an will be reserved to store the string variable, str.
array, similarly subscripts are also used to access the elements of the We can also declare a string with size much larger than the number of
character array. The subscript starts with a zero(0). elements that are initialized. For example, consider the statement
char str[10] = "HELLO";In such cases, the compiler creates a
character array of size 10; stores the value "HELLO" in it and finally
terminates the value with a null character. Rest of the elements in the
array are automatically initialized to NULL.
32
CS8251-Programming in C
2.10.2WRITING STRINGS Using putchar() function
Strings can be displayed on screen using three ways:
1. using printf() function strings can also be written by calling the putchar () function
2. using puts() function repeatedly to print a sequence of single characters.
3. using putchar() function repeatedly
33
CS8251-Programming in C
Fixed-length string
Variable-length string
In a length-controlled string, you need to specify the number of 2.12.1 FINDING THE LENGTH OF A STRING
characters in the string.
This count is used by string manipulation functions to determine the The number of characters in the string constitutes the length of the
actual length of the string variable. string.
In this format, the string is ended with a delimiter. The delimiter is For example, LENGTH("C PROGRAMMING IS FUN") will return
then used to identify the end of the string. For example, in English 19.
language every sentence is ended with a full stop. Note that even blank spaces are counted as characters in the string.
Similarly, in C we can use any character such as comma, semicolon, LENGTH(‘0') = 0 and LENGTH(‘’) = 0 because both the strings do
colon, dash, null character, etc. as the delimiter of a string. However not contain any character and the ASCII code of '\ 0' is zero.
null character is the most commonly used string delimiter in the C Therefore, both the strings are empty and of zero length.
language.
A string is stored in an array of characters. If we are using the null Algorithm to calculate the length of a string
character as string delimiting character then we treat the part of the Step 1: [INITIALIZE] SET I = 0
array from the beginning to the null character as the string and ignore Step 2: Repeat Step 3 while STR[I] != NULL
the rest. Step 3 : SETI = I + 1
[ENDOFLOOP]
Step 4: SETLENGTH= I
Step 5: END
37
CS8251-Programming in C
Algorithm to concatenate two strings gets(str2) ;
Step 1: [INITIALIZE] I= 0 and J = 0 while(str1[i] != '\0')
Step 2: Repeat Steps 3 to 4 while strl[i] ! = NULL {
Step 3: SETnew_str[J] = str1[I] str3[j] = str1[i];
Step 4: SetI=I+1andJ=J+1 i++;
[END of LOOP] j++;
Step 5: SETI=0 }
Step 6: Repeat Steps 6 to 7 while str2[i]! =NULL i=0;
Step 7: SETnew_str[J] = str2[I] while(str2[i] != '\0')
Step 8: Set I = I+1 and J = J+1 {
[END of LOOP] str3[j] = str2[i];
Step 9: SET new_str[J] =NULL i++;
Step 10: EXIT j++;
}
In this algorithm, we first initialize the two counters I and J to zero. str3[j] = '\0';
To concatenate the strings, we have to copy the contents of the first printf("\n The concatenated string is:");
string followed by the contents of the second string in a third string, puts(str3) ;
new_ str. getch() ;
Steps 2 to 4 copies the contents of the first string in new_ str. return 0;
Likewise, Steps 6 to 8 copies the contents of the second string in
new_str. Output
After the contents have been copied a null character is appended at Enter the first string: Hello,
the end of new_ str. Enter the second string: How are you?
The concatenated string is: Hello, How are you?
Program to concatenate two strings.
#include <stdio.h> 2.12.5 APPENDING A STRING TO ANOTHER STRING
#include <conio.h>
int main() Appending one string to another string involves copying the contents
{ of the source string at the end of the destination string.
char str1[100], str2[100], str3[100]; For example, if S1 and S2 are two strings, then appending S1 to S2
int i=0, j=0; means we have to add the contents of S1 to S2.Here 81 is the source
clrscr () ; string and 82 is the destination string. The append operation would
printf("\n Enter the first string: "); leave the source string S1 unchanged and destination string S2= S2 +
gets(str1) ; S1.
printf("\n Enter the second string: ");
38
CS8251-Programming in C
Algorithm to append a string to another string {
Step 1: [INITIALIZE] SET I =0 and J=O Dest_Str[i]=Source_Str[j] ;
Step 2: Repeat Step 3 while Dest_Str[I] != NULL i++;
Step 3: SET I + I + 1 j++;
[ENDOF LOOP] }
Step 4: Repeat Steps 5 to 7 while Source_Str[J] != NULL DestStr[i] = '\0';
Step 5: Dest_Str[I] = Source_Str[J] printf("\n After appending, the destination string is: ");
Step 6 : SET I = I + 1 puts(Dest_Str) ;
Step 7: SET J = J + 1 getch();
[ENDOF LOOP] return 0;
Step 8: SET Dest_Str[J]= NULL }
Step 9: EXIT Output
Enter the source string: How are you?
In this algorithm, we first traverse through the destination string to Enter the destination string: Hi,
reach its end, i.e., reach the position where a null character is After appending, the destination stringis :Hi, How are you?
encountered.
The characters of the source string are then copied into the destination 2.12.6 COMPARING TWO STRINGS
string starting from that position. Finally, a null character is added to
terminate the destination string. If S1 and S2 are two strings then comparing two will give either of
these results:
Program to append a string to another string (a) S1 and S2 are equal
#inc1ude <stdio.h> (b) S1 >S2, when in dictionary order S1 will come after S2
#include <conio.h> (c) S1 < S2, when in dictionary order S1 precedes S2
int main() To compare the two strings, each and every character is compared
{ from both the strings.
charDest_Str[100] , Source_Str[50]; If all the characters are same then the two strings are said to be equal.
int i = 0, j = 0;
clrscr (); Algorithm to compare two strings
printf ("\n Enter the source string: "); Step 1: [INITIALIZE] SET I=0, SAME=0
gets(Source_Str) ; Step 2: SETLenl = Length(STR1), Len2 = Length(STR2)
printf("\n Enter the destination string:”); Step 3: IF lenl != len2, then
gets(Dest_Str) ; Write" Strings Are Not Equal"
while(Dest_Str [i] != '\0') ELSE
i++; Repeat while I<Lenl
while(Source_Str [j] != '\0') IF STRl[I] == STR2[I]
39
CS8251-Programming in C
SET I = I+1 c1rscr() ;
ELSE printf ( "\n Enter the first string: ");
Goto Step 4 gets(strl) ;
[END OF IF] printf("\n Enter the second string: ");
[END OFLOOP] gets(str2) ;
IF I = Lenl 1en1 = str1en(strl);
SETSAME= 1 1en2 = str1en(str2);
Write "Strings are equal" if(lenl == 1en2)
[END OF IF] {
Step 4: IFSAME=0 while (i<1enl)
IF STRl[I]> STR2[I], then {
Write "Stringl is greater than String2" if(strl[i]==str2[i])
ELSE IF STRl[I]< STR2[I], then i++;
Write" String2 is greater than Stringl" else break;
[ENDOF IF] }
[ENDOFIF] if (i==len1)
Step 5: EXIT {
same=l;
In this algorithm, we first check whether the two strings are of same printf("\n The two strings are equal");
length. }
If not, then there is no point in moving ahead as it straightaway means }
that the two strings are not same. However, if the two strings are of if (lenl!=len2)
the same length, then we compare character by character to check if printf("\n The two strings are not equal") ;
all the characters are same. if (same == 0)
If yes, then variable SAME is set to 1 else if SAME = 0, then we {
check which string precedes the other in dictionary order and print the if(strl[i]>str2[i])
corresponding message. printf("\n Stringl is greater than string2") ;
else if(str1[i]<str2[i])
Programto compare two strings printf("\n String2 is greater thanstringl") ;
#inc1ude <stdio.h> getch() ;
#include <conio.h> return 0;
int main() }
{
charstrl[50], str2(50); Output
int i=0, lenl = 0, 1en2 = 0, same = 0; Enter the first string: Hello
40
CS8251-Programming in C
Enter the second string: Hello charstr[100] , reverse_str[100] , temp;
The two strings are equal int i = 0, j = 0;
clrscr() ;
2.12.7 REVERSING A STRING printf("\n Enter the string:”);
gets(str) ;
If S1= "HELLO", then reverse of S1 "OLLEH". j=strlen(str)-l;
Toreverse a string we just need to swap the first character with the while(i<j)
last, second character with the second {
last character, so on and so forth. temp = str[j];
str[j]= str[i] ;
Algorithm to reverse a string str[i] = temp;
Step 1: [INITIALIZE] SET I=0, J= Length (STR)-1 i++;
Step 2: Repeat Steps 3 and 4 while I < J j--;
Step 3: SWAP(STR(I), STR(J)) }
Step 4 : SETI = I + 1, J = J - 1 printf(“ \n The reversed string is: ”);
[ENDOFLOOP] puts(str) ;
Step 5: EXIT getch() ;
return 0;
In Step 1, I is initialized to zero and J is initialized to the length of the }
string STR -1. Output
In Step 2, a while loop isexecuted until all the characters of the string Enter the string: Hi there
are accessed. The reversed string is: erehtiH
In Step 3, we swap the ith character of STR with its jth character. (As
a result, the first character of STR will be interchanged with the last 2.13 Built in functions of strings
character, the second character will be interchanged with the second
last character of STR,and so on). Strcat function
In Step 4, the value of I is incremented and J is decremented to #include <stdio.h>
traverse STR in the forward and backward direction, respectively. #include <string.h>
int main()
Program to reverse the given string {
#include <stdio.h> char strl[50] = "Programming";
#include <conio.h> char str2[] = "In C";
#include <string.h> strcat(strl, str2);
int main() printf("\n strl: %s", strl);
{ return 0;
41
CS8251-Programming in C
} strrchr Function
Output #include <stdio.h>
strl: Programming In C #include <string.h>
int main ()
strncat Function char str [50] = "Programming In C":
char *pos;
#include <stdio.h>
pos = strrchr (str, 'n');
#include <string.h>
if (pos )
int main()
printf ("\n The last position of n %d", pos-str) ;
char strl[50] = "Programming";
else
char str2[] = "In C";
strncat(strl, str2, 2); printf("\n n is not present in the string") ;
printf("\n strl: %s", strl); return 0;
return 0; Output
} The last position of n is: 13
Output
strl: Programming In strcmp Function
#include <stdio.h>
strchr Function #include <string. h»
#include <stdio.h> int main()
#include <string.h> char str1 [10]="HELLO";
int main() char str2 [10]="HEY";
char str[50] = "Programming In C"; if(strcmp(strl,str2)==0)
char *pos; printf("\n The two strings are identical");
pos = strchr(str, 'n'); else
if (pos) printf("\n The two strings are not identical");
printf("\n n is found in str at position %d", pos); return 0;
else }
printf("\n n is not present in the string") ; Ouput:
return 0; The two strings are not identical
}
Output strncmp Function
n is found in str at position 9 #include<stdio.h>
#include<string.h>
42
CS8251-Programming in C
int main() return 0;
{ }
char strl[10] = "HELLO";
char str2[10] = "HEY"; Output
if(strncmp(str1,str2,2)==0) HE
printf("\n The two strings are identical") ;
else strlen Function
printf("\n The two strings are not identical") ; #include <stdio.h>
return 0; #include <string.h>
} int main ()
Output {
The two strings are identical char str [] = "HELLO";
printf ("\n Length of str is: %d",strlen(str)) ;
strcpy Function return 0;
#include <stdio.h> }
#include <string.h> Output
int main() Length of str is: 5
{
char str1[10] , str2[10] = "HELLO"; Eg: Palindrome of a string
strcpy(str1,str2) ;
printf("\n str1: %s", str1); #include <stdio.h>
return 0; #include <string.h>
}
Output int main()
HELLO {
char a[100], b[100];
strncpy Function clrscr();
#include <stdio.h> printf("Enter a string to check if it is a palindrome\n");
#include <string.h> gets(a);
int main() strcpy(b, a);
{ strrev(b);
char strl[10], str2[10] = "HELLO";
strncpy(strl,str2, 2); if (strcmp(a, b) == 0)
printf("\n strl: %s", strl); printf("The string is a palindrome.\n");
43
CS8251-Programming in C
else int main()
printf("The string isn't a palindrome.\n"); {
getch(); char strl [] = "HAPPY BIRTHDAY TO YOU";
return 0; char str2 [] = "HAPPY BIRTHDAY JOE";
} printf("\n The position of first character in str2 that does not match with
that in strl is %d", strspn(strl,str2)) ;
return 0;
}
Output
The position of first character in str2
that does not match with that in strl is 15
strcspn Function
strstr Function
#include <stdio.h>
#include <stdio.h>
#include <string.h>
#include <string.h>
int main()
int main()
{
{
char strl[] "PROGRAMMING IN C";
char strl []="HAPPY BIRTHDAY TO YOU";
char str2[] "IN";
char str2 []="DAY";
printf("\n The position of first character in str2 that matches with thatin
char *ptr;
strl is %d", strcspn(strl,str2));
ptr = strstr(strl, str2);
return 0;
if (ptr)
}
printf("\n Substring Found");
Output
else
The position of first character in str2
printf("\n Substring Not Found");
that matches with that in strl is 8
return 0;
}
Output strpbrk Function
Substring Found #include <stdio.h>
#include <string. h>
strspn Function int main()
{
#include <stdio.h>
char strl [] = "PROGRAMMING IN C";
#include <string.h>
44
CS8251-Programming in C
char str2 [] = "AB"; programming
char *ptr = strpbrk (strl , str2) ) ;
if (ptr==NULL) strtol Function
printf ("\n No character matches in the two strings") ;
#include <stdio.h>
else
#include <stdlib.h>
printf ("\n Character in str2 matches with that in strl") ;
main ()
return 0;
{
}
long num;
num=strtol("12345Decimal Value", NULL, 10);
Output: printf("%ld", num);
No character matches in the two strings. num = strtol("65432 Octal Value", NULL, 8);
printf("%ld", num) ,
Strtok function num = strtol ("10110101 Binary Value" ,NULL, 2);
#include <stdio.h> printf("%ld", num) :
#include <string.h> num = strtol ("A7CB4 Hexadecimal Value",NULL, 16);
main () printf ("%ld", num);
{ getch() ;
char str[] = "Hello, to, the, world of, programming" ; return 0;
char delim[] = ","; }
char result [20] ; Output
result = strtok(str, delim); 12345
while (result!=NULL) 27418
printf("\n %s", result); 181
result = strtok (NULL,delim) ; 687284
}
getch() ; Strtod Function
return 0; #include <stdio.h>
} #include <stdlib.h>
Output main ()
Hello {
to double num;
the num = strtod ("123.345abcdefg", NULL);
world of printf("%lf", num);
getch() ;
45
CS8251-Programming in C
return 0;
Output
123.345000
atoi() function
i = atoi ( "123.456" );
RESULT: i = 123 .
atof() function
x = atof( "12.39 is the
RESULT: x = 12.39
atolFunction
Example x = atol ( "12345.6789" );
RESULT: x = 12345L.