0% found this document useful (0 votes)
11 views62 pages

Unit II Arrays and Strings-book

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
11 views62 pages

Unit II Arrays and Strings-book

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 62

UNIT II ARRAYS AND STRINGS

Arrays: Introduction – Declaration of Arrays – Storing Values in Array – Accessing elements of


the Array– Operations on Array – one dimensional arrays – Two dimensional Arrays –String:
Declaring, Initializing, Printing and reading strings, String input and output functions, String
handling functions, Arrays of strings.

INTRODUCTION TO ARRAYS:

Anarray isacollectionof similar data items that arestored undera commonname.


Array is defined as finite ordered collection of similar data, stored in contiguous
(continues) memory locations.

It is a derived data type in C.


What is the use of array?

A single variable cannot store multiple values . But an array can store multiple values of
same data type in one single name.

Example where arrays are used,


 to store roll numbers of the students in a class
 to store marks of a students
 to store list of names of employees etc..

Array can store integer, float and double values which is said to be integer array.

Array that is used to store characters are said to be Character array.

Features of array:
Array might be belonging to any of the data types
Array size must be a constant value.

Array index starts with 0 and ends with n-1.


Element of an array is accessed using index or subscript.

Always, Contiguous (adjacent) memory locations are used to store array elements in
memory.
Advantage of array:
 Code Optimization: Less code is required; one variable can store numbers
of value.
 Easy to traverse data: By using array easily retrieve the data of array.
 Easy to sort data: Easily sort the data using swapping technique.
 Random Access: With the help of array index, you can randomly access
any elements from array.
Types of an array:

1. Single dimensional array


2. Multi dimensional array
Single(one)dimensionalarray:
 Array having only one subscript [ ] variable is called One-Dimensional array.
 It is also called as Single Dimensional Array or Linear Array or list.
 The elements of one dimensional array is also called as linear
array Declaring Array:
data_type array_name[size];
Example:

int roll_num[100];
char name[50];
double balance[10];

Initialization of an Array:

 After an arrayis declared it must be initialized.


 An array can be initialized in 2 ways (i) Compile time initialization
(ii)Run time initialization

(i) Compile time Array initialization:


- Compiletime initialization ofarrayelementsissame as ordinaryvariableinitialization.

Syntax:
data type array_name[size] = { list of values };

Example:
int marks[4]={ 67, 87, 56, 77 }; //integer array initialization

float area[5]={ 23.4, 6.8, 5.5 }; //float array initialization


double balance[10]={1000.0,20.0,3.4,7.2,50.0}

char str[10]={‘H’,‘a’,‘i’}; // character array

Accessing Array Elements:


We can access array elements with the help of index value of element.
Example:
int marks[50]={10,20,30,15,12}

here, marks is the array name and [50] is the maximum number of elements the array can
hold.
Printing array of numbers(Compile time initialization) Output:
#include<stdio.h> the elements in the
int main() array are
{ 95
int arr[40]={95,58,45,78}; 58
int i; 45
printf("the elements in the array are\n"); 78
for(i=0;i<=3;i++)
{
printf("%d\n", arr[i]);
}
return(0);
}
Note: [40] is the maximum size the array can hold.
(ii)Runtime Array initialization:
- An array can also be initialized at runtime using scanf() function.
- This approach is usually used for initializing large array elements , or to initialize
arrayby getting the input from the user.
Syntax:
for(i=0;i<n;i++) {
scanf(“%d”,&arr[i]); }

Reading and Printing array of elements( Run Time Output:


initialization) enter the size of an
#include<stdio.h> array
int main() 5
{ enter the elements of
int arr[100],n,i; an array
printf("enter the size of an array\n"); 45
scanf("%d",&n); 45
printf("enter the elements of an array\n"); 78
for(i=0;i<=n-1;i++) 4
{ 12
scanf("%d",&arr[i]); the elements are
} 45
printf("the elements are\n"); 45
for(i=0;i<=n-1;i++) 78
{ 4
printf("%d\n",arr[i]); 12
}
return(0);
}
Operations on 1Darray:
1. Subscripting an 1D array
It is an action of selecting an element from an array.
printf(“%d”, a[5]);

2. Assigning an array to another array


A variable can be assigned to another variable but array can’t be assigned to
another arraydirectly.

Output:
#include<stdio.h> //compilation error
int main()
{
int a[3],b[3]={1,2,3};
a[3]=b[3];
printf(“%d”, a[0]);eturn(0);
}

Example Programs: (using One Dimensional Array)

C program to find sum of array of elements: Output:


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

Illustrative Programs:
Searching: Searching is a process of finding a particular element in a given list.

Types:
1. Linearsearch
2. Binary search
Linear Search
- It is a process of finding an element in the list from the beginning and continues till
the end of the list.
Concept of linear Search:
i.
To search an element we want, we start with the first element in the list. If this is the
required element, our search is over.
ii. Else, we take up the second element and see if this is the element we search for.
iii. If this is too not the element, we pick up the third element and compare.
iv. This process continues until the element we search for is found.
Advantages:

The linear search is simple - It is very easy to understand and implement;



 It does not require the data in the array to be stored in any particular order.
Disadvantages:
The linear search is inefficient(takes more time) if the list has more number of elements.
C program to perform Linear Search:
#include<stdio.h> Output:
int main() Enter the number of
{ elements in array
int array[100], item, i, n, found=0; 4
printf("Enter the number of elements in array\n"); Enter the elements
scanf("%d",&n); 6
printf("Enter the elements \n", n); 12
for (i = 0; i < n; i++) 5
scanf("%d", &array[i]); 8
Enter the element to
printf("Enter the element to search\n"); search
scanf("%d", &item); 5
5 is present in array and
for (i = 0; i <=n-1; i++) position is 2
{
if (array[i] == item) // if required element found
{
found=1;
break;

}
}

if (found==1)

} printf("%d is present in array and position is %d\n", item,i);


Binary Search:
 Binary search is an algorithm used to find an element in an sorted array by using the
divide and conquer concept.
 This method can be applied only if list is in sorted order.
 Listisdividedintotwohalves separatedbymiddleelement.
Left half Middle Right half
Concept of Binary search:

i. Find the middle element


ii. Check the middle element with the element to be found
iii. If the middle element is equal to that element, then it will provide the output.
iv. If the value is not same, then it will check whether the middle element value is
less than or greater than the element to be found.
v. If the value is less than that element, then the search will start with the elements
next to the middle element.
vi. If the value is high than that element, then the search will start with the
elements before to the middle element.
vii. This process continues, until that particular element has been found.
Example: Consider the following set of elements in array where 31 is the element to be
searched.
Middle =(First+Last)/2 =>(0+9)/2 =4.5=>4

Now we compare the value stored at location 4, with the value being searched, i.e. 31. We
find that the value at location 4 is 27, which is not a match. As the value is greater than 27

and we have a sorted array, so we also know that the target value must be in the upper
portion of the array.

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

Advantages:

 Faster than linear search.


Disadvantages :

 Binary search algorithm can work only with the sorted array (either ascending or
descending order).
 It is time consuming and waste of memory allocation.
If the element to be identified occurs more than once, then it will show the occurrence of
the first one.
Program for Binary search: Output:
#include <stdio.h>
enter size of array
int main() 6
{ enter the
int i, first, last, middle, n, item, arr[50]; elements 5
printf("enter size of array");
12
scanf("%d",&n);
4
printf("enter the elements\n");
7
for (i = 0; i <=n-1; i++)
18
{
240
scanf("%d",&arr[i]);
Enter element to find
}
18
printf("Enter element to find\n");
scanf("%d", &item); 18 found at location 4

first = 0; last = n - 1;

middle = (first+last)/2;
while (first <= last)

{
if (arr[middle] < item)
{
first = middle + 1;

}
else if (arr[middle] == item)
{
printf("%d found at location %d.\n", item, middle);
break;

}
else

{
last = middle - 1;
middle = (first + last)/2;

}
Selection Sort:
The selection sort algorithm sorts an array by repeatedly finding the minimum element
(considering ascending order) from unsorted part and putting it at the beginning.

The algorithm maintains two subarrays in a given array.


1) The subarray which is already sorted.
2) Remaining subarray which is unsorted.
In every iteration of selection sort, the minimum element (considering ascending order)
from the unsorted subarray is picked and moved to the sorted subarray.

Consider the following example:

Program to perform selection sorting (ascending order) Output:


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

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


elements enter size of array
#include <stdio.h> 5
int main() enter the elements
{ 6
int i,j,a[20], sum=0,n,temp,b[20]; 4
float mean=0.0, median=0.0; 3
printf("enter size of array\n"); 2
scanf("%d",&n); 4
printf("enter the elements\n"); mean value is
for (i = 0; i <=n-1; i++) 3.800000median is 4.000000
{
scanf("%d",&a[i]);
sum=sum+a[i]; //Calculating mean
}
mean=(float)sum/(float)n;
printf("mean value is %f",mean);
for(i=0;i<=n-1;i++)
{
for(j=i+1;j<=n-1;j++) //calculating median
{
if(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
} if(n
%2==0)
median=(float)(a[n/2]+a[(n-1)/2])/2;
else
median=a[(n-1)/2];
printf("median is %f",median);
}

Two dimensional Arrays:( Multidimensional Arrays


- In 2-dimentional array, elements are arranged in row and column format.
- An array with two subscripts[ ][ ] is termed as two dimensional arrays.
- A two dimensional array enables us to store multiple rows of elements, in form of
matrix.

Array Declaration Syntax:

data_type arr_name [num_of_rows][num_of_column];

Example:
int arr[2][2];
- this array can hold 2*2=4 elements totally.
Array Initialization:

(i) Compile time Initialization


Array Initialization Syntax:
data_type arr_name[2][2] = {{0,0},{0,1},{1,0},{1,1}};
Example:
int arr[2][2] = {1,2, 3, 4};
int arr[2][3] = { {0,0,0}, {1,1,1} };

int arr[2][3] = { 0,0,0, 1,1,1 };

Array accessing syntax:


arr_name[index];

Example:
int arr[2][2] = {1,2, 3, 4};
arr [0] [0] = 1;

arr [0] ]1] = 2;

arr [1][0] = 3;

arr [1] [1] = 4;

Invalid initializations:
Following initializations are wrong and invalid.
int arr[2][ ]={1,2,3,4}; // We need to mention the column size.
Otherwise compiler do not know where the first row size ends.

ii) Run Time initialization:


Syntax:
for(i=0;i<n;i++)
{

for(j=0;j<n;j++)

scanf(“%d”,a[i][j]);
Programs on two dimensional arrays:
C Program To read and display 2 dimensional matrix Output:
#include <stdio.h> enter the size of row and
int main() column
{ 3
int a[10][10]; 3
int i,j,m,n; enter the elements of
printf("enter the size of row and column\n"); matrix
scanf("%d%d",&m,&n); 5
printf("enter the elements of matrix\n"); 2
for(i=0;i<=m-1;i++) 5
{ 2
for(j=0;j<=n-1;j++) 5
{ 2
scanf("%d",&a[i][j]); 5
} 2
} 5
printf("the elements are\n"); the elements are
for(i=0;i<=m-1;i++) 5 2 5
{ 2 5 2
for(j=0;j<=n-1;j++) 5 2 5
{
printf("%d\t",a[i][j]);
}
printf("\n");
}
return(0);
}
Program for Matrix Addition: Output:
#include <stdio.h> Enter the size of row and
int main() column
{ 2
int a[10][10], b[10][10]; // array declaration for matrix a&b 2
int c[10][10]={0}; // c matrix initialized to 0 Enter the elements of A
int i,j,m,n; matrix
printf("Enter the size of row and column\n"); 1
scanf("%d%d",&m,&n); //reading size or row and column 3
printf("Enter the elements of A matrix\n"); 2
for(i=0;i<=m-1;i++) 5
{ Enter the elements of B
for(j=0;j<=n-1;j++) matrix
{ 1
scanf("%d",&a[i][j]); //getting the elements of A matrix 5
} 5
} 6
printf("Enter the elements of B matrix\n"); Sum of two matrices:-
for(i=0;i<=m-1;i++) 2 8
{ 7 11
for(j=0;j<=n-1;j++)
{
scanf("%d", &b[i][j]); //getting the elements of B matrix
}
}
printf("Sum of two matrices:-\n");
for(i = 0;i<=m-1;i++)
{
for(j=0;j<=n-1;j++)
{
c[i][j] = a[i][j] + b[i][j]; // addition of A and B matrix
printf("%d\t", c[i][j]);
}
printf("\n");
}
return(0);
}
Same program can be written for matrix subtraction with - sign c[i][j] = a[i][j] - b[i][j];

Matrix multiplication: Output:


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

printf("Product Matrix is\n");


for(i= 0; i <=m-1; i++)
{
for(j = 0; j<=n-1; j++)
printf("%d ", a[i][j]);
}
printf("\n");
return(0);
}
C Program to TRANSPOSE a matrix: Output:
#include <stdio.h> Enter the SIZE of the matrix
int main() 2
{ 3
int a[10][10], i, j, m, n; Enter the ELEMENTS of the
matrix
printf("Enter the SIZE of the matrix \n"); 2
scanf("%d %d", &m, &n);
printf("Enter the ELEMENTS of the matrix\n"); 1
for (i = 0; i <= m-1; i++) 5
{ 3
for (j = 0; j<= n-1; j++) 7
{ 8
scanf("%d", &a[i][j]); The given matrix is
} 215
} 378
printf("The given matrix is \n"); Transpose of matrix is
for (i = 0; i <=m-1; ++i) 23
{ 17
for (j = 0; j <= n-1; ++j) 58
{
printf(" %d", a[i][j]);
}
printf("\n");
}
printf("Transpose of matrix is \n");
for (j = 0; j <=n-1; j++) //interchanging rows and
columns
{
for (i = 0; i <=m-1; i++)
{
printf(" %d", a[i][j]);
}
printf("\n");
} return(0);
}
C program to find determinant of 2*2 Matrix :
#include<stdio.h>
int main()
{ Example:
int a[2][2],i,j; Output:
long determinant;
printf("Enter the elements of matrix:\n "); Enter the elements of matrix:
for(i=0;i<2;i++) 8
for(j=0;j<2;j++) 3
scanf("%d",&a[i][j]); 2
1
printf("\nThe matrix is\n"); The matrix is
for(i=0;i<2;i++) 8 3
{ 2 1
printf("\n"); for(j=0;j<2;j+ Determinant is :2
+)
printf("%d\t",a[i][j]);
}
determinant = a[0][0]*a[1][1] - a[1][0]*a[0][1];
printf("\nDeterminant is :%ld",determinant);
return(0);
}
Determinant of 3*3 matrix Enter the elements of
#include<stdio.h> matrix: 1
int main() 5
{ 4
int a[3][3],i,j; 2
int determinant=0; 1
printf("Enter the elements of matrix: "); 2
for(i=0;i<3;i++) 1
for(j=0;j<3;j++) 2
scanf("%d",&a[i][j]); 1
printf("\nThe First matrix is\n");
for(i=0;i<3;i++) The First matrix is
{
printf("\n"); for(j=0;j<3;j+ 1 5 4
+) 2 1 2
printf("%d\t",a[i][j]); 1 2 1
} Determinant of matrix is: 9
for(i=0;i<3;i++)
determinant = determinant + (a[0][i]*(a[1][(i+1)%3]*a[2]
[(i+2)%3] -
a[1][(i+2)%3]*a[2][(i+1)%3]));
printf("\nDeterminant of matrix is: %d",determinant);
return(0);
}

4. Transpose of a matrix
#include <stdio.h>
#include<conio.h>
void main()
{
int r, c, i, j, a[10][10];
clrscr();
19
printf("Enter the number of rows and columns of matrix\n");
scanf("%d%d", &r, &c);
printf("Enter the elements of matrix\n");
for (i = 0; i< r; i++)
for(j= 0; j< c; j++)
scanf("%d",&a[i][j]);
printf("Transpose of entered matrix :-\n");
for (j= 0; j < r; j++)
{
for( i = 0 ; i< c ; i++ )
{
printf("%d\t",a[i][j]);
}
printf("\n");

}
getch();
}

Three Dimensional array:


Total number of elements that can be stored in a multidimensional array can be
calculated by multiplying the size of all the dimensions.

Example:

int arr[5][10][20] can store total (5*10*20) = 1000 elements totally.

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

20
2. STRING AND CHARACTER ARRAY

 String is a sequence of characters that is treated as a single data item and terminated by null
character '\0'.
 C language does not support strings as a data type.
 A string is actually one-dimensional array of characters in C language.
For example
 The string "hello friend" contains 13 characters including '\0' character which is automatically
added by the compiler at the end of the string.

2.1 Declaring and Initializing a string variables


 There are different ways to initialize a character array variable.

For Example: 1. “God Bless!!”


2. “A”
3. “ ” Empty string

Example:
char edu[ ]={‘C’,’O’,’L’,’L’,’E’,’G’,’E’,‘\0’};
char name[10]="india"; //valid character array initialization

MEMORY ALLOCATION OF THE ABOVE STRING


C O L L E G E \0
2001 2002 2003 2004 2005 2006 2007 2008

 When you initialize a character array by listings all its characters separately then you must use
the '\0' character explicitly.
Some examples of illegal initialization of character array are,
 char name[3]="array"; //Illegal
 char str[4];
 str="array"; //Illegal
Points to remember
 To save the word “hai” need 4 bytes in memory. Because the string terminated by null character. But the
length of the string is 3.
21
 The empty string “ ” have one byte of memory.
 ‘\0’- terminate the string. It determines the end of the string.

2.2 STRING INPUT AND OUTPUT

 Input function scanf() can be used with %s format specifier to read a string input from the terminal. But
there is problem with scanf() function, it terminates its input on first white space it encounters.
 Therefore if you try to read an input string "Hello World" using scanf() function, it will only read Hello
and terminate after encountering white spaces.
 However, C supports a format specification known as the edit set conversion code %[..] that can be
used to read a line containing a variety of characters, including white spaces.
 Example:
#include< stdio.h>
#include< conio.h>
void main()
{
char str[20];
clrscr();
printf("Enter a string");
scanf("%[^\n]",&str);
printf("%s",str);
getch();
}
 Another method to read character string with white spaces from terminal is gets() function.
#include< stdio.h>
#include< conio.h>
void main()
{
char text[20];
gets(text);
printf("%s",text); or puts(text);
getch();
}
2.3 ARITHMETIC OPERATIONS ON CHARACTERS:
 Whenever a character constant is used in an expression, it is automatically converted into an integer
value by the system.
 For example, if the machine uses the ASCII representation, then
x=’a’;
22
printf(“%d”,a);
 This statement results ASCII value of ‘a’. This display the number 97 on the screen.
2.4 STRING HANDLING FUNCTIONS
The c string library provides a large number of functions that can be used for string manipulations. To
access this functions the user need to include #include<string.h>header file with the program.
2.4.1 strlen()

This function is used to count and return the number of characters present in a given string.

Syntax:

var = strlen(string);

Example:
#include<stdio.h>
#include<string.h>
#include<conio.h>
void main()
{
char name[ 50] = "Computer"; OUTPUT
int length;
length = strlen(name); Length of the String:
printf("Length of the String:\n”); Computer is 8

printf(“Computer is %d”,length);
getch();
}
Explanation
In the above program, strlen() function counts the number of character in the string without the NULL
character.

2.4.2 strcpy()
This function is used to copy the contents of one string to another string.

Syntax:
strcpy(string1,string2);
23
Here the content of string2 is copied to string1.

Example:
#include<stdio.h>
#include<string.h>
#include<conio.h>
void main()
{
char str1[20]; OUTPUT
char str2[20] = "Computer";
strcpy(str1,str2); String1 is Computer
puts(“String1 is”);
String2 is Computer
puts(str1);
puts(“String2 is”);
puts(str2)
getch();
}

Explanation
In the above example, two array variables str1[20] and str2[20] has been declared. The function strcpy
copies the character of str2[20] to str1[20].That is it copies character one by one from the source string str2[20]
to the destination string str1[20].

2.4.3 strcat()
The strcat() function is used to concatenate or combine two strings together and forms a new
concatenated string.

Syntax:

strcat(string1,string2);

Here the content of string2 is combined with string1 and it removes the null character (\0) of string1 and
places string2 from there.

Example:
#include<stdio.h>
#include<string.h> OUTPUT
24
Before string concatenations
Character
Array
After string concatenations
CharacterArray
#include<conio.h>
main()
{
char str1[30]="Character ";
char str2[30]=" Array";
puts(“Before string concatenations:”)
puts(str1);
puts(str2);
strcat(str1,str2);
puts(“After string concatenations:”)
puts(str1);
puts(str2);
getch();
}
Explanation
In the above example program, two strings are entered in character array str1[30] and str2[30]. The
strcat() function concatenates both the strings , i.e. second string is appended (or) combined to the first string.
By using puts() function it displays the content of the str1[30] with concatenation of the two strings.

2.4.4 strcmp()

 This function is used to compare two strings to find out whether the strings are same or different. The
two strings are compared character by character until reach the end of the string or until the
corresponding characters differ.
 It returns the ASCII difference of the first dissimilar corresponding character.

Syntax:
strcmp(string1,string2);

The function strcmp() compares str1 and str2.


Example:
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
int res;
char str1[25] , str2[25] ;
25
clrscr();
puts(“Enter string1:”);
gets(str1);
puts(“Enter string2:”);
gets(str2);
res=strcmp(str1,str2);
if(res==0)
puts(“Strings are equal”);
else
puts(“Strings are not equal”);
getch();
}

Explanation
strcmp(str1,str2) returns a integer value:
 0 if str1 and str2 are equal , or
 >0 if str1 is greater than str2, i.e. str1 comes after str2 in alphabetic order
 <0 if str1 is lesser than str2 i.e. str1 comes before str2 in alphabetic order

RETURN VALUE EXPLANATION

<0 str1 is less than str2

=0 str1 is equal to str2


>0 str1 is greater than str2
2.4.5 strcmpi()
This function is used to compare two strings without case sensitivity.
Syntax:
strcmpi(string1,string2);

Example:
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
int res;
26
char str1[25] , str2[25] ;
clrscr();
puts(“Enter string1:”);
gets(str1);
puts(“Enter string2:”);
gets(str2);
res=strcmpi(str1,str2); OUTPUT
if(res==0) Enter string1:
Hello
puts(“Strings are equal”);
Enter string2:
else Hi
puts(“Strings are not equal”); Strings are not equal
getch();
}

2.4.6 strrev()
This function is used to reverse all the characters of a string except the terminating null character. This
function takes only one argument and returns one argument.
Syntax:

var = strrev(string);

Example:
#include<stdio.h>
#include<conio.h>
#include<string.h>
main() OUTPUT
{
Enter String :Hello
char str1[25] ;
puts(" Enter a String :”); Reversed String is : olleH
gets(str1);
strrev(str1)
puts("Reversed String is :”);
puts(str1);
getch();
}
Explanation

27
In the above program, it prints reverse string that is received by character array str1[25] by using
strrev() function.

2.4.7 strlwr()

This function can be used to convert any string to a lower case. When you are passing any upper case
string to this function it converts it to lower case.

Syntax:

Example: var = strlwr(upper_case_string);


#include<stdio.h>
#include<conio.h>
OUTPUT
#include<string.h>
main() Enter a string:
{ HELLO
char str1[25] ;
Lowercase String is:
puts("Enter a string: ");
gets(str1); hello
strlwr(str1)
puts("Lowercase String is :”);
puts(str1);
getch();
}
Explanation
In the above program, string is entered in capital letter. The string is passed to the function strlwr(). This
function converts the string to a lower case characters.

2.4.8 strupr()
This function is the same as strlwr( ) but the difference is that strupr( ) converts lower case strings into
upper case.

Syntax:

var = strupr(lower_case_string);

28
Example:
#include<stdio.h>
#include<conio.h>
OUTPUT
#include<string.h>
main() Enter a string:
{ hello
char str1[25] ;
Uppercase String is:
puts("Enter a string: ");
gets(str1); HELLO
strupr(str1)
puts("uppercase String is :”);
puts(str1);
getch(); }

Explanation
In the above program, string is entered in lower case. The string is passed to the function strupr(). This
function converts the string to a upper case.
2.4.9 strset()

This function sets all characters in a string to a specific character.


Syntax:

strset(string,ch);

Example:
#include<stdio.h> OUTPUT
#include<conio.h> Before using strset() , string is :
#include<string.h>
123456789
main()
{ After using strset() , string is :
char str1[10]=”123456789” ; $$$$$$$$$
char ch=’$’;
puts("Before using strset() , string is : ");
puts(str1);
strset(str1,ch);
puts("After using strset() , string is : ");
29
puts(str1);
getch();
}
Explanation
In the above program, All the characters (letters, digits, special characters and white-space characters)
within a string are set to a specific character

2.4.10 strchr()

This function scans a string for the 1st occurrence of a given character.
Syntax:

ptr = strchr(str,ch);

Example:
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char str1[20],ch; OUTPUT
char *ptr; Enter a string:
puts("Enter a string : ");
Hello
gets(str1);
puts("Enter a character to be found : "); Enter a character to be found :
scanf(“%c”,&ch); e
ptr=strchr(str1,ch); Located at the index 1
if(ptr==NULL)
puts(“Character not found”);
else
printf(“Located at the index %d”,ptr-str);
getch();
}
Remark:
The terminating null character is also considered to be a part of the string.
30
2.4.11 strrchr()
This function locates the last occurrence of a character in a given string.
Syntax:

OUTPUT
ptr = strrchr(str,ch);
Enter a string:
Example: Hello
#include<stdio.h>
Enter a character to be found :
#include<conio.h>
#include<string.h> l
void main() Located at the index 3
{
char str1[20],ch;
char *ptr;
puts("Enter a string : "); OUTPUT
gets(str1); Enter a string:
puts("Enter a character to be found : "); Hello
scanf(“%c”,&ch);
ptr=strrchr(str1,ch); Enter a character to be found :
if(ptr==NULL) y
puts(“Character not found”); Character not found
else
printf(“Located at the index %d”,ptr-str);
getch();
}
Remark:
The terminating null character is also considered to be a part of the string.

2.4.12 strstr()
This function finds the second string in the first string . It returns the pointer location from where the
second string starts in the first string. Otherwise it returns a NULL character.

Syntax:

ptr = strstr(str1,str2);

31
Example:
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char str1[20],str2[20]; OUTPUT
char *ptr; Enter a string:
puts("Enter a string : "); Hello Readers!!
gets(str1); Enter a string to be found :
puts("Enter a string to be found : "); Read
gets(str2);
Found at the index 6
ptr=strstr(str1,str2);
if(ptr==NULL) Found in Readers!!
puts(“String not found”);
else
{
printf(“Found at the index %d”,ptr-str1);
printf(“Found in %s”,ptr);
}
getch();
}

2.4.13 strncpy()
This function is used to copy at the most ‘n’ characters of a source to the destination string

Syntax:

strncpy(string1,string2, int n);

Example:
#include<stdio.h>
#include<string.h>
#include<conio.h>
void main()
{
OUTPUT
char str1[20],str2[20] = "Computer";
String1 is Com
32
String2 is Computer
int n=3;
strncpy(str1,str2,n);
puts(“String1 is”);
puts(str1);
puts(“String2 is”);
puts(str2)
getch();
}

Explanation
In the above example, they have declared two array variables str1[20] and str2[20]. The function strncpy
copies ‘n’ number of character of str2[20] to str1[20].

2.4.14 strncat()
The strncat() function is used to concatenates a portion of one string with another. It appends at the most
n characters of a source string to a destination string.

Syntax:
strncat(string1,string2,int n);

Example:
#include<stdio.h>
OUTPUT
#include<string.h>
Before string concatenations
#include<conio.h>
Character
main()
Array
{
After string concatenations
char str1[30]="Character ";
CharacterAr
char str2[30]=" Array";
Array
int n=2;
puts(“Before string concatenations:”)
puts(str1);
puts(str2);
strncat(str1,str2,n);
puts(“After string concatenations:”);
puts(str1);
puts(str2);

33
getch();
}

2.4.15 strncmp()
This function is used to compare a portion of two strings to find out whether they are same or different.
Syntax:

strncmp(string1,string2,int n);

Example:
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main() OUTPUT
Enter string1:
{
Hello
int res,n; Enter string2:
char str1[25] , str2[25] ; Hi
clrscr(); Enter the value of n:
puts(“Enter string1:”); 1
String portions are equal
gets(str1);
OUTPUT
puts(“Enter string2:”); Enter string1:
gets(str2); Hello
puts (“Enter the value of n:”); Enter string2:
scanf(“%d”,&n); Hi
Enter the value of n:
res=strncmp(str1,str2,n);
2
if(res==0) String portions are not equal
puts(“String portions are equal”);
else
puts(“String portions are not equal”);
getch();
}

2.4.16 strncmpi()
This function is used to compare a portion of two strings without case sensitivity.

Syntax:

strncmpi(string1,string2,int n);
34
Example:
#include<stdio.h> OUTPUT
#include<conio.h> Enter string1:
#include<string.h> Hello
void main() Enter string2:
{ hi
int res,n; Enter the value of n:
char str1[25] , str2[25] ; 1
clrscr(); String portions are equal
puts(“Enter string1:”); OUTPUT
gets(str1); Enter string1:
puts(“Enter string2:”); Hello
gets(str2); Enter string2:
puts (“Enter the value of n:”); hi
scanf(“%d”,&n); Enter the value of n:
res=strncmpi(str1,str2,n); 2
if(res==0) String portions are not equal
puts(“String portions are equal”);
else
puts(“String portions are not equal”);
getch();
}

2.4.17 strnset()
This function is used to sets the first n characters in a string to a specific character.
Syntax:

strset(string,ch,n);

Example:
#include<stdio.h>
#include<conio.h>
#include<string.h>
main()
{
35
char str[10],ch;
int n;
puts(“Enter the string:”); OUTPUT
gets(str); Enter the string:
puts(“Enter the character:”); Hello Readers!!
scanf(“%c”,&ch); Enter the character:
puts(“Enter the value of n:”); &
scanf(“%d”,&n); Enter the value of n:
puts("Before using strnset() , string is : "); 7
puts(str); Before using strnset() , string is :
strnset(str,ch,n); Hello Readers!!
puts("After using strnset() , string is : "); After using strnset() , string is :
puts(str); &&&&&&&eaders!!
getch();
}

Function purpose Syntax


Strlen counts the number of character in a string strlen(string);
Strcmp compares two strings and return zero if strcmp(str1, str2);
the strings are equal
Strcmpi Used to compare two strings without case strcmpi(str1, str2);
sensitivity
Strcat joins or appends two strings strcat(str1, str2);
Strcpy copies one string to another strcpy(str1,str2);
Strrev reverse the given string strrev(str1);
strlwr convet the string to lower case strlwr(str1);
strupr convet the string to upper case strupr(str1);
strchr find the first occurrence of the given strchr(str1,ch);
character
strrchrf find the last occurrence of the given strrchr(str1,ch);
character
strstr find the first occurrence of the substring strstr(str1,ch);
in a other string
strset set all character of a string to a specific strset(str1,ch);
character

2.5 STRING ARRAYS


The list of strings can be stored by creating an array of one-dimensional character array.
Syntax:

36
char identifier[row][column]
Example:
char name[3][30];
 The array can store 3 strings of maximum 30 characters each.
 A list of names can be treated as a table of strings. Two dimensional character array can be used to
store the entire list.
char city[][20]=={
“madras”,
“hydrabad”,
“Bombay”
};

2.6 SAMPLE PROGRAMS ON STRINGS:

STRING LENGTH WITHOUT USING LIBRARY FUNCTION:

#include<stdio.h>
#include<conio.h>
void main()
{
char word[12];
int count=0,i;
clrscr();
printf("enter the string");
scanf("%s",word);
for(i=0;word[i]!='\0';i++)
{
count++;
}
printf("the length of the string is %d",count);
getch();
}
OUTPUT:
enter the string
hai
the length of the string is 3

37
CONVERT THE STRING FROM LOWER CASE TO UPPERCASE WITHOUT USING LIBRARY
FUNCTION.

#include<stdio.h>
#include<conio.h>
void main()
{
char str[12];
int len,i;
clrscr();
printf("enter teh srting");
gets(str);
len=strlen(str);
for(i=0;i<=len;i++)
{
if(str[i]>=97&&str[i]<=122)
{
str[i]=str[i]-32;
}
}
printf("the string in lower case %s",str);
getch();
}
OUTPUT:
enter the string
hai
the length of the string is 3

CONVERT THE SRTING FROM UPPER TO LOWER WITHOUT USING LIBRARY FUNCTION

#include<stdio.h>
#include<conio.h>
void main()
{
char str[12];
int len,i;
clrscr();
printf("enter teh srting");
38
gets(str);
len=strlen(str);
for(i=0;i<=len;i++)
{
if(str[i]>=65&&str[i]<=90)
{
str[i]=str[i]+32;
}
}
printf("the string in lower case %s",str);
getch();
}
OUTPUT:
enter teh srting HAI
the string in lower case hai

STRING COPY WITHOUT USING LIBRARY FUNCTION


#include<stdio.h>
#include<conio.h>
void main()
{
char str[12],dest[12];
int len,i;
clrscr();
printf("enter the string");
gets(str);
len=strlen(str);
for(i=0;str[i]!='\0';++i)
{
dest[i]=str[i];
}
printf("the copied string =%s",dest);
getch();
}
OUTPUT:
enter the string
panimalar
the copied string panimalar
39
STRING CONCATENATION WITHOUT USING LIBRARY FUNCTION
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char word1[12],word2[20];
int length=0,i;
clrscr();
printf("enter the string1\n");
scanf("%s",word1);
printf("enter the string2\n");
scanf("%s",word2);
length=strlen(word1);
for(i=0;word2[i]!='\0';i++)
{
word1[length]=word2[i];
length++;
}
word1[length]='\0';
printf("the concatenated string is %s:\n",word1);
getch();
}

OUTPUT:
enter the string1
hello
enter the string2
hai
the concatenated string is hellohai:

STRING REVERSE WITHOUT USING LIBRARY FUNCTION


#include<stdio.h>
#include<conio.h>
void main()
{
int ;

40
char a[50];
printf("Enter a String to reverse");
gets(a);
l=strlen(a);
printf("reversed string is”);
for(i=l-1;i>=0;i--)
{
printf("%s",a[i]);
}
getch();
}
OUTPUT:

Enter a String to reverse


Hai
reversed string is
iaH

STRING COMPARE WITHOUT USING LIBRARY FUNCTION


#include <stdio.h>
#include <conio.h>
void main()
{
char a[50], b[50];
int i, temp = 0;
printf("Enter the first string");
gets(a);
printf("Enter the second String");
gets(b);
for(i=0; (a[i]!='\0')||(b[i]!='\0'); i++)
{
if(a[i] != b[i])
{
temp = 1;
break;
}
}
if(temp == 0)
printf("Both strings are same.");
else
printf("Both strings not same.");
getch();
41
}
OUTPUT:
Enter the first string
Computer
Enter the second String
Computer
Both strings are same.

TO CHECK THE GIVEN STRING IS PALINDROME OR NOT USING LIBRARY FUNCTION

#include <stdio.h>
#include<conio.h>
#include <string.h>
void main()
{
char a[100], b[100];
clrscr();
printf("Enter the string\n");
scanf("%s",a);
strcpy(b,a);
strrev(b);
if (strcmp(a,b) == 0)
printf("Entered string is a palindrome.\n");
else
printf("Entered string is not a palindrome.\n");
getch();
}

OUTPUT:
Enter the string:
madam
Entered string is a palindrome.

TO CHECK THE GIVEN STRING IS PALINDROME OR NOT WITHOUT USING LIBRARY


FUNCTION
#include<stdio.h>
#include<conio.h>
42
void main()
{
int len=0,i,j,flag=0;
char word1[10];
clrscr();
printf("enter the string");
scanf("%s",word1);
len=strlen(word1);
i=0;
j=len-1;
while(i<len)
{
if(word1[i]!=word1[j])
{
flag=1;
break;
}
i++;
j--;
}
if(flag==0)
{
printf("string is palindrome");
}
else
{
printf("string is not a palindrome");
} getch();
}
OUTPUT:
enter the string
liril
string is palindrome
2.7 SORTING:
 Sorting is the process of arranging elements in ascending or in descending order.
1. The elements can be arranged in a sequence from smallest to largest such that every element is less
than or equal to its next neighbor in the list. Such an arrangement is called ascending order.

43
For example:
List[i] <= List[ i + 1 ] , 0 < i < N-1.

2. The elements can be arranged in a sequence from largest to smallest such that every element is greater
than or equal to its next neighbor in the list . Such an arrangement is called ascending order.
For example:
List[i] >= List[ i + 1 ] , 0 < i < N-1.

Different types of Sorting algorithms:


 Selection Sort
 Bubble Sort
 Insertion Sort
 Merge Sort
 Quick Sort
 Shell Sort
 Radix Sort
 Merge Sort

2.7.1 TYPES OF SORTING

Sorting can be classified in to two categories:


1. Internal sorting
2. External sorting
2.7.1.1 INTERNAL SORTING:
 Sorting takes place in the internal memory that is main memory of a computer.
 Sorting methods applied to small collection of data.
 The entire data is stores in main memory.
Examples for internal sorting:
 Selection Sort
 Bubble Sort
 Insertion Sort
 Quick Sort
 Shell Sort
 Radix Sort
 Merge Sort

2.7.1.2. EXTERNAL SORTING:


 External sorting method is applied only when the number of data elements to be sorted is too large.
44
 External sorting is required when the data being sorted do not fit into the main memory of a computer.
 If the data is resides in external memory and is brought into main memory in blocks for sorting and then
result is returned back to the external memory

Example for external sorting:

 Merge sort.

Simple sorting program to sort an array of elements:


#include<stdio.h>
#include<conio.h>
void main()
{
int a[50], n, i, j, temp;
clrscr();
printf("Enter the size of an array");
scanf("%d", &n);
printf("Enter the array elements");
for (i = 0; i < n; i++)
scanf("%d", &a[i]);
for (i = 0 ; i < n; i++)
{
for (j = i+1;j<n;j++)
{
if (a[i] > a[j])
{
temp= a[i];
a[i]=a[j];
a[j] = temp;
}
}
}
printf("Array after Sorted in ascending order:\n");
for ( i = 0 ; i < n ; i++ )
printf("%d\n", a[i]);
printf("Array after Sorted in descending order:\n");
for(i=n-1;i>=0;i--)
printf("%d\n", a[i]);
45
getch();
}
OUTPUT:
Enter the size of an array:
5
Enter the array elements:
62079
Array after Sorted in ascending order:
02679
Array after Sorted in descending order:
97620

2.7.2 BUBBLE SORT


Bubble sort is the one of the easiest sorting method. In this each data item is compared with its neighbor
and if it is a descend sorting, the bigger number is moved to the top of all elements, the smaller numbers are
slowly moved to the bottom position.
Program
#include <stdio.h>
#include<conio.h>
void main()
{
int data[100],i,n,step,temp;
clrscr();
printf("Enter the number of elements to be sorted: ");
scanf("%d",&n);
printf("enter the elements");
for(i=0;i<n;++i)
{
scanf("%d",&data[i]);
}

for(step=0;step<n-1;step++)
for(i=0;i<n-step-1;i++)
{
if(data[i]>data[i+1]) /* To sort in descending order, change > to < in this line. */
{
temp=data[i];
data[i]=data[i+1];
46
data[i+1]=temp;
} }
printf("In ascending order: ");
for(i=0;i<n;i++)
printf("%d ",data[i]);
getch(); }
OUTPUT:
Enter the number of elements to be sorted:
6
enter the elements
3
4
2
1
9
7
In ascending order: 1 2 3 4 7 9

2.7.3 SELECTION SORT


 Selection sort determines the minimum or maximum of the list and swaps it with the element at the
index where it supposed to be.
 If the array contains ‘n’ elements to be sorted in their correct sequence, the first element is compared
with the remaining (n-1) elements and which is the lower element, place that element in first position.
Then the second element from the array is taken and compared with the remaining (n-2) elements.
 If an element with the value less than that of the second element of the array and so on. Continue the
process until all the elements in an array are sorted.
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,temp,n,min,a[100];
clrscr();
printf("enter the number of elements in an array");
scanf("%d",&n);
printf("enter the elements");
for(i=0;i<n;i++)
{
47
scanf("%d",&a[i]);
}
for(i=0;i<n-1;i++)
{
min=i;
for(j=i+1;j<n;j++)
{
if(a[min]>a[j])
min=j;
}
if(i!=min)
{
temp=a[i];
a[i]=a[min];
a[min]=temp;
}
}
printf("\n sorted array is...\n");
for(i=0;i<n;i++)
{
printf("\n%d",a[i]);
}
getch();
}
OUTPUT:
enter the number of elements in an array
5
enter the elements
9
4
6
3
2

sorted array is...

2
3
48
4
6
9

2.8 SEARCHING:
The process of looking up a particular element in an array is known as searching.

2.8.1 LINEAR SEARCH:


This C Program implements linear search. Linear search is also called as sequential search. Linear search is
a method for finding a particular value in a list that consists of checking every one of its elements, one at a time
and in sequence, until the desired one is found.

Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int a[100],key,i,n;
clrscr();
printf("enter the number of elements in array:\n");
scanf("%d",&n);
printf("enter elements:");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("enter the number to search:\n");
scanf("%d",&key);
for(i=0;i<n;i++)
{

49
if(a[i]==key) /*if required element found*/
{
printf("%d is present at location %d\n",key,i+1);
break;
}
}
if(i==n)
printf("%d is not present in arry\n",key);
getch();
}
Output
enter the number of elements in array:
5
enter elements:3
4
62
44
22
enter the number to search:
4
4 is present at location 2
2.8.2 BINARY SEARCH:

 Binary search is simpler and faster than the linear search. Binary search is called so because on
each search the array to be searched is divided into two parts, one of which is ignored as it will
not contain the required element. One essential condition for the binary search is that the array
which is to be searched should be arranged in order.

50
 Binary search is an algorithm for locating the position of an item in a sorted array. A search of
sorted data, in which the middle position is examined first. Search continues with either the left
or the right portion of the array, thus eliminating half of the remaining search array.

 In binary search we start by taking a look at the approximate middle element. Then, we compare
the middle element with the one we want to search in an array. If the value of middle element is
greater than the element to be searched then we discard the first half of the array and start all
over again by taking the second half of the array. If the middle element is smaller than the
element to be searched, then we discard the second half of the array.

 We keep on looking for the middle element of the array and keep on discarding the first half or
second half of the array depending on the result of the comparison of the middle elment when
they cannot be further divided.

Program:

#include<stdio.h>
#include<conio.h>
void main()
{
int i, first, last, middle, n, x, a[50];
clrscr();
printf("Enter the size of an array \n");
scanf("%d",&n);
printf("Enter the elements of an array");
for (i = 0; i < n; i++)
scanf("%d",&a[i]);
printf("Enter the number to searched\n");
scanf("%d", &x);
first=0;
last=n-1;
middle = (first+last)/2;
while (first <= last)
{
if (a[middle] < x)
first = middle + 1;
else if (a[middle] == x)
{
printf("%d found at location %d.\n", x, middle+1);
51
break;
}
else
last = middle - 1;
middle = (first + last)/2;
}
if (first > last)
printf("Not found! %d is not present in the list.\n", x);
getch();
}
Output:
Enter the size of an array
5
Enter the elements of an array
15287
Enter the number to search
7
7 found at location 4

SAMPLE PROGRAMS:

Programs on one dimensional array:


1. Program to get and print an array.
2. Program to print an array in a reverse order.
3. Sum of array elements.
4. Program to find max, min, second largest, second smallest, middle element of an array.
Programs on strings:
1. Count no of occurrences of a particular character in a string
2. Count blank spaces in a paragraph

1. Program to get and print an array


#include<stdio.h>
#include<conio.h>
void main()
{
int i, a[50], n;
clrscr();
printf("Enter no of elements :");
52
scanf("%d", &n);
printf("Enter the values :");
for (i = 0; i < n; i++)
{
scanf("\n%d", &a[i]);
}
printf("The values that you entered are");
for (i = 0; i < n; i++)
{
printf("\n%d", a[i]);
}
getch();
}
Output:
Enter no of elements
4
Enter the values
80
60
50
70
The values that you entered are
80
60
50
70

2. Program to print an array in a reverse order


#include<stdio.h>
#include<conio.h>
void main()
{
int i, a[50], n;
clrscr();
printf("Enter no of elements :");
scanf("%d", &n);
printf("Enter the values :");
53
for (i = 0; i < n; i++)
{
scanf("\n%d", &a[i]);
}
printf("The array in reversed order is\n");
for (i = n-1; i>=0; i--)
{
printf("%d\n", a[i]);
}
getch();
}
Output:
Enter no of elements
4
Enter the values
80
60
50
70
The values that you entered are
70
50
60
80
3. Sum of array elements
#include<stdio.h>
#include<conio.h>
void main()
{
int i, a[50], n, sum=0;
clrscr();
printf("Enter no of elements :");
scanf("%d", &n);
printf("Enter the values :");
for (i = 0; i < n; i++)
{
scanf("\n%d", &a[i]);
}
54
for (i = 0; i < n; i++)
{
sum=sum+a[i];
}
printf("the sum of the array is %d",sum);
getch();
}
Output:
Enter no of elements
3
Enter the values
2
3
1
the sum of the array is 6

4. Program to find max, min, second largest , second smallest, middle element of an array
#include<stdio.h>
#include<conio.h>
void main()
{
int a[50], n, i, j, temp,m;
clrscr();
printf("Enter the size of an array");
scanf("%d", &n);
printf("Enter the array elements");
for (i = 0; i < n; i++)
scanf("%d", &a[i]);
for (i = 0 ; i < n; i++)
{
for (j = i+1;j<n;j++)
{
if (a[i] > a[j])
{
temp= a[i];
a[i]=a[j];
a[j] = temp;
}
55
}
}
printf("the sorted array");
for(i=0;i<n;i++)
printf("%d\n",a[i]);
printf("The greatest element is %d\n", a[n-1]);
printf("The smallest element is %d\n", a[0]);
printf("The second largest element is %d\n", a[n-2]);
printf("The second smallest element is %d\n", a[1]);
m=(0+(n-1)/2);
printf("The middle element is %d\n", a[m]);
getch();
}
Output:
Enter the size of an array:
5
Enter the array elements:
62079
The greatest element is 9
The smallest element is 0
The second largest element is 7
The second smallest element is 2
The middle element is 0

Programs on strings:
Sorting of names
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,n;
char a[20][20],temp[20];
clrscr();
printf("Enter the no. of string to be sorted");
scanf("%d",&n);
printf("Enter the strings:");
56
for(i=0;i<n;i++)
{
scanf("%s",a[i]);
}
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(strcmp(a[i],a[j])>0)
{
strcpy(temp,a[i]);
strcpy(a[i],a[j]);
strcpy(a[j],temp);
} } }
printf("The sorted string\n");
for(i=0;i<n;i++)
{
printf("%s\n",a[i]);
}
getch();
}
OUTPUT:

Enter the no. of string to be sorted:


3
Enter the strings:
vino
aarthi
panimalar
The sorted string:
Aarthi
Panimalar
Vino

Count blank spaces in a paragraph


#include<stdio.h>
#include<conio.h>
void main()
57
{
char ch[10];
int i,count=0;
clrscr();
printf("Enter the string\n");
gets(ch);
for(i=0;ch[i]!='\0';i++)
{
if(ch[i]==' ')
count++;
}
printf("Total no of Spaces : %d",count);
getch();
}

OUTPUT:
Enter the string
God is love
Total no of Spaces: 2
Count number of vowels consonants and digits in a paragraph
#include<stdio.h>
#include<conio.h>
void main()
{
char line[150];
int i,v,c,ch,d,s,o=0;
printf("Enter a line of string:\n");
gets(line);
for(i=0;line[i]!='\0';++i)
{
if(line[i]=='a' || line[i]=='e' || line[i]=='i' || line[i]=='o' || line[i]=='u' || line[i]=='A' || line[i]=='E' || line[i]=='I' ||
line[i]=='O' || line[i]=='U')
++v;
else if((line[i]>='a'&& line[i]<='z') || (line[i]>='A'&& line[i]<='Z'))
++c;
else if(line[i]>='0'&&c<='9')
++d;
else if (line[i]==' ')
58
++s;
}
printf("Vowels: %d",v);
printf("\nConsonants: %d",c);
printf("\nDigits: %d",d);
printf("\nWhite spaces: %d",s);
getch();
}

OUTPUT:
Enter the string
God is love
Vowels:
Consonants:
Digits:
White spaces:

Count no of occurrences of a particular character in a string


#include <stdio.h>
#include<conio.h>
void main()
{
char a[100], ch;
int count=0, i;
clrscr();
printf("Enter a string");
scanf(“%s”,a);
printf("Enter the character to be searched");
scanf(“%c”, &ch);
for(i = 0; a[i]!=’\0’; i++)
{
if (str [i] == ch)
count++;
}
if(count==0)
printf(“Character is not present”);
else
printf(“Occurrences of a character is %d “,count);
59
getch();
}
OUTPUT
Enter a string
Hello
Enter the character to be searched
l
Occurrences of a character is 2

PART – A

1. List out the features of Arrays.

2. Define a float array of size 5 and assign 5 values to it.

3. Identify the main elements of an array declaration.

4. What are the drawbacks of Initialization of arrays in C?

5. What will happen when you access the array more than its dimension?

6. Point out an example code to express two dimensional array.

7. How to create a two dimensional array?

8. What is the starting index of an array?

9. Distinguish between one dimensional and two dimensional arrays.

10. What are the different ways of initializing array?

11. What is the use of ‘\0’ and ‘%s’?

12. Is address operator used in scanf() statement to read an array? Why?

13. What is the role of strrev()?

14. Discover the meaning of a String.

60
15. How to initialize a string? Give an example.

16. Differentiate between Linear search and Binary search.


17. Write the output of the following
Code: main()
{
char x; x = ‘a’;
printf(“%d \n”,x);
}
18. Specify any two methods of sorting.

19. List out the any four functions that are performed on character strings.
20. Write the output of the following

Code: main()
{
static char name[]=”KagzWrxAd” int i=0; while(name[i]!=’\0’)
{
printf(“%c”,name[i]); i++;
}}

PART –B

1. Explain the need for array variables. Describe the following with respect to arrays:- Declaration of array
and accessing an array element. (8)
2. Write a C program to re-order a one-dimensional array of numbers in descending order. (8)
3. Write a C program to perform the following matrix operations:
(i) Addition (5)

(ii) Subtraction (5)


(iii) Scaling (6)
4. Write a C program to calculate mean and median for an array of elements.(8+8)
5. Write a C program for Determinant and transpose of a matrix.(8+8)
6. Describe the following with suitable examples. (8+8)
(i) Initializing a 2 Dimensional Array
(ii) Memory Map of a Dimensional Array.
7. Explain about the String Arrays and its manipulation in detail (16)
7.(i). Write a C program to find average marks obtained by a of 30 students in a test.(10)
(ii).Write short notes on Reading and Writing string. (6)
8.Write a C program to sort the n numbers using selection sort (16)

61
9.Develop a C program to search an element from the array. (16

10.Describe the following functions with examples. (4+4+4+4)

(i) strlen() (ii) strcpy() (iii)strcat() (iv)strcmp()


11.Write a C program to find whether the given string is palindrome or not without using string functions. (16)
12.Write a C program to count the number of characters, spaces, vowels, constants and others using string
functions. (16)

13. Discuss about the following :-


(i).Advantages and disadvantages of linear and binary search.(8)
(ii).Discuss briefly runtime initialization of a two dimensional array.(8)

14. Explain about the following : (i).String and character array.(6)


(ii).Initialising a string variables.(4) (iii).String input and output (6)

62

You might also like