Arrays and Strings

Download as pdf or txt
Download as pdf or txt
You are on page 1of 25

ARRAYS & STRINGS

BASIC CONCEPT OF ARRAYS: Consider a program to find average temperature in a week. Here
we need to store 7 floating point numbers. If we use simple variable and data type concepts, then we
need 7 variables of float data type and program will be something as follows:

#include <stdio.h>
int main ()
{
float temp1,temp2,temp3,temp4,temp5,temp6,temp7;
float avg;
printf("Enter Day-1 Temperature: "); scanf(“%f”,&temp1);
printf("Enter Day-2 Temperature: "); scanf(“%f”,&temp2);
printf("Enter Day-3 Temperature: "); scanf(“%f”,&temp3);
printf("Enter Day-4 Temperature: "); scanf(“%f”,&temp4);
printf("Enter Day-5 Temperature: "); scanf(“%f”,&temp5);
printf("Enter Day-6 Temperature: "); scanf(“%f”,&temp6);
printf("Enter Day-7 Temperature: "); scanf(“%f”,&temp7);
avg = (temp1 + temp2 + temp3 + temp4 + temp5 + temp6 + temp7) / 7;
printf(“Average Temperature of a Week = %f ", avg);
return 0;
}
It was simple, because we had to store just 7 floating point numbers. Now let's assume we have to
compute average temperature of an year , so what is next? Are we going to use 365 variables?
Thus we can conclude here that:

 It's difficult to program with too many declarations.


 It's not recommended way of programming.
 It's not the right way of programming.

To handle such situation, C language provides a concept called the arrays. These are the situations,
where we need to have logical collection of values of same type in Programming. Few more examples
are:
 List of Marks of a Student
 List of Employees of an Organization
 List of Daily Temperature in an year
 List of temperatures recorded every hour in a day, or a month, or a year
 List of products and their cost sold by a store
 Matrices and so on…
Having these collections of data we need to perform various operations on these values such as:

  Searching for a particular element.


 Ordering of the elements
 Finding Maximum, Minimum, Average, Mean and so on…
ARRAY

Array is a collection of homogeneous elements (elements of same data type), stored


sequentially one after the other in memory. An element of an array can be accessed by using: name of
the array and position of element in the array.
Arrays are of 2 types:
1) Single dimensional array
2) Multi dimensional array

SINGLE DIMENSIONAL ARRAY

A single dimensional array is a linear list consisting of related elements of same type. In
memory, all the elements are stored in continuous memory-location one after the other.

The Syntax of declaration of Single Dimensional Arrays is as shown below:

data_type array_name[array_size];

where
data_type can be int, float, char or any valid built-in or user defined data type
array_name is any valid identifier i.e name of the array
array_size indicates number of elements in the array, it can be any valid integer expression.

For example:
int marks[100];
float temperature[365];
char name[60]
Here:
marks is an array of 100 integer elements stored in a contiguous memory location.
temperature is an array of 365 floating point elements stored in a contiguous memory area.
name is an array of 60 character elements stored in a contiguous memory location.
The declaration int a[5]; can be pictorially represented as shown below:
a[0] a[1] a[2] a[3] a[4]

Note that, the first element is indexed at position 0, second element at position 1 and so on
upto n-1 where n is size of an array. And the size of array is 5 times the size of int because there are
5 integer elements.
Storing Values in Arrays
The values can be stored in an array using following three methods:

1) Initialization
2) Assigning values
3) Input values from keyboard
1. Initialization of One-Dimensional Array
The syntax is as shown below:
data_type array_name[array_size] = {v1, v2, v3,..., vN};
where v1, v2, v3, ..., vN are values
Ex: int a[5] = { 21, 45, 34, 56, 67 };
The above code can be pictorially represented as shown below:
a[0] a[1] a[2] a[3] a[4]
21 45 34 56 67
Note: Here even the declaration int a[ ] = { 21, 45, 34, 56, 67 }; is correct because based on
number of elements specified the size will be computed automatically.
Example: The following program illustrate the initialization of one-dimensional
array. #include<stdio.h>
void main()
{ int age[5] = {21, 45, 34, 37, 94};
printf("Value in array age[0] : %d \n", age[0]);
printf("Value in array age[1] : %d \n", age[1]);
printf("Value in array age[2] : %d \n", age[2]);
printf("Value in array age[3] : %d \n", age[3]);
printf("Value in array age[4] : %d ",age[4]);
}
Output: Value in array age[0] :21
Value in array age[1] :45
Value in array age[2] :34
Value in array age[3] :37
Value in array age[4] :94
2. Assigning values to One-Dimensional Array
Example: int age[5];
age[0] = 22; //value 2 stored in array „age? at position 0
age[1] = 44; //value 4 stored in array „age? at position 1
age[2] = 34; //value 34 stored in array „age? at position 2
age[3] = 35; //value 3 stored in array „age? at position 3
age[4] = 47; //value 4 stored in array „age? at position 4
Example: Program to illustrate assigning values to one-dimensional array.
#include<stdio.h>
void main()
{ int age[5];
age[0] = 22; age[1] = 44; age[2] = 34; age[3] = 35; age[4] = 47;
printf("Value in array age[0] : %d \n", age[0]); printf("Value in array
age[1] : %d \n", age[1]);
printf("Value in array age[2] : %d \n", age[2]);
printf("Value in array age[3] : %d \n", age[3]);
printf("Value in array age[4] : %d ",age[4]);
}
Output: Value in array age[0] :22
Value in array age[1] :44
Value in array age[2] :34
Value in array age[3] :35
Value in array age[4] :47
3. Reading/Writing to One-Dimensional Array
Example: int age[5]
scanf("%d", &age[0]); //read data from keyboard into array age at position 0.
scanf("%d", &age[1]); //read data from keyboard into array age at position 1.
scanf("%d", &age[2]); //read data from keyboard into array age at position 2.
scanf("%d", &age[3]); //read data from keyboard into array age at position 3.
scanf("%d", &age[4]); //read data from keyboard into array age at position 4.
In general, to read 5 values, we can write as:
for(i = 0; i < 5; i++)
{
scanf("%d", &age[i]);
}
Similarly, to display 5 elements stored in the array, we can write:
for(i = 0; i < 5; i++)
{
printf("%d", age[i]);
}
Example: Program to illustrate reading/writing to one-dimensional array.
#include<stdio.h>
void main()
{
int age[5], i;
printf("enter 5 numbers:\n”);
for(i=0;i<5;i++)
{
scanf("%d", &age[i]);
}
for(i=0;i<5;i++)
{
printf("Value in array age[%d] : %d \n ", i, age[i]);
}
}
Output: enter 5 numbers: 2 4 34 3 4
Value in array age[0] :2
Value in array age[1] :4
Value in array age[2] :34
Value in array age[3] :3
Value in array age[4] :4
Thus Array constructs can be used in a simple and easier way using looping constructs.
NOTE: While Using Arrays, we must keep in mind the following points:
 Array index starts at 0 NOT 1
  Array SIZE cannot be ZERO
 C does NOT check array bounds whether index points to an element within the array OR
outside the array boundary. So we must never access array elements outside the boundary
 and the result of accessing an array outside its boundary may result :
 Corrupting of data
 Segmentation fault
 Exposing system to a security hole!
Example: Program to find maximum element in an array of n integer elements
#include<stdio.h>
int main ()
{
int a[50],n,max, i;
printf(“\n\tEnter the number of elements: “);
scanf(“%d”,&n);
printf(“\n\tEnter %d Elements of array: “, n);
for ( i = 0; i < n; i++ )
scanf(“%d”,&a[i]);
max = a[0];
for (i = 1; i < n; i++ )
{ if(a[i] > max)
max = a[i];
}
printf(“ Maximum Element of an array =%d ", max );
return 0;
}
Example: Program to find minimum element in an array of n integer elements
#include<stdio.h>
int main ()
{ int a[50], n, min, i;
printf(“\n\tEnter the number of elements: “);
scanf(“%d”, &n); /* 0 ≤ n ≤ 49 */
printf(“\n\tEnter %d Elements of array: “, n);
for ( i = 0; i < n; i++ )
scanf(“%d”, &a[i]);
min = a[0];
for (i = 1; i < n; i++ )
{ if(a[i] < min)
min = a[i];
}
printf(“ Minimum Element of an array = %d ", min);
return 0;
}
Example: Program to find minimum and maximum element in an array of n integer elements
#include<stdio.h>
int main ()
{ int a[50], n, min, max, i;
printf(“\n\tEnter the number of elements: “);
scanf(“%d”, &n); /* 0 ≤ n ≤ 49 */
printf(“\n\tEnter %d Elements of array: “, n);
for ( i = 0; i < n; i++ )
scanf(“%d”, &a[i]);
min = max = a[0];
for (i = 1; i < n; i++ )
{ if(a[i] < min)
min = a[i];
if(a[i] > max)
max = a[i];
}
printf(“ Min Element = %d And Max Element = %d” , min, max);
return 0;
}
Searching Problem
This is the problem of finding the given key element in a list of elements. When the key element
is found in the list we call Search as Successful Search otherwise Unsuccessful Search. Two simple
Searching Methods which are commonly used are:
• Linear / Sequential Search
• Binary Search
Linear / Sequential Search
It compares each elements of the array with key element Sequentially / Linearly(one element
at a time) and it STOPS when Key is Found and declare Successful Search, It also STOPS when Array
exhaust and declare Unsuccessful Search. The algorithm of Linear/Sequential Search is:
Algorithm : Linear_Search( )
Begin
read the number of elements n
read n elements of an array a
read the key element to be searched
flag = FALSE // Assume key is not found
for i = 0 to n-1 do //compare key with all the elements
if a[i] == key then
flag = TRUE break
end if
end for
if flag == TRUE then
print “Successful Search”
else
print “UnSuccessful Search”
end if
End
Example: Program to find given key element in an array of n integer elements using Linear
Search
int main ()
{ int a[50], n, min, i, flag = 0;
printf(“\n\tEnter the number of elements: “);
scanf(“%d”, &n); /* 1 ≤ n ≤ 50 */
printf(“\n\tEnter %d Elements of array: “, n);
for ( i = 0; i < n; i++ )
scanf(“%d”, &a[i]);
printf(“\n\tEnter the Key element to be Searched: “);
scanf(“%d”, &key);
for (i = 0; i < n; i++ )
{ if(a[i] == key)
{
flag = 1; break;
}
}
if( flag == 1)
printf(“Successful Search - Key found ”);
else
printf(“Unsuccessful Search - Key NOT found”);
return 0;
}

Binary Search

If we look at the questions viz. How do we search for a person’s telephone number? If we
know only the person’s name. and How difficult is this? Similarly How do we search for a person’s
name? If we know only the person’s telephone number. and Why is this more difficult? similarly How
do we search for a student blue book, when blue books are unsorted? AND when blue books are
sorted?
Here what we can notice is Searching will be easier if the list is sorted. The technique what we
use in searching of key element in sorted list is Binary Search. It works only on Sorted Elements.

How does it work?

It finds the middle element in the complete list of sorted elements then Compares the key
element with middle element and STOPS if middle element is KEY and declare Successful Search. If
KEY is less than middle element then it search in the lower half of the sorted list in the same way and
If KEY is greater than middle element it search in the higher half of the sorted list in the same way
and finally If Array exhaust it STOPS and declare Unsuccessful search.
The algorithm of Binary Search can be given as:
Algorithm : Binary_Search( )
Begin
read the number of elements n
read n elements of an array a
read the key element to be searched
low = 0 high = n-1 flag = FALSE
do
mid = (low + high) / 2
if a[mid] == key then
flag = TRUE break
else if a[mid] > key then
low = mid + 1
else
high = mid – 1
end if
until low <= high
if flag == TRUE then
print “Successful Search”
else
print “UnSuccessful Search”
end if
End
Example: Program to find given key element in an array of n integer elements using Binary
Search
int main ()
{ int a[50], n, key, low, high, mid, i, flag = 0;
printf(“\n\tEnter the number of elements: “);
scanf(“%d”, &n); /* 1 ≤ n ≤ 50*/
printf(“\n\tEnter %d Elements of an array in Sorted Order: “, n);
for ( i = 0; i < n; i++ )
scanf(“%d”, &a[i]);
printf(“\n\tEnter the Key element to be Searched: “);
scanf(“%d”, &key);
low = 0; high = n – 1;
while(low <= high)
{
mid = (low + high) / 2;
if(key == a[mid]) flag = 1;
else if(key > a[mid]) low = mid + 1;
else high = mid – 1;
}
if( flag == 1) printf(“Successful Search - Key found ”);
else printf(“Unsuccessful Search - Key NOT found”);
return 0;
}
MULTI DIMENSIONAL ARRAYS

Arrays with two or more subscipts(dimensions/indices) are called multi dimensional arrays.
It is widely used in matrix operations. Its syntax is:

Data_Type Array_Name[Row_Size][Col_Size];

Here we can note that Two Dimensional Arrays are "an array of One-Dimensional arrays
of elements of same type". These are also called "Double Subscripted". Here a[ i ][ j ] refers to i-th
Row and j-th Column element of 2D Array

Example:
int a[3][4];

Here a is an array of 3 arrays of 4 integer elements. The above code can be pictorially represented
as shown below:

a[0][0] a[0][1] a[0][2] a[0][3]


a[1][0] a[1][1] a[1][2] a[1][3]
a[2][0] a[2][1] a[2][2] a[2][3]

A two dimensional array is used when elements are arranged in a tabular fashion. Here,
to identify a particular element, we have to specify 2 indices:
  
First index identifies the row number of the element and
 
Second index identifies the column number of the element

Thus 2D Arrays Simulate Matrices of Order mXn

Initialization of Two Dimensional Arrays


Example-1:
int a[2][3] = { { 1, 2, 3 }, { 4, 5, 6 } };

The above code can be pictorially represented as shown below

a[0][0] = 1 a[0][1] = 2 a[0][2] = 3


a[1][0] = 4 a[1][1] = 5 a[1][2] = 6
Example-2:
int a[2][3] = { 1, 2, 3, 4, 5 };

a[0][0] = 1 a[0][1] = 2 a[0][2] = 3


a[1][0] = 4 a[1][1] = 5 a[1][2] = 0
Example-3:
int a[2][3] = { { 1, 2}, { 4 } };

a[0][0] = 1 a[0][1] = 2 a[0][2] = 0


a[1][0] = 4 a[1][1] = 0 a[1][2] = 0

Here we can note that example 2 and 3 are partially initialized, so the uninitialized
elements get ZERO by default.

Example-4:
int a[ ][2] = { 11, 2, 3, 4, 5 }; /*Row size = 3 */
int a[ ][4] = { 11, 2, 3, 4, 5 }; /*Row size = 2 */
int a[ ][5] = { 11, 2, 3, 4, 5 }; /*Row size = 1 */
int a[ ][8] = { 11, 2, 3, 4, 5 }; /*Row size = 1 */

In 2D’ Arrays Row size is optional but COLUMN size Compulsory during initializing 2D’ Arrays
at the time of their declaration

Reading and Writing Two Dimensional Arrays


Example:
int matrix[2][3];
scanf("%d", &matrix[0][0]); //read data from keyboard into matrix at row=0 col=0.
scanf("%d", &matrix[0][1]); //read data from keyboard into matrix at row=0 col=1.
scanf("%d", &matrix[0][2]); //read data from keyboard into matrix at row=0 col=2.
scanf("%d", &matrix[1][0]); //read data from keyboard into matrix at row=1 col=0.
scanf("%d", &matrix[1][1]); //read data from keyboard into matrix at row=1 col=1.
scanf("%d", &matrix[1][2]); //read data from keyboard into matrix at row=1 col=2.

This way of reading / printing a 2D’ array is not easy and not recommended

In general, to read 6 values, we can write:


for(i=0;i<2;i++) /* specify i-th Row */
{
for(j=0;j<3;j++) /* specify j-th Column */
{
scanf("%d", &matrix[i][j]);
}
}
Similarly to display 6 elements stored in the matrix, we can write:
for(i=0;i<2;i++) /* specify i-th Row */
{
for(j=0;j<3;j++) /* specify j-th Column */
{
printf("%d ", matrix[i][j]);
}
}
Example: Program to illustrate reading/writing to two-dimensional array.
#include<stdio.h>
void main()
{
int matrix[2][3], i, j;
printf("enter elements of 2*3 matrix: \n”);
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
{
scanf("%d", &matrix[i][j]);
}
}
printf("elements of the matrix are: \n”);
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
{
printf("%d \t", matrix[i][j]);
}
printf(“\n”);
}
}
Output:
enter elements of 2*3 matrix:
1 23 11
44 5 6
elements of the matrix are:
1 23 11
44 5 6
Example: Program to read and print mXn
Matrix #include<stdio.h>
void main ()
{
int a[10][10], i, j, m, n;
printf(“\n\tEnter the Order of Matrix : “);
scanf(“%d %d”,&m,&n); /* m is ROW & n is COLUMN */
printf(“\n\tEnter %d Elements of Matrix : “, m * n);
for(i = 0; i < m; i++) /* specify i-th Row */
for(j = 0; j < n; j++) /* specify j-th Column */
scanf(“%d”,&a[ i ][ j ]);
printf(“\n\tThe %d Elements of Matrix are: “, m * n );
for(i = 0; i < m; i++) /* specify i-th Row */
for(j = 0; j < n; j++) /* specify j-th Column */
printf(“%d”,a[ i ][ j ]);
} /* closing of main */
Output:
Enter the Order of Matrix : 2 3
Enter 6 Elements of Matrix: 22 7 4 84 5 13
The 6 Elements of Matrix are: 22 7 4 84 5 13

We must display the matrices as matrices only. The following code display matrix in the matrix
form i.e row wise one after the other.

Example: Program to read and print mXn


Matrix #include<stdio.h>
void main ()
{
int a[10][10], i, j, m, n;
printf(“\n\tEnter the Order of Matrix : “);
scanf(“%d %d”,&m,&n); /* m is ROW & n is COLUMN */
printf(“\n\tEnter %d Elements of Matrix : “, m * n);
for(i = 0; i < m; i++) /* specify i-th Row */
for(j = 0; j < n; j++) /* specify j-th Column */
scanf(“%d”,&a[ i ][ j ]);
printf(“\n\tThe %d Elements of Matrix are: “, m * n );
for(i = 0; i < m; i++) /* specify i-th Row */
{
printf("\n\t");
for(j = 0; j < n; j++) /* specify j-th Column */
printf(“%d”,a[ i ][ j ]);
}
} /* closing of main */
STRINGS
String is an Array of Characters terminated by a NULL character '/0'.
Example:
char a[10] = “Hello”;
The above string can be pictorially represented as shown below:
a[0] a[1] a[2] a[3] a[4] a[5] ….. a[9]

H e l l o ‘\0’ 0 0

STRING VARIABLE

There is no separate data type for handling strings in C. They are treated as just an arrays of
characters. So, a variable which is used to store an array of characters is called a string variable.

Declaration of String

Strings are declared in C in similar manner as arrays. Only difference is that, strings are of char type.

Example:
char s[5]; //string s can hold maximum of 5 characters including NULL character
The above code can be pictorially represented as shown below:
a[0] a[1] a[2] a[3] a[4]

Initialization of String

Example:
char s[4]={'V', 'T', 'U' };
The above code can be pictorially represented as shown below:
a[0] a[1] a[2] a[3]
V T U \0
we can also use
char s[10]="VTU";
Here 10 bytes of memory is allocated and only three characters are stored and remaining will be
initialized to zero.
a[0] a[1] a[2] a[3] a[4] a[5] ….. a[9]
V T U \0 0 0 0 0
Example: Program to illustrate the initialization of string.
#include<stdio.h>
void main()
{
char s[4]={'V','T','U'}; //or char s[4]="VTU";
printf("Value in array s[0] : %c \n", s[0]);
printf("Value in array s[1] : %c \n", s[1]);
printf("Value in array s[2] : %c \n", s[2]);
}
Output:
Value in array s[0] : V
Value in array s[1] : T
Value in array s[2] : U
Reading & Printing Strings
The strings can be read from the keyboard and can be displayed onto the monitor using
following formatted functions:
  
Formatted input function: scanf()
 
Formatted output function: printf()
Example: Program to illustrate the use of scanf() and printf().
#include <stdio.h>
int main()
{
char str[50];
int i, n; clrscr();
printf(“\n\tEnter a string(gets):“);
gets(str);
printf(“\n\t String Entered is(gets) : %s“, str);
printf(“\n\tEnter number of character in the
string:“); scanf(“%d”, &n);
printf(“\n\tEnter %d characters of string one by one :”);
for( i = 0; i < n ; i++ )
scanf(“%c”, &str[ i ] );
str[ i ] = ‘\0’ ;
printf(“\n\t String Entered is: %s“, str);
printf(“\n\tEnter a string(scanf): “); scanf(“%s”, str);
printf(“\n\t String Entered is(scanf) : %s“, str);
getchar(); return 0;
}
Example: Program to illustrate the use of scanf() and printf().
#include<stdio.h>
void main()
{ char name[10];
printf(“enter your name: \n”); scanf(“%s”, name);
printf(“welcome: ”); printf(“%s”, name);
}
STRING INPUT/OUTPUT FUNCTIONS: gets, puts
The strings can be read from the keyboard and can be displayed onto the monitor
using following unformatted functions:
  
Unformatted input function: gets()
 
Unformatted output function: puts()
Example: Program to illustrate the use of gets() and puts().
#include<stdio.h>
void main()
{
char name[10];
printf(“enter your name: \n”);
gets(name); //same as scanf(“%s”, name);
printf(“welcome: ”);
puts(name); //same as printf(“%s”, name);
}
Output: enter your name:
rama
welcome: rama
Example: Program to count the number of characters in a string. – String
Lenth #include <stdio.h>
int main()
{
char str[100]; int i, length;
printf(“\n\tEnter a String to Compute its Length: ");
scanf(“%s", str);
for(i = 0; str[ i ] != ‘\0’; i++)
; /* NULL Statement * /
length = i;
printf(“\n\n\t The Length of String: %s is %d”, str, length);
return 0;
}
Example: Program to Print String in Reverse
#include <stdio.h>
int main()
{
char str[100]; int i, length;
printf(“\n\tEnter a String a Reverse: ");
scanf(“%s", str);
for(i = 0; str[ i ] != ‘\0’; i++) ; /* NULL Statement * /
length = i;
printf(“\n\n\t The Reverse of a String - %s - is : ” , str);
for( i = length – 1; i >= 0; i--)
printf(“%c”, str[ i ]);
return 0;
}
In order to Compare Two Strings, we have to compare each character of String one by one
and needs to return
  
a negetive value if S1 < S2,
  
if S1 == S2
 
a posetive value if S1 > S2

Example: Program to Compare Two String


#include <stdio.h>
int main()
{
char str1[100], str2[100]; int i, flag;
printf(“\n\tEnter a String-1: ");
scanf(“%s", str1);
printf(“\n\tEnter a String-2: ");
scanf(“%s", str2); i = 0 ;
while ( (str1 [ i ] == str2 [ i ]) && (str1 [ i ] != ‘\0’) )
i++;
flag = str1 [ i ] - str2 [ i ] ;

if(flag == 0)
printf(“\n\n\t The Strings are equal” );
else if (flag > 0)
printf(“\n\n\t The String1 is higher than String2” );
else
printf(“\n\n\t The String1 is lower than String2” );
return 0;
}

CHARACTER HANDLING LIBRARY FUNCTIONS

Character handling Functions Includes functions to perform useful tests and manipulations
on character data. Each function receives a character (an int) or EOF as an argument. These library
functions exists in the header <ctype.h>. Commonly used Character handling functions are:

 int isdigit( int )


 int isalpha( int )
 int isalnum( int )
 int islower( int )
 int isupper( int )
  int tolower( int )
 int toupper( int )
Example: Program to Convert lower case character to upper case and vice
versa. #include<ctype.h>
#include<stdio.h>
int main()
{
char ch; clrscr();
printf("Enter a Character : "); scanf("%c", &ch);
if(islower(ch))
ch = toupper(ch);
else
ch = tolower(ch);
printf("\n\tCharacter After Reversing case is : %c",
ch); getch(); return 0;
}

Example: Program to Check whether the character read is digit or an alphabet.


#include<ctype.h>
#include<stdio.h>
int main()
{
char ch; clrscr();
printf("Enter a Character: "); scanf("%c",&ch);
if(isdigit(ch))
printf("\n\tCharacter %c is a Digit", ch);
if(isalpha(ch))
printf("\n\tCharacter %c is a Alphabet", ch);
getch(); return 0;
}
Pointers and Strings
The arrays are implicitly treated as pointers. And the strings are array of characters
terminated by NULL character. Hence a pointer to char type can be used to read a string.
Example: Program to read a String using Pointer
#include<stdio.h>
#include<conio.h>
int main()
{int i; char *str1, str2[50], *ptr; clrscr();
printf("\n\tEnter a String-1: "); scanf("%s",
str1);
printf("\n\tEnter a String-2: ");
scanf("%s", &str2);
ptr = str1;
printf("\n\tThe String is : %s",ptr);
ptr = str2;
printf("\n\tThe String is : %s",ptr);
getch(); return 0;
}
To hold the list of names we can use Two dimensional array of characters. Consider the
below example.
char s[3][50] = { “EDUSAT”, “PROGRAM”, “BANGALORE” };
char *ptr;ptr = s;
The above declaration can be pictorially viewed as shown below:

Location Name s[0] s[1] s[2]


Content 1 2 3

Address 1400 1450 1500


Here
th
s[0] = Address of the 0 String
s[1] = Address of the 1st String
nd
s[2] = Address of the 2 String

Example: Program to Read a List of Names


#include<stdio.h>
int main()
{
int i , n; char names[10][50]; clrscr(); printf("\n\tEnter the
Number of Names: "); scanf("%d", &n); printf("\n\tEnter %d
Names", n); for(i = 0; i < n; i++)

{
printf("\n\tEnter Name-%d: ", i+1);
scanf("%s", names[i]);
}
printf("\n\tThe %d Names are: ", n);
for(i = 0; i < n; i++) printf("\n\t\t\t%s",names[i]);
getch();
return 0;
}
Example: Program to Read a sentence and print frequency of vowels and count of consonants.
#include <stdio.h>
#include<ctype.h>
#include<conio.h>
int main()
{
char str[100]; clrscr();
int i, na, ne, ni, no, nu, nvowel, ncons, x;
printf(“\n\tEnter a Sentence : ");
gets(str); /* scanf(“%s", str); */
na = ne = ni = no = nu = nvowel = ncons = x = 0;
for (i = 0 ; str [ i ] != ‘\0’; i++)
{if(!isalpha(str[ i ])) { x++; continue; }
switch(str [ i ])
{ case ‘A’ :
case ‘a’ : na++; break;
case ‘E’ :
case ‘e’ : ne++; break;
case ‘I’ :
case ‘i’ : ni++; break;
case ‘O’ :
case ‘o’ : no++; break;
case ‘U’ :
case ‘u’ : nu++; break;
}
}
nvowel = na + ne + ni + no + nu ;
ncons = i – nvowel - x;
printf(“\n\tNumber of a’s in the String is : %d “, na);
printf(“\n\tNumber of e’s in the String is : %d “, ne);
printf(“\n\tNumber of i’s in the String is : %d “, ni);
printf(“\n\tNumber of o’s in the String is : %d “, no);
printf(“\n\tNumber of u’s in the String is : %d “, nu);
printf(“\n\tNumber of Vowels in the String is : %d “, nvowel);
printf(“\n\tNumber of Consonants in the String is : %d “, ncons);
getch(); return 0;
}
Output: Enter a Sentence : Hai Students
Number of a’s in the String is : 1
Number of e’s in the String is : 1
Number of i’s in the String is : 1
Number of o’s in the String is : 0
Number of u’s in the String is : 1
Number of Vowels in the String is : 4
Number of Consonants in the String is : 7
STRING MANIPULATION FUNCTIONS FROM THE STANDARD LIBRARY
Strings are often needed to be manipulated by programmer according to the need of a problem.
All string manipulation can be done manually by the programmer but, this makes programming
complex and large. To solve this, the C supports a large number of string handling functions. There
are numerous functions available in <string.h> header file. It includes functions to perform useful tests
and manipulations on Strings. Each of these functions receives a pointer to character as an argument.
Commonly used String handling functions are:
 unsigned int strlen(const char *s);
 char * strcpy(char *dest, const char *src);
 char * strcat(char *dest, const char *src);
 char * strcmp(const char *dest, const char *src);
 char * strchr(const char *s, int c);
 char * strstr(const char *m_str, const char *s_str);
 char * strrev(char *str);
strlen()
This function calculates the length of string. It takes only one argument, i.e., string-name.
The syntax is : temp_variable = strlen(string_name);
Example: Program to illustrate the use of strlen().
#include<string.h>
#include<stdio.h>
void main()
{
char c[20]; int len;
printf("Enter string whose length is to be found:");
gets(c);
len=strlen(c);
printf("\n Length of the string %s is %d ",c, len);
}
Output: Enter string whose length is to be found: program
Length of the string program is 7
strcpy()
This function copies the content of one string to the content of another string. It takes
2 arguments. The syntax is : strcpy(destination,source);
where source and destination are both the name of the string.
Example: Program to illustrate the use of strcpy().
#include<string.h>
#include<stdio.h>
void main()
{char src[20],dest[20];
printf("Enter string: ");
gets(src);
strcpy(dest, src); //Content of string src is copied to string dest
printf("Copied string: "); puts(dest);
}
Output: Enter string: vtunotesbysri
Copied string: vtunotesbysri
Example: Program to demonstrate use of strcpy() and strcat() functions.
#include<stdio.h>
#include<string.h>
int main()
{
char dest[25], *str1 = "EDUSAT“, *str2 = "Program";
char *blank = " "; int len;
strcpy(dest, str1);
strcat(dest, blank);
strcat(dest, str2);
len = strlen(dest);
printf("\n\n\tThe Length of String\"%s\" is %d\n", dest, len);
return 0;
}
Output: The Length of String "EDUSAT Program" is 14

strcmp()
This function compares 2 string and returns value 0, if the 2 strings are equal. It takes 2
arguments, i.e., name of two string to compare. The syntax is shown below:
temp_varaible=strcmp(string1,string2);

Example: Program to illustrate the use of strcmp().


#include <string.h>
#include<stdio.h>
void main()
{
char str1[30],str2[30];
printf("Enter first string: ");
gets(str1);
printf("Enter second string: ");
gets(str2);
if(strcmp(str1,str2)==0)
printf("Both strings are equal");
else
printf("Strings are unequal");
}
Output:
Enter first string: rama
Enter second string: rama
Both strings are equal
Example: Develop, implement and execute a C Program to search a Name in a list of
names using Binary searching Technique.
#include<stdio.h>
#include<c onio.h>
#include<string.h>
int main()
{
int i, n, low, high, mid;
char names[10][50];
char str[50];
clrscr();
printf("\n\tEnter the Number of Names: ");
scanf("%d",&n);
printf("\n\tEnter %d Names", n);
for(i = 0; i < n; i++)
{
printf("\n\tEnter Name-%d: ", i +1 );
fflush(stdin);
gets(names[ i ]);
}
printf("\n\n\tEnter the Name to be Searched: ");
fflush(stdin);
gets(str);
low = 0; high = n-1;
while(low <= high)
{
mid = (low + high) / 2;
if(strcmp(str,names[mid]) == 0)
{
printf("\n\tName Found at Position: %d",
mid+1); getch(); exit(0);
}
else if(strcmp(str,names[mid]) > 0) low = mid + 1;
else high = mid - 1;
}
printf("\n\n\tName Does not Exist"); getch(); return 0;
}
Output: Enter the Number of Names: 4
Enter 4 Names
Enter Name-1: Arun Kumar
Enter Name-2: Bhaskar Reddy
Enter Name-3: Chandrashekhar
Enter Name-4: Lahari
Enter the Name to be Searched: Bhaskar Reddy Name Found at Position: 2
SOME USEFUL STRING FUNCTIONS

Example: Program to find length of a string without using strlen().


#include<stdio.h>
void main(void)
{
char str1[25];
int len=0;
printf("Enter string whose length is to be found:");
gets(str1);
while(str1[len]!='\0')
len++; //here the length of string is calculated.
printf("Length of the string is %d", len);
}
Output:
Enter string whose length is to be found: vtunotesbysri
Length of the string is 13

Example: Program to concatenate two strings without using strcat().


#include<stdio.h>
void main()
{
char str1[25],str2[25];
int i=0,j=0;
printf(" Enter First String:");
gets(str1);
printf("\n Enter Second String:");
gets(str2);
while(str1[i]!='\0')
i++;
while(str2[j]!='\0')
{
str1[i]=str2[j];
j++;
i++;
}
str1[i]='\0';
printf("\n Concatenated String is ");
puts(str1);
}
Output:
Enter First String: rama
Enter Second String: krishna
Concatenated String is ramakrishna
Example: Program to copy one string into other without using strcpy().
#include<stdio.h>
void main()
{
char src[100], dest[100]; int i;
printf("Enter string:");
gets(src);
i = 0;
while (src[i] != '\0')
{
dest[i] = src[i];
i++;
}
dest[i] = '\0';
printf("Copied String ; %s ", dest);
}
Output:
Enter string : vtunotes
Copied String : vtunotes
Example: Program to compare 2 strings without using strcmp().
#include<stdio.h>
void main()
{
char str1[100],str2[100]; int i=0, flag=0;
printf("Enter first string: "); scanf("%s",str1);
printf("Enter second string: "); scanf("%s",str2);
while(str1[i]!='\0' && str2[i]!='\0')
{
if(str1[i]!=str2[i])
{
flag=1;
break;
}
i++;
}
if (flag==0 && str1[i]=='\0' && str2[i]=='\0')
printf("Both strings are equal");
else
printf("Both strings are not equal");
}
Output:
Enter first string: rama
Enter second string: rama
Both strings are equal

You might also like