Page 41 - DCAP404 _Object Oriented Programming
P. 41
Object-oriented Programming
Notes The statement can be either simple or compound. In practice, it is often a compound statement,
which may include other control statements. For example, consider the following program:
#include <iostream.h>
int main()
{
char chr;
cout << “Please enter a character:” ;
cin >> chr;
if (chr == ‘X’)
cout << end1 << “The character is X”;
else
cout << end1 << “The character is not X”;
return 0;
}
Note that the operator, ==, used for comparing two data items, is different from the assignment
operator, =,
In an if-else block of statements, the condition is evaluated first. If the condition is true (value is
non-zero), the statements in the immediate block are executed, if the condition is false (value is
zero) the statements in the else block are executed.
In the above example, if the input character is ‘X’, the message displayed is, ‘the character is X’
otherwise, the message, ‘The character is not X’ 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 as an
assignment. For example, if the statement, if (chr == ‘X’), was written as, if (chr = ‘X’), then, chr
would have been assigned the value, ‘X’ and the condition would be evaluated as true. Thus, the
message, the character is ‘X’ would have been displayed, regardless of the input.
This program could also have been written as given below:
#include <iostream.h>
int main()
{
char chr;
cout << “Please enter a character: “;
cin >> chr;
if (chr != ‘X’)
cout << end1 << “The character is no X”;
else
cout << end1 << “The character is X”;
return 0;
}
34 LOVELY PROFESSIONAL UNIVERSITY