Monday, December 14, 2009

4.9 THE comma OPERATOR

We now introduce the comma (,) operator which is used primarily in conjunction with the for statement.This operator permits two different expressions to appear in situations where only one expression would ordinarily be used.For example it is possible to write

for (expression1a,expression1b;expression2;expression3) statement

where expression1a and expression1b are  the two expressions,separated by the comma operator,where only one expression (expression1) would normally appear.

let us write a C program which uses the comma (,) operator to search for a palindrome

/*search for a palindrome*/


#include stdio.h
#include ctype.h

#define EOL '\n'
#define TRUE 1
#define FALSE 0


main()
{
char letter[80];
int tag, count, countback, flag, loop=TRUE;


/*main loop*/


while (loop) {
flag=TRUE;

/*read the text*/


printf("Please enter a word, phrase, or sentence below:'\n'");
for (count=0; (letter[count]=getchar())!= EOL; ++count)
;
if ((toupper(letter[0])= ='E' ) && (toupper(letter[1])= ='N' ) && (toupper(letter[3])= ='D' ))
break;
tag = count - 1;


/*carry out the search*/


for((count=0, countback=tag); count <=tag/2;(++count, --countback)) {
if (letter[count] != letter[countback]) {
flag = FALSE;
break;

}

}
/*display message*/


for (count=0;count <=tag; ++count)
putchar(letter[count]);
if (flag) printf("is a palindrome");
else printf("is not a palindrome");
}

}

A typical interactive session is shown below, indicating the type of output that is generated when the program is executed.As usual the user's response is underlined.

Please enter a word, phrase, or sentence below:

TOOT

TOOT  is a palindrome


Please enter a word, phrase, or sentence below:
FALSE
FALSE is not a palindrome

No comments:

Post a Comment