Working with Strings & Standard Functions 275
Explanation In the above program string is entered that is to be tested for PALINDROME. The string
length is calculated and assigned to variable ' j ' . The value o f ' j ' is less by one with original string
length because the array elements are counted from zero (0).
The i f statement within the w h ile loop checks the first and last character of string for equality.
Counter variable ' i ' and ' j ' denote the first and the last characters respectively. To get the successive
characters from both the ends variable 1 i ' is increased and % j ' is decreased. Till the match variable
'test' is 1 and the loop continues otherwise test is set to zero (0) and the break statement terminates the
loop.
8.40 Write a program to compare the strings using strcmpO function and display their ASCII
difference. Initialize the strings and copy some names of the cities to the variables.
# include <canio.h>
# include <stdio.h>
# include <string.h>
mainQ
{
char a l [15], a2 [1 5 ], a3 [15], a4 [15 ], a5 [15], a6 [15 ];
in t c l, c2, c3 r
strcpy (al,"NAGPUR");
strcpy(a2,"NAGPOR*);
Strcpy(a3, "PANDHARPOR");
strcpy(a4,"KDIBAPDR");
Strcpy(a5,"AURANGABAD");
Strcpy(a6, "HYDERABAD");
clrscr();
cl«=strcnp(al,a2);
c2«stranp(a3,a4);
c3=strcmp(a5,a6);
printf ( “ nAscii Difference between two stringsn");
printf ("Difference between (% s % s)= % d n"^ ilfa2,cl);
printf ("Difference between (% s %s)=%dn",a3,a4j:2);
printf ("Difference between (% s % s)=% dn",a5,a6^3);
getcheO;
I
OUTPUT:
Difference between (NAGPUR NAGPUR)= 0
Difference between (PANDHARPUR KOLHAPUR)= 5
Difference between (AURANGABAD HYDERABAD)=-7
Explanation In the above program five character arrays are declared. Using strcpy () function
names of cities are copied to arrays. Using strcmp () function strings are compared. The strcnp 0
returns the ASCI I difference of two strings. The ASCII values of the first characters of two strings are
taken into account for comparison. Rest of the elements are not considered for ASCII difference. The
ASCII value of the first character of first string is subtracted from ASCII value of the first character of
a second string. The Table 8.1 given below illustrates the calculation.