Arrays and Strings
Arrays and Strings
Arrays and 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:
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:
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.
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.
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 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
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
This way of reading / printing a 2D’ array is not easy and not recommended
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.
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
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 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:
{
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);