Tuesday 12 February 2013

The If - else statement in C Programming Language



The following function shows the use of the if - else conditional construct:

#include <stdio.h>
main()
{
char chr;
puts("Enter a character");
chr = getchar();
fflush (stdin);
if(chr == 'A')
puts(" The value is A");
else
puts("The value is not A");
}

Note, that the operator ==, used for comparing two data items, is defferent from =, which is the assignment operator.

In the above example, if the input character is A, the message displayed is Character is A, otherwise the message Character is not A is displayed. Also, note that the condition has to be specified within parenthesis.

If, however, the operator = is used instead of the == operator, the statement is executed is executed as an assignment. For example, if the statement if(chr =='A') was written as if(chr = 'A') then chr would have got the value A, and it being non-zero, teh condition would be evaluated as true. Thus, the messasge Character is A would have been printed regardless of the input.

0 comments:

Post a Comment

Powered by Blogger.