Decision Control Structure
Decision Control Structure
Example 1: While purchasing certain items, a discount of 10% is offered if the quantity purchased is more
than 1000. If quantity and price per item are input through the keyboard, write a program to calculate
the total expenses.
main( )
{
int qty, dis = 0 ;
float rate, tot ;
printf ( "Enter quantity and rate " ) ;
scanf ( "%d %f", &qty, &rate) ;
if ( qty > 1000 )
dis = 10 ;
tot = ( qty * rate ) - ( qty * rate * dis / 100 ) ;
printf ( "Total expenses = Rs. %f", tot ) ;
}
You can also use expression instead of condition in if statement the syntax is as follow:
if ( expression )
statement ;
Here the expression can be any valid expression including a relational expression. We can even use
arithmetic expressions in the if statement. For example all the following if statements are valid.
if ( 3 + 2 % 5 )
printf ( "This works" ) ;
if ( a = 10 )
printf ( "Even this works" ) ;
if ( -5 )
printf ( "Surprisingly even this works" ) ;
Note that: in C a non-zero value is considered to be true, whereas a 0 is considered to be false.
Multiple Statements within if
It may so happen that in a program we want more than one statement to be executed if the
expression following if is satisfied. If such multiple statements are to be executed then they must be
placed within a pair of braces as illustrated in the following example.
Example 2: The current year and the year in which the employee joined the organization are entered
through the keyboard. If the number of years for which the employee has served the organization is
greater than 3 then a bonus of Rs. 2500/- is given to the employee. If the years of service are not greater
than 3, then the program should do nothing.
main( )
{
int bonus, cy, yoj, yr_of_ser ;
printf ( "Enter current year and year of joining " ) ;
scanf ( "%d %d", &cy, &yoj ) ;
yr_of_ser = cy - yoj ;
if ( yr_of_ser > 3 )
{
bonus = 2500 ;
printf ( "Bonus = Rs. %d", bonus ) ;
}}
else
printf ( "How about mother earth !" ) ;
}
}
Note that the second if-else construct is nested in the first else statement. If the condition in the
first if statement is false, then the condition in the second if statement is checked. If it is false as well,
then the final else statement is executed.
Practice Time
Exercise 1: A company insures its drivers in the following cases:
− If the driver is married.
− If the driver is unmarried, male & above 30 years of age.
− If the driver is unmarried, female & above 25 years of age.
In all other cases the driver is not insured. If the marital status, sex and age of the driver are the
inputs, write a program to determine whether the driver is to be insured or not.
Exercise 2: Write a program to calculate the salary as per the following table: