0% found this document useful (0 votes)
16 views46 pages

Unit 2 C

This document provides an overview of arrays and strings in C programming, detailing their declaration, initialization, and operations. It covers one-dimensional and two-dimensional arrays, including examples for computing statistics, matrix operations, and string manipulations. Additionally, it explains how to access, store, and manipulate array elements, along with algorithms for common operations such as insertion and traversal.

Uploaded by

vini t
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views46 pages

Unit 2 C

This document provides an overview of arrays and strings in C programming, detailing their declaration, initialization, and operations. It covers one-dimensional and two-dimensional arrays, including examples for computing statistics, matrix operations, and string manipulations. Additionally, it explains how to access, store, and manipulate array elements, along with algorithms for common operations such as insertion and traversal.

Uploaded by

vini t
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 46

CS8251-Programming in 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.

 If the number of values provided is less than the number of


elements in the array, the un-assigned elements are filled with
zeros.

2.4.1 Initializing Arrays during Declaration

 When an array is initialized, we need to provide a value for every


element in the array.
 Arrays are initialized by writing, type array_name[sizel={ list of
values};
 The values are written within curly brackets and every value is
separated by a comma.
It is a compiler error to specify more number of values than the
number of elements in the array.

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];

Eg: Code for inputting each element of the array Explanation:


 The code accesses each element of the first array and
int i, marks[10] ; simultaneously assigns its value to the corresponding element of
for(i=0; i<10; i++) the second array.
scanf(“ %d",&marks[i]) ;  Finally, the index value i is incremented to access the next element
Explanation: in succession.
 We start with the index i at 0 and input the value for the first element  Therefore, when this code is executed, arr2[0]= arr1 [0], arr2[1] =
of the array. arr1[1], arr2[2] = arr1[2],and so on.
 Since the array can have 10 elements, we must input values for
elements whose index varies from 0 to 9. // Fill an array with even numbers
 Therefore, in the for loop, we test for condition (i<10) which means int i, arr[10];
the number of elements in the array. for(i=0;i<10;i++)
arr[i]=i*2;
2.4.3 Assigning Values to Individual Elements
Explanation:
 The third way is to assign values to individual elements of the  If we want to fill an array with even integers starting (from 0). In the
array by using the assignment operator. code, we assign to each element a value equal to twice of its index,
 A simple assignment statement can be written as: marks[3] = 100; where index starts from zero. So after executing this code we will
Here, 100 is assigned to the fourth element of the array which is have, arr [0] = 0, arr [1] = 2,arr [2] = 4, and so on.
specified as marks [3].
 Any value that evaluates to the data type of the array can be 2.5 OPERATIONS ON ARRAYS
assigned to the individual array element.
 We cannot assign one array to another array, even if the two arrays  There are a number of operations that can be performed on arrays.
have the same type and size. To copy an array, you must copy the These operations include:
value of every element of the first array into the element of the  Traversing an array
second array.  Inserting an element in an array
 Deleting an element from an array
 Merging two arrays
5
CS8251-Programming in C
 Searching an element in an array Eg: // To read and display n numbers using an array
 Sorting an array in ascending or descending order
#include <stdio.h>
2.5.1 Traversing an Array #include <conio.h>
int main()
 Traversing an array means accessing each and every element of the {
array for a specific purpose. int i=0, n, arr[20];
 If A is an array of homogeneous data elements, then traversing the clrscr ();
data elements can include printing every element, counting the printf( "\n Enter the number of elements :”);
total number of elements, or performing any process on these scanf("%d” , &n);
elements. printf("\n Enter the elements");
 Since an array is a linear data structure (because all its elements for(i=0;i<n;i++)
forma sequence), traversing its elements is very simple and straight {
forward. printf("\n Arr[%d] =",i);
scanf("%d", &arr[i]);
 Algorithm for array traversal }
Step 1: [INITIALIZATION]SET I = lower_bound printf("\n The array elements are \n”);
Step 2: Repeat Steps 3 to 4 while I <=upper_bound for(i=0;i<n;i++)
Step 3: Apply Process to A[I] printf(“ Arr[%d] = %\t”, i, arr[i]);
Step 4: SET I = I + 1 return 0;
[ENDOFLOOP] }
Step 5: EXIT o/p:
Explanation: Enter the number of elements : 5
 In Step 1, we initialize index to the lower bound of the array. Enter the elements
 In Step 2, a while loop is executed. Arr[0] = 1
 Steps 3 and4 form part of the loop. Step 3 processes the Arr[1] = 2
individual array element as specified by the array name and index Arr[2] = 3
value. Arr[3] = 4
 Step 4 increments the index value so that the next array element Arr[4] = 5
could be processed. The array elements are
Arr[0] = 1 Arr[1] = 2 Arr[2] = 3
 The while loop in Step 2 is executed until all the elements in the
Arr[3] = 4 Arr[4] = 5
array are processed.
 In other words, the while loop will be executed until i is less
than or equal to the upper bound of the array.
6
CS8251-Programming in C
2.5.2 Inserting an element in an array Algorithm to insert a new element at a specified position

 Inserting an element in array means adding a new data element to


Step 1: [INITIALIZATION] SET I =N
an already existing array.
 If the element has to be inserted at the end of the existing array, Step 2: Repeat Steps 3 and 4 while I >= POS
then the task of inserting is quite simple.
Step 3: SETA[I + 1]= A[I]
 We just have to add 1 to the upper_bound and assign the value.
For example, if an array is declared to contain 10 elements, but Step 4 : SET I = I - 1
currently it is having only 8 elements, then obviously there is space to
(ENDOFLOOP)
accommodate two more elements.
 But if it already has 10 elements, then we will not be able to add Step 5: SET N=N+ 1
another element to it.
Step 6: SETA[POS] =VAL
Algorithm to append a new element to an existing array Step 7: EXIT
Step 1: Set upper_bound = upper_bound + 1
Step 2: Set A[upper_bound] = VAL
Explanation:
Step 3: EXIT
 The algorithm INSERT will be declared as INSERT (A, N, POS,
Explanation:
 In Step 1, we increment the value of the upper_bound. VAL).
 In Step2, the new value is stored at the position pointed  The arguments are
byupper_bound. A, the array in which the element has to be inserted
N, the number of elements in the array
Insert an element in the middle of an array POS, the position at which the element has to be inserted and
VAL, the value that has to be inserted.
 Consider an array whose elements are arranged in ascending  In Step 1, we first initialize I with the total number of elements in
order.
 Now, if a new element has to be added, it will have to be added the array.
probably somewhere in the middle of the array.  In Step 2, a while loop is executed which will move all the elements
 To do this, we will have to first find the location where the new that have index greater than POS one position towards right to create
element will be inserted and then move all the elements (that have space for the new element.
a value greater than that of the new element) one space to the  In Step5, we increment the total number of elements in the array
right so that the space can be created to store the new value. by 1 and finally in Step 6, the new value is inserted at the desired
position.
7
CS8251-Programming in C
Eg: printf (\n Enter the number of elements in the array “);
scanf("%d", &n);
printf("\n Enter the array elements:”);
for (i=0; i<n; i++)
scanf ("%d", &arr[i]);
printf (“ \n Enter the number to be .inserted:”);
scanf ("%d", &num);
printf(“ Enter the position at which the number has to be added :”);
scanf(“%d”,&pos);
for(i=n-1;i>=pos;i--)
arr[i+1]=arr[i];
arr[pos]=num;
n++;
printf("\n The array after insertion of %d is: ", num);
for(i=0;i<n;i++)
printf("\t %d", arr[i]);
getch();
return 0;
}
o/p:
Enter the number of elements in the array: 5
Enter the array elements:
12345
Enter the number to be inserted: 7
Enter the position at which the number has to be added: 3
The array after insertion of 7 is:
123745
Eg:
Insert a number at a given location in an array Insert a number at a given location in an array that is already sorted
in ascending order
#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
int main() int main()
int i,n,num,pos,arr[10] ; int i,j,n,num,arr[10] ;
clrscr(); clrscr();
8
CS8251-Programming in C
2.5.3 Deleting an Element from an Array
printf (\n Enter the number of elements in the array “);
scanf("%d", &n);  Deleting an element from an array means removing a data element
printf("\n Enter the array elements:”); from an already existing array.
for (i=0; i<n; i++)  If the element has to be deleted from the end of the existing array,
scanf ("%d", &arr[i]); then the task of deletion is quite simple.
printf (“ \n Enter the number to be inserted:”);  We just have to subtract 1 from the upper_bound.
scanf ("%d", &num);
for(i=0;i<n;i++) Algorithm to delete the last element of an array:
{ Step 1: SET upper_bound = upper_bound - 1
if(arr[i]>num) Step 2: EXIT
{
for(j=n-1;j>=i;j--) Explanation:
arr[j+1]=arr[j];  Array is declared to store marks of all the students in the class.
arr[i]=num;  Now suppose there are 54 students and the student with roll number
break; 54 leaves the course. The marks of this student was therefore stored
} in marks [54].
}  We just decrement the upper_bound. Subtracting 1 from the
n++; upper_bound will indicate that there are 53 valid data in the array.
printf("\n The array after insertion of %dis:", num);
for(i=0;i<n;i++) Delete an element from the middle of an array
printf("\t %d", arr[i]);
getch();  Consider an array whose elements are arranged in ascending order.
return 0; Now, if an element has to be deleted from somewhere middle of the
} array.
o/p:  To do this, we will first find the location from where the element
Enter the number of elements in the array: 5 has to be deleted and then move all the elements (that have a value
Enter the array elements: greater than that of the element) one location towards the left so that
12345 location vacated by the deleted element is occupied by rest of the
Enter the number to be inserted: 6 elements.
The array after insertion of 6 is:
1 2 34 5 6 Algorithm to delete an element from the middle of an array
 The algorithm DELETE will be declared as DELETE (A, N,POS).
The arguments are as follows:

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.

Eg: merge two unsorted arrays

#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

 Binary search is a searching algorithm that works efficiently with a


sorted list.
 The algorithm finds the position of a particular element in the array.
 The mechanism of binary search can be better understood by using
the analogy of a telephone directory.

Algorithm for binary search

 In Step 1, we initialize the value of variables-BEG, END and POS.

 In Step 2, a while loop is executed until BEG is less than or equal to


END. Eg:\\ Binary Search

 In Step 3, value of MID is calculated. #include <stdio.h>


#include<conio.h>
 In Step 4, we check if the value of A [MID] is equal Ito VAL (item to int main()
be searched in the array).
15
CS8251-Programming in C
{ 8
int i, first, last, mid, n, search, array[100]; 9
printf("Enter number of elements\n"); 11
scanf("%d",&n); 43
printf("Enter %d integers\n", n); 485
for (i = 0; i < n; i++) Enter value to find 11
scanf("%d",&array[i]) 11 found at location 4
printf("Enter value to find\n");
scanf("%d", &search); Eg:
Given an array thatis declared and initialized a
first = 0; int A[ ] ={ 0,1,2,3,4,5,6,7,8,9,10};
last = n - 1; and the value to be searched is VAL = 9.
mid = (first+last)/2;  BEG = 0, END = 10, MID = (0 + 10)/2 = 5
while(first <= last)  Now, VAL = 9 and A[MID] = A[5] = 5
{  A[5] is less than VAL(9), therefore, we will now search for the value
if(array[mid] < search) in the latter half of the array. So, again we change the values of BEG
first = mid+ 1; and MID.
else if (array[middle] == search)  Now, BEG = MID + 1 = 6, END=10, MID=(6+10)/2 =16/2 = 8.
{  Now, VAL = 9 and A[MID] = A[8] = 8.
printf("%d found at location %d.\n", search, mid+1);  A [8] is less than VAL, therefore, we will now search for the value in
break; the latter half of the array. So, again we change the values of BEG
} and MID.
else  Now, BEG = MID + 1 = 9, END = 10, MID= (9+10)/2 = 9.
last = mid - 1;  NOWVAL = 9 and A[MID] = 9.In this algorithm we see that BEG
midle=(first+last)/2; and END are beginning and ending positions of the segment that are
} looking to search for the element.
if(first > last)  MID is calculated as (BEG + END)/2. Initially, BEG =
printf("Not found! %d isn't present in the list.\n", search); lower_bound and END= upper_bound.
return 0;  The algorithm will terminate when A[MID] = VAL.
}  When the algorithm ends, we will set POS = MID.
o/p:  POS is the position at which the value is present in the array.
Enter the no of elements : 7  However, if VAL is not equal to A[MID], then the values of BEG,
Enter 7 integers END, and· MID will be changed depending on whether VAL is
4 smaller or greater than A [MID].
5
16
CS8251-Programming in C
 If VAL< A [MID] , then VAL will be present in the left segment of Advantgaes :
the array. So, the value of END will be changed as, END = MID – 1.
 If VAL > A [MID] , then VAL will be present in the right segment of  Simple and easy to implement
the array. So, the value of be changed as, BEG = MID + 1.  Can be used for small data sets
 Finally, if VAL is not present in the array, then END will be less than
BEG. Disadvantgaes :
 When this happens, the algorithm will terminate and the search will
be unsuccessful.  Inefficient for large data sets

2.5.6 Selection Sort Eg:\\Selection sort

 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.

2.6.4 Passing the entire array


 When an entire array is to be sent to the called function, the calling
function just needs to pass the name of the array.
 In cases where we do not want the called function to make any
changes to the array, the array must be received as a constant array by
the called function.
 This prevents any type of unintentional modifications of the array
elements.
 To declare the array as a constant array, simply add the keyword
2.6.3 Passing addresses const before the data type of the array.

 Like ordinary variables, we can pass the address of an individual


array element by preceding the indexed array element with the
address operator (&).
 Therefore, to pass the address of the fourth element of the array to the
called function, we will write &arr [3].
 However, in the called function the value of the array element must
be accessed using the indirection (*) operator.

Fig: Passing entire array to function


20
CS8251-Programming in C
Eg: \\ Read and print an array of n numbers o/p:

#include<stdio.h> Enter the size of the array: 5


#include<conio.h> Enter the elements of the array: 1 2 3 4 5
voidread_array( intarr [], int); The elements of the array are: 1 2 3 4 5
voiddisplay_array( intarr[], int );
int main() 2.7 TWO-DIMENSIONAL ARRAYS
{  A one-dimensional array is organized linearly and only in one
intnum[10], n; direction.
clrscr ();  A two-dimensional array is specified using two subscripts where
printf(“ \n Enter the size of the array: ”); one subscript denotes row and the other denotes column.
scanf(“%d”,&n);
read_array(num, n);
display_array(num, n);
getch();
return 0;
}

void read_array(intarr[10] , int n)


{
inti;
printf(“ \n Enter the elements of the array:") ; 2.7.1 Declaring Two-dimensional Arrays
for(i=0;i<n;i++)
{  Similar to one-dimensional arrays, two-dimensional arrays must be
scanf(“%d”,&arr[i]); declared before being used.
}  The declaration statement tells the compiler the name of the array,
} the data type of each element in the array, and the size of each
dimension.
void display_array(intarr[10] , int n)  A two-dimensional array is declared as
{ data_type array_name[row_size] [column_size];
printf ("\n The elements of the array are n") ;  Therefore, a two-dimensional m x n array is an array that contains m
for(inti=0;i<n;i++) x n data elements and each element is accessed using two
printf("\t %d", arr[i]); subscripts,i and j where i<= m andj<= n.
}  Each dimension of the two-dimensional array is indexed from zero
to its maximum size minus one.
21
CS8251-Programming in C
 The first index selects the row and the second selects the column.  There are two ways of storing a two-dimensional array in memory.
 For example, if we want to store the marks obtained by 3 students in The first way is row major order and the second is column major
5 different subjects, then we can declare at two-dimensional array as order.
int marks [3] [5] ;  Let us see how the elements of a2D array are stored in row major
 Atwo-dimensional array called marks is declared that has m(3) rows order. Here, the elements of the first row are stored before the
and n(5) columns. The first element of the array is denoted by marks elements of the second and third row, i.e., the elements of the array
[0] [0], the second element as marks [0] [1], and so on. Here, marks are stored row by row where n elements of the first row will occupy
[0] [0] stores the marks obtained by the first student in the first the first n locations.
subject, marks [1] [0] stores the marks obtained by the second student
in the first subject, and so on.

 The pictorial form of a two-dimensional array is-given


 When we store the elements in a column major order, the elements of
the first column are stored before the elements of the second and third
column, i.e., the elements of the array are stored column by column
where m elements of the first column will occupy the first m
locations.

 In one-dimensional arrays, we have seen that computer does not keep


 Hence, we see that a 2D array is treated as a collection of one track of the address of every element in the array.
dimensional arrays.  It stores only the address of the first element and calculates the
addresses of other elements from the base address (address of the first
element).
 Same is the case with a two-dimensional array. Here also, the
computer stores the base address and the address of the other
elements is calculated using the following formula.
Address(A[I][J])=B_A+w{M(J-1)+(I-1)}, if the array elements are
stored in column major order,
Address(A[I][J])=B_A+w{N(I - 1)+(J -1)}, if the array elements are
stored in row major order.
 A rectangular picture ofa two-dimensional array, these elements will where, w is the word size, i. e., number of bytes required store
be actually stored sequentially in memory. element, M is the number of rows, N is the number of columns, I and
J are the subscripts of the array element and B_A is the base address.
22
CS8251-Programming in C
to separate the elements in the row as well as to separate the elements
of two rows.
 In case of one-dimensional arrays, if the array is completely
initialized, we may omit the size of the array. Same concept can be
applied to a two-dimensional array, except that only the size of the
first dimension can be omitted.
 The declaration statement given below valid.
int marks[] [3]={{90,87,78},{68, 62, 71}};
 To initialize the entire two-dimensional array to simply specify the
first value as zero, i.e., simply write
2.7.2 Initializing Two-dimensional Arrays int marks[2][3]={0};
 In order to input the values from the keyboard, you must use the
 Declaring a two dimensional array only reserves space for the array in
following code.
the memory.
for(i=0;i<2;i++)
 No values are stored in it.
for(j=0;j<2;j++)
 A two-dimensional array is initialized in the same way as a one-
scanf(“%d”, &arr[i][j]);
dimensional array.
 For example,
2.7.3Accessing the Elements of Two dimensional Arrays
int marks [2] [3] = {90, 87, 78, 68, 62, 71};
 The initialization of a two-dimensional array is done rowby row. The
 In case of one-dimensional arrays we used a single for loop to vary
above statement can also be written as
the index i in every pass, so that all the elements could be scanned.
int marks [2] [3]={{90,87,78},{68, 62, 71}};
 Since a two-dimensional array contains two subscripts, we will use
 The given two-dimensional array has 2 rows and 3columns.Here, the
two for loops to scan the elements.
elements in the first row are initialized first and then the elements of
 The first for loop will scan each row in the 2D array and the second
the second row are initialized.
for loop will scan individual columns for every row in the array.
Therefore,0
Eg:
marks [0] [0] = 90
marks [0] [1] = 87 #include<stdio.h>
marks [0] [2] = 78 #include<conio.h>
marks [1] [0] = 68 int main()
marks [1] [1] = 62 {
marks [1] [2] = 71 intarr[2] [2] = {12, 34, 56,32};
inti, j;
Therefore in the above eg., each row is defined as a one-dimensional
for(i=0;i<2;i++)
array of three elements that are enclosed in braces. Commas are used {
23
CS8251-Programming in C
printf("\n"); }
for(j=0;j<2;j++)
printf("%d\t", arr[i] [j]); o/p
} Enter number of rows: 3
return 0;
} 1
Output
12 34 1 1
56 32
Eg:// Pascal’s triangle 1 2 1

#include <stdio.h> 2.8 Operations on Two Dimensional Arrays


#include<conio.h>
int main()  Two dimensional arrays can be used to implement the mathematical
{ concepts of matrices.
int rows, coef = 1, space, i, j;
printf("Enter number of rows: "); Matrix Operations
scanf("%d",&rows);
 A matrix is a rectangular array of numbers or symbols arranged in
for(i=0; i<rows; i++) rows and columns. The operations on matrix are
{  Matrix Addition
for(space=1; space <= rows-i; space++)  Scalar product of a matrix
printf(" ");  Determinant of a matrix
for(j=0; j <= i; j++)  Transpose of a matrix
{
if (j==0 || i==0) 2.8.1 Matrix Addition
coef = 1;
else  If two matrices have the same dimensions, they may be added
coef = coef*(i-j+1)/j; together.
printf("%4d", coef);  The result is a new matrix with the same dimensions in which each
} element is the sum of the corresponding elements of the previous
printf("\n"); matrices.
} Eg:
getch();
return 0;
24
CS8251-Programming in C
#include<stdio.h>
#include<conio.h> printf(" \n Enter the elements of the second matrix");
int main() printf(" \n *** ** *** *** *** ** *** *** ***");
inti,j; for(i=0; i<rows2; i++)
int rows1,colsl, rows2, cols2, rows_sum, cols_sum; {
int mat1[5][5], mat2[5][5], sum[5][5]; for(j=0; j<cols2; j++)
clrscr(); scanf("%d",&mat2[i][j] );
}
printf("\n Enter the number of rows in the first matrix:”);
scanf("%d",&rows1) ;
printf("\n Enter the number columns in the first matrix: "); for(i=0; i<rows_sum; i++)
scanf("%d",&cols1) ; {
printf("\n Enter the number of rows in the second matrix: "); for(j=0; j<cols_sum; j++)
scanf ("%d" ,&rows2) ; sum[i][j]=mat1[i][j]+mat2[i][j];
printf("\n Enter the number of columns in the second matrix: ”); }
scanf ("%d" ,&cols2);
printf ("\n The elements of the resultant matrix are ”);
if(rowsl != rows2 || colsl != cols2) printf ("\n *************** ** ****** **");
{ for(i=0; i<rows_sum; i++)
printf("\n The number of rows and columns of both the matrices must be {
equal"); printf(“\n”);
getch(); for(j=0; j<cols_sum; j++)
exit (); printf ("\t %d", sum[i][j]);
} }

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.9 PASSING TWO-DIMENSIONAL ARRAYS TO FUNCTIONS

 There are three ways of passing two-dimensional arrays to functions.


First, we can pass individual elements of the array.
 This is exactly same as passing elements of a one-dimensional array.
Second, we can pass a single row of the two-dimensional array. This
is equivalent to passing the entire one-dimensional array to a
function. 2.9.2 Passing an Entire 2D Array
 Third, we can pass the entire two-dimensional array to the function.
 To pass a two-dimensional array to a function, we use the array name
as the actual parameter.
 However, the parameter in the called function must indicate that the
array has two dimensions.

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.

 All the characters of a string array are stored in successive memory


locations.
31
CS8251-Programming in C
 For example, if the user enters Hello World, then str will contain only
Hello. This is because the moment a blank space is encountered, the
string is terminated by the scanf () function. You may also specify
field width to indicate the maximum number of characters can be read
in.
 Unlike int(%d), float(%f), and char(%c),%s format not require
ampersand before the variable name.
 Using & operand with a string variable in the scanf statement
generates an error.

Using gets() function


 Consider the following declaration:
 The gets() function takes the starting address of the string which will
char str[3];
hold the input.
str = "HELLO";
 The string inputted using gets() is automatically terminated with a
The above declaration is illegal in C and would generate compile time
null character.
error because of two reasons. First, the array is initialized with
more elements than it can store. Second, initialization cannot be
Using getchar() function
separated from declaration.
 Strings can also be read by calling the getchar()function repeatedly to
2.10.1 READING STRINGS read a sequence of single characters (unless a terminating character is
entered) and simultaneously storing it in a character array.
 If we declare a string by writing char str [100];Then str can be read
by using three ways:
 using scanf function
 using gets() function
 using getchar(), getch( ) or getche( ) function repeatedly.
Using scanf function
 Strings can be read using scanf () by writing
scanf("%s", str);
Although the syntax of scanf( ) function is well known and easy to
use, the main pitfall with this function is that the function terminates
as soon as it finds a blank space.

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

Using printf() function

 A string can be displayed using printf() by writing


printf ("%s", str);
 We use the conversion character's' to output a string.
 We may also use width and precision specifications along with %s.
 The width specifies the minimum output field width. If the string is
short, extra space is either left padded or right padded. A negative Functions to read and write characters
width left pads short string rather than the default right justification.
The precision specifies the maximum number of characters to be Function Operation
displayed. If the string is long, the extra characters are truncated.
 For example printf("%5.3s",str); The above statement would print getchar() Used to read a character from the keyboard; waits
only the first three characters in a total field of five characters. Also for carriage return (enter key). It returns an integer,
these three characters are right justified in the allocated width. in which the low-order byte contains the character.
 To make the string left justified, we must use a minus sign. For getchar() can be used to input any key including
example,printf("%-5.3s", str); RETURN,TAB, and ESC.
getch() Is an alternative for getchar().Unlike getchar (), the
Using puts() function getch () function waits for a key press, after which
it returns immediately.
 The next method of writing a string is by using puts()function.
getche() Similar to getch(). The only difference is that
 The string can be displayed by writing puts(str) ;
getcheO echoes the character on screen.
 puts() is a simple function that overcomes the drawbacks of the
printf() function. putchar() Used to write a character to the screen. It accepts an
 The puts() function writes a line of output on the screen. integer parameter of which only the low-order byte
 It terminates the line with a newline character (' \n' ). is output to the screen. Returns the character written
 It returns an EOF (-1) if an error occurs and returns a positive number Or EOF(-1) if an error occurs.
on success.

33
CS8251-Programming in C

Fixed-length string

 When storing a string in a length format, you need to specify an


appropriate size for the string variable.
 If the size is too small, then you will not be able to store all the
elements in the string.
 On the other hand, if the string size is large, then unnecessarily
memory space will be wasted.

Variable-length string

 A better option is to use a variable length format in which the string


can be expanded or contracted to accommodate the elements in it.
 For example, if you declare a string variable to store the name of a
student. If a student has a long name of say 20 characters, then the
string can be expanded to accommodate 20 characters.
2.11 STRING TAXONOMY  On the other hand, a student name has only 5 characters, then the
 In C, we can store a string either in fixed-length format or in variable- string variable can be contracted to store only 5 characters.
length format.  However, to use a variable-length string format you need a technique
to indicate the end of elements that are a part of the string.
 This can be done either by using length-controlled string or a
delimiter.
34
CS8251-Programming in C
length-controlled string 2.12 OPERATIONS ON STRINGS

 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

 In this algorithm, I is used as an index of the string STR.


 To traverse each and every character of STR we increment the value
of I.
 Once the null character is encountered, the control jumps out of the
while loop and length is initialized with the value of I. This is because
the number of characters in the string constitutes its length.

Program to find the length of a string.


#include <stdio.h>
 In C a string is a variable length array of characters that is delimited #include <conio.h>
by the null character. int main()
{
char str[100] , i = 0, length;
clrscr() ;
35
CS8251-Programming in C
printf( "\n Enter the string :") ;
gets (str) ;  In the algorithm, we initialize I to zero.
while (str [i] != '\0')  Using I as the index of STR, we traverse each character from Step 2
i++; to 3.
length = i;  If the character is already in upper case, then it is copied in Upperstr
printf (" \n The length of the string is : %d", length); else the lower case character is converted into upper case by
getch() ; subtracting 32 from its ASCII value.
return 0;  The upper case character is then stored in Upperstr. Finally, when all
} the characters have been traversed a null character is appended to
Upperstr (as done in step 4)
Output
Enter the string: HELLO Program to convert characters of a string to upper case
The length of the string is : 5 #include <stdio.h>
#include <conio.h>
2.12.2 CONVERTING CHARACTERS OF A STRING INTO int main()
UPPER CASE {
charstr[100] , upper_str [100];
 In memory the ASCII codes are stored instead of the real value. int i=0, j=0;
 The ASCII code for A-Z varies from 65 to 91 and the ASCII code for clrscr() ;
a-z ranges from 97 to 123. printf("\n Enter the string:");
 So if we have to convert a lower case character to upper case, then we gets(str) ;
just need to subtract 32 from the ASCII value of the character. while(str[i] != '\0')
{
Algorithm to convert characters of a string into upper case. if(str[i]>='a' &&str[i]<='z')
Stepl: [INITIALIZE]SET I=0 upper_str[j]=str[i] -32;
Step 2: Repeat Step 3while STR[I] !=NULL else
Step 3 : IF STR[I] >= 'a' ANDSTR[I] <= ‘z ' upper_str[j]=str[i];
SETUpperstr[I] = STR[I] - 32 i++; j++;
ELSE }
SETUpperstr[I] = STR[I] upper_str [j]='\0' ;
[ENDOFIF] printf (" \n The string converted into upper case is: ");
SETI = I + 1 puts(upper_str) ;
[ENDOFLOOP] return 0;
Step 4: SETUpperstr [I] =NULL }
Step 5: EXIT
36
CS8251-Programming in C
Output Program to convert characters of a string into lower case
Enter the string: hello #include <stdio.h>
The string converted into upper case is: HELLO #include<conio.h>
int main()
2.12.3 CONVERTING CHARACTERS OF A STRING INTO {
LOWER CASE charstr[100], lower str [100];
inti=0,j=0;
 If we have to convert an upper case character into lower case, then we clrscr () ;
just need to add 32 to its ASCII value. printf("\n Enter the string :");
gets(str) ;
Algorithm to convert characters of a string into lower case while(str[i] != '\0')
Step 1: [INITIALIZE]SET I=0 {
Step 2: Repeat Step 3 while STR[I] !=NULL if(str[i]>='A' &&str[i]<='Z')
Step 3: IFSTR[I] >= 'A' ANDSTR[I]<= 'Z' lower_str[j]=str[i] + 32;
SETLowerstr[I] = STR[I] + 32 else
ELSE lower_str [j]=str[i] ;
SETLowerstr[I] = STR[I] i++; j++;
[ENDOFIF] }
SETI=I+1 lower_str[j] = '\0';
[ENDOFLOOP] printf("\n The string converted intolower case is : ");
Step 4: SET Lowerstr puts(lower_str) ;
[I] =NULL return 0;
Step 5: EXIT }
Output:
 In the algorithm, we initialize I to zero. Enter the string: HeLLo
 Using I as the index of STR, we traverse each character from Step 2 The string converted into lower case is: hello
to 3.
 If the character is already in lower case, then it is copied in lowerstr 2.12.4 CONCATENATING TWO STRINGS TO FORM A NEW
else the upper case character is converted into lowercase by adding 32 STRING
to its ASCII value.
 The lower case character is then stored in Lowerstr. Finally, when all  If S1 and S2 are two strings, then concatenation operation produces a
the characters have been traversed a null character is appended to string which contains characters of S1 followed by the characters of
Lowerstr(as done in Step 4). S2.

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.

ARRAYS OF STRI NGS


 We have seen that a string is an array of characters.
 For example, if we say char name [] = "Mohan", then name is a
string (character array) that has five characters.
 Now suppose that there are 2 0 students in a class and we need a
string that stores names of all the 2 0 students. How can this be done?
 Here, we need a string of strings or an array of strings. Such an array
of strings would store 20 individual strings. An array of string is
declared as, char names [20)[30);
 Here, the first index will specify how many strings are needed and the
second index specifies the length of every individual string. So here,
we allocate space for 20 names where each name can be a maximum
of 30 characters long.
 Hence the general syntax for declaring a two-dimensional array of
strings can be given as
<datatype><array_name> [row_size) [column_size] ;
46

You might also like