Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
SlideShare a Scribd company logo
1
ARRAYS
Definition
An array isa fixed-size sequencedcollectionof elementsof the same datatype.
Advantagesof arrays
 Huge amount of data can be storedundersingle variable name.
 Searchingof data itemisfaster.
 2 dimensionarraysare usedto representthe matrices.
 It ishelpful inimplementingotherdatastructure like linkedlist,queue,stack.
Types ofarrays
 One dimensional array.
 Two dimensional array.
 Multi dimensionalarray.
One dimensional array
A list of itemscan be givenone variable name usingonly one subscript is calledsingle subscripted
variable or a one dimensional array.
Declaration of one dimensional array
Syntax :
<data_type> <array_name> [size]
Data_type :It representsthe type of array(i.e)float,int,char,string.
Array_name:The name of array.
Size: Size of array representthe total numberof elementof array,datastoredinarray withindex,we
can retrieve databythere index.
Example:intx[7];
2
Initializationof one dimensionalarrays
Array can initializedateitherof the following:
 At run time .
 At compile time.
Run time initialization
An array can be explicitlyinitializedatruntime.
Syntax:
<data_type> <array_name> [size];
Example:intx[10];
Compile time initialization
The elementsof the arraycan be initialized asthe ordinaryvariables.
Example:int a[5]={1,2,3,4,5};
#include<stdio.h>
#include<conio.h>
voidmain()
{
intarr[50],i=0,b,c[5]={1,2,3,4,5};
3
clrscr();
printf("Howmanyelementyouwantto enter n");
scanf("%d",&b);
printf("Enter%dNoforarray n",b);
for(i=0;i<b ; i++)
{
scanf("%d", &arr[i]);
}
//output
printf("nElementof the arrayare :- n");
for(i=0;i<b ; i++)
{
printf("Elementof %dpositionis%d n",i,arr[i]);
printf(“Elementsof %d positionis%dn”,I,c[i]);
}
getch();
}
Output:
How manyelementyouwanttoenter 2
Enter 2 Nofor array
6
5
Elementof the array are :-
Elementof 0 positionis
6
4
Elementof 0 positionis
1
Elementof 1 positionis
5
Elementsof 1 positionis
2
Two dimensional array
A list of itemscan be givenone variable name usingtwo subscript is calledtwo dimensional
array. One subscriptfor row and another for column.
SYNTAX:
data-type array_name[row-size][column-size];
EXAMPLE:
inta[3][4];
Initializationof twodimensional arrays
Array can initializedateitherof the following:
 At run time .
 At compile time.
5
Run time initialization
An array can be explicitlyinitializedatruntime.
Syntax:
data-type array_name[row-size][column-size];
example:inta[2][2];
Compile time initialization
The elementsof the arraycan be initializedasthe ordinaryvariables.
Example:
 intodd[3][2]={1,3,5,7,9,11};
 Individual elementcanalsobe assignedas:
 Odd[0][0]=1;
 Odd[0][1]=3;
 Odd[1][0]=5;
 Odd[1][1]=7;
 Odd[2][0]=9;
 Odd[2][1]=11;
Readingdatafrom the user:
Nestedforloopisused.
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
int m, n, p, q, c, d, k, sum = 0;
6
int first[10][10], second[10][10], multiply[10][10];
printf("Enter the number of rows and columns of first matrixn");
scanf("%d%d", &m, &n);
printf("Enter the number of rows and columns of second matrixn");
scanf("%d%d", &p, &q);
if (n != p)
printf("Matrices with entered orders can't be multiplied with each
other.n");
else
{
printf("Enter the elements of first matrixn");
for (c = 0; c < m; c++)
{
for (d = 0; d < n; d++)
scanf("%d", &first[c][d]);
}
printf("Enter the elements of second matrixn");
for (c = 0; c < p; c++)
{ for (d = 0; d < q; d++)
scanf("%d", &second[c][d]);
}
for (c = 0; c < m; c++)
{
for (d = 0; d < q; d++)
{
for (k = 0; k < p; k++)
{
sum = sum + first[c][k]*second[k][d];
}
multiply[c][d] = sum;
sum = 0;
}
}
printf("Product of entered matrices:-n");
for (c = 0; c < m; c++)
{
for (d = 0; d < q; d++)
{
printf("%dt", multiply[c][d]);
printf("n");
}
}
getch();
}
7
Multidimensional array
A list of itemscan be givenone variable name usingmore than two subscript is calledmulti
dimensional array. The exact limitis determinedbythe compiler.
SYNTAX:
data-type array_name[s1][s2][s3][s4][s5]……….[sm];
EXAMPLE:
inta[3][4][5];
Dynamicarrays
STATICARRAYS:
The processof allocatingmemoryatcompile time isknownasstaticmemoryallocation
and the arrays that receive staticmemoryallocationare calledstaticarrays.
Dynamicarrays:
The processof allocatingmemorytoarraysat runtime is knownasdynamicmemory
allocationandthe arrays createdat run time are calleddynamicarrays.
Dynamicarrays are createdusingpointervariablesandmemorymanagementfunctions
malloc,callocandrealloc.Thesefunctionsare includedinthe headerfile<stdlib.h>.Thedynamicarraysis
usedto create and manipulate datastructuressuchaslinkedlist,stackandqueues.
Character Arrays & Strings
Introduction
A string is a sequence of characters. Any sequence or set of characters defined within double
quotation symbols is a constant string. In c it is required to do some meaningful operations on strings
they are:
 Readingstringdisplayingstrings
 Combiningorconcatenatingstrings
 Copyingone stringtoanother.
 Comparingstring& checkingwhethertheyare equal
 Extractionof a portionof a string
8
Declaring & InitializingStringVariables
char month1[ ]={‘j’,’a’,’n’,’u’,’a’,’r’,’y’};
Thenthe string monthisinitializing to January. This is perfectly valid but C offers a special way
to initialize strings.
The above string can be initialized as
char month1[]=”January”;
The characters of the stringare enclosedwithinapartof double quotes.The compilertakescare
of stringenclosedwithina pair of double quotes. The compiler takes care of storing the ASCII codes of
characters of the string in the memory and also stores the null terminator in the end.
/*String.c string variable*/
#include < stdio.h >
#include<conio.h>
voidmain()
{
char month[15];
printf (“Enterthe string”);
gets(month);
printf (“The stringenteredis%s”,month);
}
0 specifies a single character whose ASCII value is zero.
J A N U A R Y 0 ? ? ? ? ? ? ?
Character string terminated by a null character ‘0’.
A string variable is any valid C variable name & is always declared as an array.
syntax
char string_name[size];
9
The size determines the number of characters in the string name.
Example:
char address[100];
The size of the array should be one byte more than the actual space occupied by the string since the
complier appends a null character at the end of the string.
Reading Strings from the terminal:
The function scanf with%s format specification is needed to read the character string from the
terminal.
Example:
char address[20];
scanf(“%s”,address);
->Scanf statement has a draw back it just terminates the statement as soon as it finds a blank space,
suppose if we type the string new york then only the string new will be read and since there is a blank
space after word “new” it will terminate the string.
->The function getchar can be used repeatedly to read a sequence of successive single characters and
store it in the array.
We cannotmanipulate stringssince Cdoesnotprovide anyoperatorsfor string. For instance we cannot
assign one string to another directly.
For example:
String=”xyz”;
String1=string;
are notvalid.To copythe chars inone string to another string we may do so on a character to character
basis.
10
Reading a Line of Text
To read a line of text with white spaces, we have a special format specifier %[..] called “Edit set
conversion code” that can be used to read a line containing a variety of characters.
Example: To terminate a string only when a ‘n’ (New Line) character is inserted, we need to give the
following statement:
scanf(“%[^n]”,str);
Here, str – string variable
^n – Describes terminate the reading when ‘n’ character is encountered
Using getchar and gets Function
getchar() function is used to read a single character from the terminal. By providing a loop to
read characters until we provide a newline character, we are facilitating the reading of a line of text.
Example:
int c;
char character;
….
c = 0;
do
{
character = getchar();
line[c++] = character;
}while(character != ‘n’);
11
We may also use the gets() function present in <stdio.h> header file to read a line of text. It is in the
form:
gets(str);
Example:
char line[80];
gets(line);
Writing Strings to Screen
Using printf() function
The format specifier %s can be used to display an array of characters that is terminated by null
(0) character.
Example:printf(“%s”, name);
We can also specify the precision. Example:
%10.4s
Indicatesthatfirstfourcharacters are to be printedin a field width of 10 columns. Including a –
(minus) sign immediately after the % symbol will print the content left-justified.
For variable specification of width and precision, we use the * symbol. Example:
printf(“%*.*s”,w,s,str);
Using putchar() and puts()
We can use the putchar() function repeatedly to print a string to the screen.
Example:
Void main()
{
char name[6] = “paris”;
for(i=0;i<5;i++)
12
putchar(name[i]);
putchar(‘n’);
getch();
}
Another convenient way of printing a string to screen is using puts() function present in <stdio.h>.
Example:
puts(line);
Arithmetic operations on characters:
We can alsomanipulate the charactersaswe manipulate numbersinclanguage.Whenever the system
encountersthe character data it is automatically converted into a integer value by the system. We can
represent a character as a interface by using the following method.
x=’a’;
Printf(“%dn”,x);
Will display 97 on the screen. Arithmetic operations can also be performed on characters for example
x=’z’-1; is a valid statement. The ASCII value of ‘z’ is 122 the statement the therefore will assign 121 to
variable x.
It is also possible to use character constants in relational expressions for example
ch>’a’ && ch < = ’z’ will check whether the character stored in variable ch is a lower case letter.
A character digit can also be converted into its equivalent integer value suppose un the expression
Void main()
{
char character=’8’;
int a;
a=character-‘1’;
13
printf(“%d”,a);
getch();
}
where a is defined as an integer variable & character contains value 8 then a= ASCII value of 8 ASCII
value ‘1’=56-49=7.
We can also get the support of the c library function to converts a string of digits into their equivalent
integer values the general format of the function in
x=atoi(string);
here x is an integervariable &stringis a character array containing string of digits. For example
string=“101”; it will be stored as numeral 101 to x.
Putting Strings Together
We cannot apply the arithmetic addition for joining of two or more strings in the manner
string1 = string2 + string3; or
string1 = string2 + "SACY";
For carrying out the above we need to write a program to copy the contents of the string2 &
string3 into string1 one after the other. This process is called concatenation of strings.
strcat() Function
strcat() joins two or more strings together. It takes the following form
strcat(string1, string2);
string1 and string2 are character arrays. When the above function is executed, string2 is
appendedtostring1. It does so by removing the null character at the end of string1 and placing string2
from there. The string at string2 remains unchanged.
strcat function may also append a string constant to a string variable. The following is valid
14
strcat(part1,"SACY");
C also permits nesting of strcat functions. For example
strcat(strcat((string1,string2),string3);
is allowed and concatenates all the three strings together. The resultant string is stored in
string1.
String Handling Functions
C language recognizesthatstringisa differentclassof array bylettingusinput and output the array as a
unitand are terminatedbynull character.Clibrarysupportsa large numberof string handling functions
that can be used to array out many o f the string manipulations such as:
 Length (number of characters in the string).
 Concatentation (adding two are more strings)
 Comparing two strings.
 Substring (Extract substring from a given string)
 Copy(copies one string over another)
To do all the operations described here it is essential to include<string.h> library header file in the
program.
strlen() function:
Thisfunctioncountsand returnsthe numberof charactersin a string.The lengthdoes not include a null
character.
Syntax: n=strlen(string);
Where n is integer variable. Which receives the value of length of the string.
15
Example
length=strlen(“Hollywood”);
The function will assign number of characters 9 in the string to a integer variable length.Result is
length=9.
strcat() function:
when you combine two strings, you add the characters of one string to the end of other string. This
processiscalledconcatenation. The strcat() functionjoins2stringstogether.Ittakesthe following form
strcat(string1,string2)
string1 & string2 are character arrays. When the function strcat is executed string2 is appended to
string1. the string at string2 remains unchanged.
Example
#include<stdio.h>
#include<conio.h>
#include<string.h>
Void main()
{
strcpy(string1,”sri”);
strcpy(string2,”Bhagavan”);
Printf(“%s”,strcat(string1,string2);
getch();
}
16
From the above program segment the value of string1 becomes sribhagavan. The string at str2
remains unchanged as bhagawan. Result string1= sribhagavan
strcmp function:
In c you cannot directly compare the value of 2 strings in a condition like:
if(string1==string2)
Most librarieshowevercontainthe strcmp() function,whichreturnsazeroif 2 strings are equal,
or a non zero number if the strings are not the same. The syntax of strcmp() is given below:
strcmp(string1,string2)
String1 & string2may be stringvariablesorstringconstants.String1,& string2may be stringvariablesor
stringconstants some computers return a negative if the string1 is alphabetically less than the second
and a positive number if the string is greater than the second.
Example:
#include<stdio.h>
#include<conio.h>
#include<string.h>
Void main()
{
strcmp(“Newyork”,”Newyork”);//will return zero because 2 strings are equal.
strcmp(“their”,”therr”);//willreturna9 whichis the numeric difference between ASCII ‘i’ and ASCII ’r’.
strcmp(“The”, “the”)// will return 32 which is the numeric difference between ASCII “T” & ASCII “t”.
getch();
}
strcmpi() function
This function is same as strcmp() which compares 2 strings but not case sensitive.
17
Example :
#include<stdio.h>
#include<conio.h>
#include<string.h>
Void main()
{
strcmpi(“THE”,”the”);// will return 0.
getch();
}
strcpy() function:
C does not allow you to assign the characters to a string directly as in the statement name=”Robert”;
Insteaduse the strcpy(0functionfoundinmostcompilersthe syntax of the functionisillustratedbelow.
strcpy(string1,string2);
Strcpy function assigns the contents of string2 to string1. string2 may be a character array variable or a
string constant.
Example:
#include<stdio.h>
#include<conio.h>
#include<string.h>
Void main()
{
strcpy(Name,”Robert”);
getch();
}
In the above example Robert is assigned to the string called name. Result:Name=Robert.
18
Other string functions
 strncpy//stringcopy
 strncmp//stringcompare
 strncat//stringconcatenation
 strstr//findingsubstring
strncpy//string copy
Thisis three parameterfunctionandisinvokedasfollows.
Syntax:strncpy(s1,s2,n);
Example:
#include<stdio.h>
#include<conio.h>
#include<string.h>
Void main()
{
char s2=”ammukutti”;
strncpy(s1,s2,5);
s1[6]=’0’;
printf(“%s”,s1);
getch();
}
Result:ammuk
strncmp//string compare
syntax:strncmp(s1,s2,n);
thiscomparesleftmostn charactersof s1 and s2 andreturns.
(a) 0 if theyare equal.
(b) Negative number,ifs1 sub-stringislessthans2.
(c) Positive numberotherwise negative number.
19
strncat//string concatenation
syntax:strncat(s1,s2,n);
Concatenate the leftmostncharacters of s2 to the endof s1.
Example:
#include<stdio.h>
#include<conio.h>
#include<string.h>
Void main()
{
Char s1=”Bala”, s2=”ammukutti”;
strncat(s1,s2,5);
printf(“%s”,s1);
getch();
}
Result:Balaammuk.
strstr//finding sub string
It isa twoparameterfunctionthatcan be usedto locate a sub-stringina string.
Syntax:strstr(s1,s2);
Example:
#include<stdio.h>
#include<conio.h>
#include<string.h>
Void main()
{
20
Char s1=”Abacus”, s2=”cus”;
if(strstr(s1,s2)==NULL)
printf(“substringisnotfound”);
else
printf(“s2isa substringof s1);
getch();
}
Strchr//determine the existence ofa first occurrence of character in a string
Example:
s1=”Mohamed”;
strchr(s1,”M”);
strrchr//last occurrence of character ina string
Example:
s1=”Mohamed”;
strrchr(s1,”d”);

More Related Content

Array &strings

  • 1. 1 ARRAYS Definition An array isa fixed-size sequencedcollectionof elementsof the same datatype. Advantagesof arrays  Huge amount of data can be storedundersingle variable name.  Searchingof data itemisfaster.  2 dimensionarraysare usedto representthe matrices.  It ishelpful inimplementingotherdatastructure like linkedlist,queue,stack. Types ofarrays  One dimensional array.  Two dimensional array.  Multi dimensionalarray. One dimensional array A list of itemscan be givenone variable name usingonly one subscript is calledsingle subscripted variable or a one dimensional array. Declaration of one dimensional array Syntax : <data_type> <array_name> [size] Data_type :It representsthe type of array(i.e)float,int,char,string. Array_name:The name of array. Size: Size of array representthe total numberof elementof array,datastoredinarray withindex,we can retrieve databythere index. Example:intx[7];
  • 2. 2 Initializationof one dimensionalarrays Array can initializedateitherof the following:  At run time .  At compile time. Run time initialization An array can be explicitlyinitializedatruntime. Syntax: <data_type> <array_name> [size]; Example:intx[10]; Compile time initialization The elementsof the arraycan be initialized asthe ordinaryvariables. Example:int a[5]={1,2,3,4,5}; #include<stdio.h> #include<conio.h> voidmain() { intarr[50],i=0,b,c[5]={1,2,3,4,5};
  • 3. 3 clrscr(); printf("Howmanyelementyouwantto enter n"); scanf("%d",&b); printf("Enter%dNoforarray n",b); for(i=0;i<b ; i++) { scanf("%d", &arr[i]); } //output printf("nElementof the arrayare :- n"); for(i=0;i<b ; i++) { printf("Elementof %dpositionis%d n",i,arr[i]); printf(“Elementsof %d positionis%dn”,I,c[i]); } getch(); } Output: How manyelementyouwanttoenter 2 Enter 2 Nofor array 6 5 Elementof the array are :- Elementof 0 positionis 6
  • 4. 4 Elementof 0 positionis 1 Elementof 1 positionis 5 Elementsof 1 positionis 2 Two dimensional array A list of itemscan be givenone variable name usingtwo subscript is calledtwo dimensional array. One subscriptfor row and another for column. SYNTAX: data-type array_name[row-size][column-size]; EXAMPLE: inta[3][4]; Initializationof twodimensional arrays Array can initializedateitherof the following:  At run time .  At compile time.
  • 5. 5 Run time initialization An array can be explicitlyinitializedatruntime. Syntax: data-type array_name[row-size][column-size]; example:inta[2][2]; Compile time initialization The elementsof the arraycan be initializedasthe ordinaryvariables. Example:  intodd[3][2]={1,3,5,7,9,11};  Individual elementcanalsobe assignedas:  Odd[0][0]=1;  Odd[0][1]=3;  Odd[1][0]=5;  Odd[1][1]=7;  Odd[2][0]=9;  Odd[2][1]=11; Readingdatafrom the user: Nestedforloopisused. Example: #include<stdio.h> #include<conio.h> void main() { int m, n, p, q, c, d, k, sum = 0;
  • 6. 6 int first[10][10], second[10][10], multiply[10][10]; printf("Enter the number of rows and columns of first matrixn"); scanf("%d%d", &m, &n); printf("Enter the number of rows and columns of second matrixn"); scanf("%d%d", &p, &q); if (n != p) printf("Matrices with entered orders can't be multiplied with each other.n"); else { printf("Enter the elements of first matrixn"); for (c = 0; c < m; c++) { for (d = 0; d < n; d++) scanf("%d", &first[c][d]); } printf("Enter the elements of second matrixn"); for (c = 0; c < p; c++) { for (d = 0; d < q; d++) scanf("%d", &second[c][d]); } for (c = 0; c < m; c++) { for (d = 0; d < q; d++) { for (k = 0; k < p; k++) { sum = sum + first[c][k]*second[k][d]; } multiply[c][d] = sum; sum = 0; } } printf("Product of entered matrices:-n"); for (c = 0; c < m; c++) { for (d = 0; d < q; d++) { printf("%dt", multiply[c][d]); printf("n"); } } getch(); }
  • 7. 7 Multidimensional array A list of itemscan be givenone variable name usingmore than two subscript is calledmulti dimensional array. The exact limitis determinedbythe compiler. SYNTAX: data-type array_name[s1][s2][s3][s4][s5]……….[sm]; EXAMPLE: inta[3][4][5]; Dynamicarrays STATICARRAYS: The processof allocatingmemoryatcompile time isknownasstaticmemoryallocation and the arrays that receive staticmemoryallocationare calledstaticarrays. Dynamicarrays: The processof allocatingmemorytoarraysat runtime is knownasdynamicmemory allocationandthe arrays createdat run time are calleddynamicarrays. Dynamicarrays are createdusingpointervariablesandmemorymanagementfunctions malloc,callocandrealloc.Thesefunctionsare includedinthe headerfile<stdlib.h>.Thedynamicarraysis usedto create and manipulate datastructuressuchaslinkedlist,stackandqueues. Character Arrays & Strings Introduction A string is a sequence of characters. Any sequence or set of characters defined within double quotation symbols is a constant string. In c it is required to do some meaningful operations on strings they are:  Readingstringdisplayingstrings  Combiningorconcatenatingstrings  Copyingone stringtoanother.  Comparingstring& checkingwhethertheyare equal  Extractionof a portionof a string
  • 8. 8 Declaring & InitializingStringVariables char month1[ ]={‘j’,’a’,’n’,’u’,’a’,’r’,’y’}; Thenthe string monthisinitializing to January. This is perfectly valid but C offers a special way to initialize strings. The above string can be initialized as char month1[]=”January”; The characters of the stringare enclosedwithinapartof double quotes.The compilertakescare of stringenclosedwithina pair of double quotes. The compiler takes care of storing the ASCII codes of characters of the string in the memory and also stores the null terminator in the end. /*String.c string variable*/ #include < stdio.h > #include<conio.h> voidmain() { char month[15]; printf (“Enterthe string”); gets(month); printf (“The stringenteredis%s”,month); } 0 specifies a single character whose ASCII value is zero. J A N U A R Y 0 ? ? ? ? ? ? ? Character string terminated by a null character ‘0’. A string variable is any valid C variable name & is always declared as an array. syntax char string_name[size];
  • 9. 9 The size determines the number of characters in the string name. Example: char address[100]; The size of the array should be one byte more than the actual space occupied by the string since the complier appends a null character at the end of the string. Reading Strings from the terminal: The function scanf with%s format specification is needed to read the character string from the terminal. Example: char address[20]; scanf(“%s”,address); ->Scanf statement has a draw back it just terminates the statement as soon as it finds a blank space, suppose if we type the string new york then only the string new will be read and since there is a blank space after word “new” it will terminate the string. ->The function getchar can be used repeatedly to read a sequence of successive single characters and store it in the array. We cannotmanipulate stringssince Cdoesnotprovide anyoperatorsfor string. For instance we cannot assign one string to another directly. For example: String=”xyz”; String1=string; are notvalid.To copythe chars inone string to another string we may do so on a character to character basis.
  • 10. 10 Reading a Line of Text To read a line of text with white spaces, we have a special format specifier %[..] called “Edit set conversion code” that can be used to read a line containing a variety of characters. Example: To terminate a string only when a ‘n’ (New Line) character is inserted, we need to give the following statement: scanf(“%[^n]”,str); Here, str – string variable ^n – Describes terminate the reading when ‘n’ character is encountered Using getchar and gets Function getchar() function is used to read a single character from the terminal. By providing a loop to read characters until we provide a newline character, we are facilitating the reading of a line of text. Example: int c; char character; …. c = 0; do { character = getchar(); line[c++] = character; }while(character != ‘n’);
  • 11. 11 We may also use the gets() function present in <stdio.h> header file to read a line of text. It is in the form: gets(str); Example: char line[80]; gets(line); Writing Strings to Screen Using printf() function The format specifier %s can be used to display an array of characters that is terminated by null (0) character. Example:printf(“%s”, name); We can also specify the precision. Example: %10.4s Indicatesthatfirstfourcharacters are to be printedin a field width of 10 columns. Including a – (minus) sign immediately after the % symbol will print the content left-justified. For variable specification of width and precision, we use the * symbol. Example: printf(“%*.*s”,w,s,str); Using putchar() and puts() We can use the putchar() function repeatedly to print a string to the screen. Example: Void main() { char name[6] = “paris”; for(i=0;i<5;i++)
  • 12. 12 putchar(name[i]); putchar(‘n’); getch(); } Another convenient way of printing a string to screen is using puts() function present in <stdio.h>. Example: puts(line); Arithmetic operations on characters: We can alsomanipulate the charactersaswe manipulate numbersinclanguage.Whenever the system encountersthe character data it is automatically converted into a integer value by the system. We can represent a character as a interface by using the following method. x=’a’; Printf(“%dn”,x); Will display 97 on the screen. Arithmetic operations can also be performed on characters for example x=’z’-1; is a valid statement. The ASCII value of ‘z’ is 122 the statement the therefore will assign 121 to variable x. It is also possible to use character constants in relational expressions for example ch>’a’ && ch < = ’z’ will check whether the character stored in variable ch is a lower case letter. A character digit can also be converted into its equivalent integer value suppose un the expression Void main() { char character=’8’; int a; a=character-‘1’;
  • 13. 13 printf(“%d”,a); getch(); } where a is defined as an integer variable & character contains value 8 then a= ASCII value of 8 ASCII value ‘1’=56-49=7. We can also get the support of the c library function to converts a string of digits into their equivalent integer values the general format of the function in x=atoi(string); here x is an integervariable &stringis a character array containing string of digits. For example string=“101”; it will be stored as numeral 101 to x. Putting Strings Together We cannot apply the arithmetic addition for joining of two or more strings in the manner string1 = string2 + string3; or string1 = string2 + "SACY"; For carrying out the above we need to write a program to copy the contents of the string2 & string3 into string1 one after the other. This process is called concatenation of strings. strcat() Function strcat() joins two or more strings together. It takes the following form strcat(string1, string2); string1 and string2 are character arrays. When the above function is executed, string2 is appendedtostring1. It does so by removing the null character at the end of string1 and placing string2 from there. The string at string2 remains unchanged. strcat function may also append a string constant to a string variable. The following is valid
  • 14. 14 strcat(part1,"SACY"); C also permits nesting of strcat functions. For example strcat(strcat((string1,string2),string3); is allowed and concatenates all the three strings together. The resultant string is stored in string1. String Handling Functions C language recognizesthatstringisa differentclassof array bylettingusinput and output the array as a unitand are terminatedbynull character.Clibrarysupportsa large numberof string handling functions that can be used to array out many o f the string manipulations such as:  Length (number of characters in the string).  Concatentation (adding two are more strings)  Comparing two strings.  Substring (Extract substring from a given string)  Copy(copies one string over another) To do all the operations described here it is essential to include<string.h> library header file in the program. strlen() function: Thisfunctioncountsand returnsthe numberof charactersin a string.The lengthdoes not include a null character. Syntax: n=strlen(string); Where n is integer variable. Which receives the value of length of the string.
  • 15. 15 Example length=strlen(“Hollywood”); The function will assign number of characters 9 in the string to a integer variable length.Result is length=9. strcat() function: when you combine two strings, you add the characters of one string to the end of other string. This processiscalledconcatenation. The strcat() functionjoins2stringstogether.Ittakesthe following form strcat(string1,string2) string1 & string2 are character arrays. When the function strcat is executed string2 is appended to string1. the string at string2 remains unchanged. Example #include<stdio.h> #include<conio.h> #include<string.h> Void main() { strcpy(string1,”sri”); strcpy(string2,”Bhagavan”); Printf(“%s”,strcat(string1,string2); getch(); }
  • 16. 16 From the above program segment the value of string1 becomes sribhagavan. The string at str2 remains unchanged as bhagawan. Result string1= sribhagavan strcmp function: In c you cannot directly compare the value of 2 strings in a condition like: if(string1==string2) Most librarieshowevercontainthe strcmp() function,whichreturnsazeroif 2 strings are equal, or a non zero number if the strings are not the same. The syntax of strcmp() is given below: strcmp(string1,string2) String1 & string2may be stringvariablesorstringconstants.String1,& string2may be stringvariablesor stringconstants some computers return a negative if the string1 is alphabetically less than the second and a positive number if the string is greater than the second. Example: #include<stdio.h> #include<conio.h> #include<string.h> Void main() { strcmp(“Newyork”,”Newyork”);//will return zero because 2 strings are equal. strcmp(“their”,”therr”);//willreturna9 whichis the numeric difference between ASCII ‘i’ and ASCII ’r’. strcmp(“The”, “the”)// will return 32 which is the numeric difference between ASCII “T” & ASCII “t”. getch(); } strcmpi() function This function is same as strcmp() which compares 2 strings but not case sensitive.
  • 17. 17 Example : #include<stdio.h> #include<conio.h> #include<string.h> Void main() { strcmpi(“THE”,”the”);// will return 0. getch(); } strcpy() function: C does not allow you to assign the characters to a string directly as in the statement name=”Robert”; Insteaduse the strcpy(0functionfoundinmostcompilersthe syntax of the functionisillustratedbelow. strcpy(string1,string2); Strcpy function assigns the contents of string2 to string1. string2 may be a character array variable or a string constant. Example: #include<stdio.h> #include<conio.h> #include<string.h> Void main() { strcpy(Name,”Robert”); getch(); } In the above example Robert is assigned to the string called name. Result:Name=Robert.
  • 18. 18 Other string functions  strncpy//stringcopy  strncmp//stringcompare  strncat//stringconcatenation  strstr//findingsubstring strncpy//string copy Thisis three parameterfunctionandisinvokedasfollows. Syntax:strncpy(s1,s2,n); Example: #include<stdio.h> #include<conio.h> #include<string.h> Void main() { char s2=”ammukutti”; strncpy(s1,s2,5); s1[6]=’0’; printf(“%s”,s1); getch(); } Result:ammuk strncmp//string compare syntax:strncmp(s1,s2,n); thiscomparesleftmostn charactersof s1 and s2 andreturns. (a) 0 if theyare equal. (b) Negative number,ifs1 sub-stringislessthans2. (c) Positive numberotherwise negative number.
  • 19. 19 strncat//string concatenation syntax:strncat(s1,s2,n); Concatenate the leftmostncharacters of s2 to the endof s1. Example: #include<stdio.h> #include<conio.h> #include<string.h> Void main() { Char s1=”Bala”, s2=”ammukutti”; strncat(s1,s2,5); printf(“%s”,s1); getch(); } Result:Balaammuk. strstr//finding sub string It isa twoparameterfunctionthatcan be usedto locate a sub-stringina string. Syntax:strstr(s1,s2); Example: #include<stdio.h> #include<conio.h> #include<string.h> Void main() {
  • 20. 20 Char s1=”Abacus”, s2=”cus”; if(strstr(s1,s2)==NULL) printf(“substringisnotfound”); else printf(“s2isa substringof s1); getch(); } Strchr//determine the existence ofa first occurrence of character in a string Example: s1=”Mohamed”; strchr(s1,”M”); strrchr//last occurrence of character ina string Example: s1=”Mohamed”; strrchr(s1,”d”);