Unit II Arrays and Strings-book
Unit II Arrays and Strings-book
INTRODUCTION TO ARRAYS:
A single variable cannot store multiple values . But an array can store multiple values of
same data type in one single name.
Array can store integer, float and double values which is said to be integer array.
Features of array:
Array might be belonging to any of the data types
Array size must be a constant value.
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:
int roll_num[100];
char name[50];
double balance[10];
Initialization of an Array:
Syntax:
data type array_name[size] = { list of values };
Example:
int marks[4]={ 67, 87, 56, 77 }; //integer array initialization
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]); }
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);
}
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:
}
}
if (found==1)
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:
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.
Example:
int arr[2][2];
- this array can hold 2*2=4 elements totally.
Array Initialization:
Example:
int arr[2][2] = {1,2, 3, 4};
arr [0] [0] = 1;
arr [1][0] = 3;
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.
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];
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();
}
Example:
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.
Example:
char edu[ ]={‘C’,’O’,’L’,’L’,’E’,’G’,’E’,‘\0’};
char name[10]="india"; //valid character array initialization
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.
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);
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
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:
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()
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:
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();
}
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”
};
#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
OUTPUT:
enter the string1
hello
enter the string2
hai
the concatenated string is hellohai:
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:
#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.
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.
Merge sort.
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
3
48
4
6
9
2.8 SEARCHING:
The process of looking up a particular element in an array is known as searching.
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:
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:
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:
PART – A
5. What will happen when you access the array more than its dimension?
60
15. How to initialize a string? Give an example.
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)
61
9.Develop a C program to search an element from the array. (16
62