Page 44 - DCAP404 _Object Oriented Programming
P. 44
Unit 2: Beginning of OOP Language
printf ( * Area of circle = & f* , area); Notes
}
else
{
scanf ( ‘&f & f“, & length , & width) ;
area = length * width;
printf ( * Area of rectangle = &f ‘, area);
}
The above example shows how an area can be calculated for either of two different geometric
figures. If circle is assigned a nonzero value, however, then the length and width of a rectangle
are read into the computer, the area is calculated and then displayed. In each case, the type of
geometric figure is included in the label that accompanies the value of the area. Here is an
example of three nested if-else statements.
If ( ( time > = 0.) && ( time < 12.) ) printf ( * Good Morning*) ;
else if ( ( time > = 12.) && ( time < 18.) ) printf ( * Good Afternoon *);
else if ( ( time > = 18.) && ( time < 24.)) printf ( * Good Evening *) ;
else printf ( * Time is out of range *);
This example causes a different message to be displayed at various times of the day. Specifically,
the message Good Morning will be displayed if time has a value between 0 and 12; Good
Afternoon will be displayed if time has a value between 12 and 18; and Good Evening will be
displayed if time has a value between 18 and 24. An error message (Time is out of range) will be
displayed if the value of time is less than zero, or greater than or equal to 24.
The following program uses a cascading if-else construct to determine if the input character is a
vowel, else it prints an appropriate message.
# include < iostream.h>
int main ( )
{
char in_chr;
cout << “ Enter a character in lowercase “ < , endl;
cin >> in_chr;
if ( in_chr == ‘e‘)
cout << endl << “ Vowel a” << endl;
else if ( in_chr == ‘e‘)
cout <, endl << “Vowel e” <, endl;
else if ( in_chr == ‘ i )
cout << endl << “ Vowel i “ << endl);
else if ( in_chr == ‘ o ‘ )
cout <, endl << “ Vowel o “ << endl;
else if ( in_chr == ‘u‘)
LOVELY PROFESSIONAL UNIVERSITY 37