Arrays II
Arrays II
Arrays II
(Non-Numeric Arrays)
0
Chapter Outline
“There are basically two types of people. People
10.1. Introduction.
who accomplish things and people who claim to
have accomplished things. The first group is less 10.2. One-Dimensional
crowded.” -Mark Twain
array of characters.
10.3. String-handling
functions.
10.4. Two-Dimensional
array of characters.
“We must remember that one determined 10.5. Conclusion
person can make a significant difference, and
that a small group of determined people can
change the course of history.” -Sonia Johnson
e.g., “I Love India” is a string. Whenever a string is stored in memory, the compiler automatically inserts
a NULL character (\0) at the end of string. This NULL character is a string terminator, i.e., it denotes the
end of string. This NULL character is the first ASCII character which has a value of zero.
In this syntax:
<Storage_class> is any one of auto, extern, static or register, an optional one.
char is the data type that determines the type of elements in the array are as characters.
<array_name> is any valid identifier.
size, a positive integer constant or integer constant expression, determines the number of characters in
the string.
Ex: char name[20]; //can hold a string of 19 characters; one location is for NULL
char a [35]; //can hold a string of 34 characters; one location is for NULL
When we declare a character array, a memory location should be reserved for the NULL character.
1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012
I L o v e I n d i a \0
a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9] a[10] a[11] a[12]
Interview question #1
If I can say
char a[]=”I Love India”;
Why can’t I say
char a[13];
a=”I Love India”;
As we know that strings are arrays. As we can’t assign arrays directly, strings can’t be assigned
directly. Instead, we can use strcpy() like this:
strcpy(a,”Hello world”);
}
Usually, scanf() statement expects an address of the variable. Because the name of the array itself is an
address of it, we don’t use an ampersand (&) before the name of the string. The %s option uses a blank
space as a delimiter and hence it considers the character separated by blank space as two strings.
The disadvantage of scanf() function is that there is no way to read a multi-word string (i.e., string
with spaces) into a single variable. The scanf() function terminates the input string when it finds blank
space in input string. E.g., if the input for scanf() function is “pradeep kumar”, the string variable str
holds only the string pradeep.
To read a multi-word, we can use the following form of scanf():
#include<stdio.h>
main()
{
char str[25];
printf(“\n Enter your name:”);
scanf(“[^\n]”,str);//[^\n] means read set of characters except new line character
printf(“\n Your Name=%s”,str);
}
10.2.3.2. By using the gets() and puts() functions
The gets() function can also be used to read a string using keyboard. It reads and assigns the input string
to the character array until the ENTER key is pressed. The input string can consist of blank spaces and
tabs as part of it. The puts() function is used to print that string which was read by using gets() or
scanf().
Ex: #include<stdio.h>
main()
{
char str[25];
printf(“\n Enter your name:”);
gets(str);
puts(str);
}
The string can be entered until the ENTER key is pressed and can be stored in string variable. Now,
suppose that we input the string “pradeep kumar”. Then the variable str holds the whole string “pradeep
kumar”.
The disadvantage of gets() function is that it can be used to read only one string at a time. E.g.,
the following gets() statement is invalid:
gets(str1,str2); //invalid
The gets() function expects only one string as an argument. If more than one string is input to this
function, the compiler gives an error “too many arguments to function gets”
However, a scanf() function can be used to read more than one string at a time.
E.g., scanf(“%s%s%s”,str1,str2,str3); can be used to read 3 strings.
10.2.3.3. By using a loop
A string can be read character by character by using a for loop (or any loop). Each time the loop runs, the
getchar() function takes the character from the keyboard and that character will be assigned to the one of
character array’s locations. The loop should be stopped when the new line character is encountered. When
the repetition has stopped, the last location should occupy the NULL character for denoting the end of
string.
For printing the string using a loop, the iterative process should start at 0 th location and should
terminate before the NULL character. In each iteration, the character should be printed with the help of
putchar() or printf() with %c conversion specifier.
E.g.,#include<stdio.h>
main()
{ char str1[23],ch;
int i;
printf("\n Enter any string:");
for(i=0;(ch=getchar())!='\n';i++)
str1[i]=ch;
str1[i]='\0';
for(i=0;str1[i]!=’\0’;i++)
putchar(str1[i]);
}
Example programs:
/*A program to check whether given /*Program to count no.of vowels and
string is palindrome or not*/ consonants in a line of text*/
#include<stdio.h> #include<stdio.h>
main() main()
{ {
char str[30]; char text[50];
int len=0,flag=0,i,j; int nv=0,nc=0;
printf("\n Enter a string:"); printf(“\n Enter a line of text:”);
gets(str); gets(text);
for(i=0;str[i]!='\0';i++) for(i=0;text[i]!=’\0’;i++)
len++; {
for(i=0,j=len-1;i<j;i++,j--) if(text[i]==’a’||text[i]==’e’||text[i]==’o’||
if(str[i]!=str[j]) text[i]==’i’||text[i]==’u’)
{ nv++;
flag=1; else
break; nc++;
} }
if(flag==0) printf(“\n No.of vowels=%d”,nv);
printf("\n Given string is palindrome"); printf(“\n No.of consonants=%d”,nc); }
else
printf("\n Given string is not a
palindrome");
}
/*Program to count no.of lines, words /*Program to convert the case of text*/
and characters in multiple lines of #include<stdio.h>
text*/ main()
#include<stdio.h> {
main() char text[50];
{ printf(“\n Enter a line of text:”);
char text[150],ch; gets(text);
int nl=0,nw=0,nc=0; for(i=0;text[i]!=’\0’;i++)
printf(“\n Enter multiple lines of text (end {
with #):”); if(text[i]>=’A’ && text[i]<=’z’)
for(i=0;(ch=getchar())!=’#’;i++) text[i]=text[i]+32;
{nc++; else
if(ch==’ ‘) text[i]=text[i]-32;
nw++; }
else if(ch==’\n’) printf(“\n converted text=%s”,text);
nl++; }
else ;
}
printf(“\n No.of lines=%d”,nl);
printf(“\n No.of words=%d”,nc);
printf(“\n No.of characters=%d”,nc); }
Passing a string to a function
To pass a string to a function, these rules should be followed:
The function must be called by passing only the name of the string, without the subscript.
In the function definition, the formal parameter must be a character array type; the size of the
array does not need to be specified.
The function prototype must show that the argument is a character array.
The following program demonstrates the concept of passing a string to a function:
}
void display(char s[]) //function definition
{
printf(“\n Given string=%s”,s);
}
int getCount(char s[],char ch) //function definition
{
int count=0,i;
for(i=0;s[i]!=’\0’;i++)
if(s[i]==ch)
count++;
return count;
}
/* A program to convert a string to a /* A program to convert an integer to a
number*/ string*/
#include<stdio.h> #include<stdio.h>
int str_to_int(char []); #include<string.h>
main() char * int_to_str(int);
{ main()
char str[10]="1234"; {int n = 1234;
printf("number = %d",str_to_int(str)); printf("string is %s",int_to_str(n));
} }
int str_to_int(char str[]) char * int_to_str(int n)
{ {static char str[10];
int i,sum=0; char temp;
for(i=0;str[i]!='\0';i++) int i=1,j;
{ if(n>=0)
if(str[i]=='-' && i==0) str[0]='+';
continue; else
sum = sum*10 + (str[i]-'0'); {str[0]='-';
} n = -n;}
if(str[0]=='-') for(;n>0;n=n/10)
sum = -sum; str[i++] = n%10+'0';
return sum; str[i]='\0';
} for(i=1,j=strlen(str)-1;i<j;i++,j--)
{temp = str[i]; str[i] = str[j]; str[j] = temp;}
return str;
}
/*A program to convert a string to float*/ /*A program to convert a float to string*/
#include<stdio.h> #include<stdio.h>
char * float_to_str(float);
float str_to_float(char *);
main()
main() {float n = -1234.1234;
{ char str[20]="-1234.12345"; printf("string is %s",float_to_str(n));
printf("number = %f",str_to_float(str)); }
char * float_to_str(float p)
}
{static char str[10];
float str_to_float(char *str) char temp;
{ int i,x=0,y=10; int i=1,j,k,n,m;
float sum=0; if(p>=0)
str[0]='+';
for(i=0;str[i]!='\0';i++)
else
{ if(str[i]=='-' && i==0) { str[0]='-';
continue; p = -p;}
if(str[i]=='.') m = n = p;
{x=1; for(;n>0;n=n/10)
str[i++] = n%10+'0';
continue;} p = p-m;
if(x==0) for(j=1;j<=4;j++)
sum = sum*10 + (str[i]-'0'); p = p*10;
else n=p;
str[i]='.';
{ sum = sum + (str[i]-'0')/(float)y; k = i;
y=y*10; for(i++;n>0;n=n/10)
}} str[i++] = n%10+'0';
if(str[0]=='-') str[i]='\0';
for(i=1,j=k-1;i<j;i++,j--)
sum = -sum; {temp = str[i]; str[i] = str[j]; str[j] = temp; }
return sum;} for(i=k+1,j=strlen(str)-1;i<j;i++,j--)
{temp = str[i]; str[i] = str[j]; str[j] = temp;}
return str;
}
10.3. String-handling functions
C supports a number of string handling functions. All of these built-in functions are aimed at
performing various operations on strings. All of these built-in functions are defined in the header file
string.h. Therefore, whenever we use one of these string handling functions, we should add the
preprocessor statement #include<string.h> to our program. Some of the string- handling functions are:
strlen() strrev() strcpy() strcat() strcmp()
strlwr() strupr() strncpy() strncat() strncmp()
1. strlen() function: This function is used to find the length of the string excluding the NULL character.
In other words, this function is used to count the number of characters in a string. Its syntax is as follows:
int strlen(string1);
2. strrev() function: This function is used to find the reversed string of a given string. Its syntax is as
follows: strrev(string1);
strcpy(string1,string2);
/* A program to copy one string to another /* A program to copy one string to another
using strcpy() function*/ without using strcpy() function*/
#include<stdio.h> #include<stdio.h>
#include<string.h> void MyStringCopy(char[],char []);
main() main()
{ { char string1[30],string2[30];
char string1[30],string2[30]; printf("\n Enter first string:");
printf(“\n Enter first string:”); gets(string1);
gets(string1); printf("\n Enter second string:");
printf(“\n Enter second string:”); gets(string2);
gets(string2); MyStringCopy(string1,string2);
strcpy(string1,string2); }
printf(“\n First string=%s”,string1); void MyStringCopy(char str1[30],char str2[30])
printf(“\n Second string=%s”,string2); { int i;
} for(i=0;str2[i]!='\0';i++)
str1[i]=str2[i];
str1[i]='\0';
printf("\n First string=%s",str1);
printf("\n Second string=%s",str2);
}
4.strcat() function: This function is used to concatenate two strings. i.e., it appends one string at the
end of the specified string. Its syntax as follows:
strcat(string1,string2);
/* A program to concatenate one string with /* A program to concatenate one string with
another using strcat() function*/ another without using strcat() function*/
#include<stdio.h> #include<stdio.h>
#include<string.h> void MyStringConcat(char[],char[]);
main() main()
{ { char string1[30],string2[15];
char string1[30],string2[15]; printf("\n Enter first string:");
printf(“\n Enter first string:”); gets(string1);
gets(string1); printf("\n Enter second string:");
printf(“\n Enter second string:”); gets(string2);
gets(string2); MyStringConcat(string1,string2);
strcat(string1,string2); }
printf(“\n Concatenated string=%s”,string1); void MyStringConcat(char str1[30],char str2[15])
} { int i,j;
for(i=0;str1[i]!='\0';i++);
for(j=0;str2[j]!=0;j++)
str1[i+j]=str2[j];
str1[i+j]='\0';
printf("\n Concatenated string=%s",str1);
}
5. strcmp() function: This function compares two strings character by character (ASCII comparison) and
returns one of three values {-1,0,1}. Its syntax is as follows:
int strcmp(string1,string2);
6. strlwr() function: This function converts all the uppercase alphabets into lowercase. Its syntax is as
follows:
strlwr(string1);
7. strupr() function: This function converts all the lowercase alphabets into uppercase. Its syntax is as
follows:
strupr(string1);
strncpy(string1,string2,n);
where string1 and string2 are the one-dimensional arrays of characters and n is an integer.
e.g., string1 holds Delhi and string2 holds Bangalore and n=4, then strncpy() copies the first 4
characters of string2 to string1. The string1 holds the copied substring Bang.
strncat(string1,string2,n);
where string1 and string2 are the one-dimensional arrays of characters and n is an integer.
e.g., string1 holds Master and string2 holds System and n=3, then strncpy() concatenates or adds
the first 3 characters of string2 to string1. The string1 holds the concatenated string MasterSys.
10. strncmp() function: This function compares the first n characters of two input strings and returns
one of these 3 values {-1,0,1} same as strcmp() function. Its syntax is as follows:
strncmp(string1,string2,n);
where string1 and string2 are the one-dimensional arrays of characters and n is an integer.
e.g., string1 holds master and string2 holds minister and n=4, then strncmp() compares first 4
characters of both of these strings character by character and returns the value (i.e., -1) as strcmp()
returns.
/* A program to compare first n characters of /* A program to compare first n characters of
two strings using strncmp() function*/ two strings without using strncmp()
#include<stdio.h> function*/
#include<string.h> #include<stdio.h>
main() int MyStringNCmp(char[],char[],int);
{ main()
char string1[30],string2[15]; {
int x; char string1[30],string2[30];
printf(“\n Enter first string:”); int n,x;
gets(string1); printf("\n Enter first string:");
printf(“\n Enter second string:”); gets(string1);
gets(string2); printf("\n Enter second string:");
x=strncmp(string1,string2); gets(string2);
if(x==0) printf("\n Enter howmany characters:");
printf(“\n Both strings are equal”); scanf("%d",&n);
else if(x>0) x=MyStringNCmp(string1,string2,n);
printf(“\n First string is bigger”); if(x==0)
else printf("\n Both strings are equal");
printf(“\n Second string is bigger”); else if(x>0)
} printf("\n First string is greater");
else
printf("\n Second string is greater");
}
int MyStringNCmp(char str1[],char str2[],int n)
{ int i,c=0;
for(i=0;i<n;i++)
{ if(str1[i]>str2[i])
{ c=1;
break;
}
if(str1[i]<str2[i])
{ c=-1;
break;
}
}
return c;
}
10.4.1. Declaration: Like Two-dimensional numeric arrays, Two-dimensional character arrays should be
declared before it is used. A Two-dimensional array of characters can be declared as follows:
<Storage_class> char <array_name>[row][column];
where <Storage_class> is any one of auto, extern, static or register, an optional one.
char is the data type that determines the type of elements in the array.
<array_name> is any valid identifier.
row, a positive integer, determines the number of strings in the array.
Column, a positive integer, determines the number of characters a string can hold.
Ex: char a[5][10]; //can hold 5 input strings, each input string should be of length 9 chars.
10.4.2. Initialization: Like One-dimensional character array, a Two-dimensional character array can also
be initialized with the help of assignment operator as follows:
char names[3][10]={ {‘R’,’a’,’j’,’ ’,’k’,’u’,’m’,’a’,’r’},
{‘S’,’a’,’n’,’j’,’a’,’n’,’a’},
{‘P’,’o’,’o’,’j’,’a’}};
is equivalent to
char names[3][10]={“Raj kumar”,”Sanjana”,”Pooja”};
When this Two-dimensional character array is initialized, it will be in memory as follows:
[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]
names[0] R a j k u m a r \0
names[1] S a n j a n a \0
names[2]
P o o j a \0
10.4.3. Reading and printing multiple strings: The above three methods will be very helpful in
reading and printing each string with the help of a loop. The loop is used for keeping track of loop counter
of rows of two-dimensional array. The following example clears this concept:
Method-1: using printf() and Method-2: using gets() Method-3: Using getchar() and
scanf() and puts() putchar() repeatedly
#inlcude<stdio.h> #inlcude<stdio.h> #include<stdio.h>
main() main() main()
{ { { char names[10][15],ch;
char names[10][15]; char names[10][15]; int i,n,j,k;
int n,i; int n,i; printf(“\n How many strings:”);
printf(“\n How many strings:”); printf(“\n How many scanf(“%d”,&n);
scanf(“%d”,&n); strings:”); for(k=0;k<n;k++)
for(i=0;i<n;i++) scanf(“%d”,&n); {printf(“\n Enter %d
{printf(“\n Enter %d for(i=0;i<n;i++) string:”,k+1);
string:”,i+1); {printf(“\n Enter %d for(i=0;(ch=getchar())!='\n';i++)
scanf(“%s”,names[i]); string:”,i+1); names[k][i]=ch;
} gets(names[i]); names[k][i]='\0';
printf(“\n Given strings are:”); } }
for(i=0;i<n;i++) printf(“\n Given strings printf(“\n Given strings are:”);
printf(“%s\t”,names[i]); are:”); for(k=0;k<n;k++)
} for(i=0;i<n;i++) { for(i=0;names[k][i]!=’\0’;i++)
puts(names[i]); putchar(names[k][i]);
} putchar(‘\n’);
}
}
/*A program print frequencies of words /* A program to print words those begin
in a line of text*/ with given alphabet*/
#include<stdio.h> #include<stdio.h>
#include<string.h> main()
main() {
{ char **words,alpha;
char str[50],copy[20][20],word[15]; int n,i;
char temp[]=" "; printf("\n Enter how many words:");
int i,j,k,l,count; scanf("%d",&n);
printf("\n Enter a line of text:"); for(i=0;i<n;i++)
scanf("%[^\n]",str); *(words+i)=(char *)malloc(15*sizeof(char));
k=0; printf("\n Enter %d words",n);
for(i=0;str[i]!='\0';i++) for(i=0;i<n;i++)
{ j=i; scanf("%s",*(words+i));
l=0; printf("\n Enter the alphabet based on which
while(str[j]!=' ') words are displayed:");
{ copy[k][l]=str[j]; scanf("\n%c",&alpha);
l++; printf("\n The searched words starts
j++; with \'%c\' are:",alpha);
} for(i=0;i<n;i++)
copy[k][l]='\0'; {
k++; if(words[i][0]==alpha)
i=j; printf("%s\t",*(words+i));
} }
for(i=0;i<k;i++) }
{ count=1;
for(j=i+1;j<k;j++)
{ if(strcmp(copy[i],copy[j])==0)
{
strcpy(copy[j]," ");
count++;
}
}
if(strcmp(copy[i]," ")!=0)
printf("\n%s occured %d
times",copy[i],count);
}
}
10.5. Conclusion
Generally, a string is a collection of characters. In C, just like int represents integer values, there is no
data type that represents strings. Instead, a string is represented as a one-dimensional array of
characters. Each string has one termination character (‘\0’) that denotes the end of string.
In C, there is a header file namely string.h that has different built-in functions which perform
various operations on strings. In order to represent one string (either single word or multi-word), one-
dimensional array is helpful. In order to store multiple strings (either single word or multi-word), two-
dimensional array is helpful.