0% found this document useful (0 votes)
3 views15 pages

Decision Control in C Programming

Chapter 3 discusses decision control instructions in programming, detailing three methods for making decisions: if-else statements, conditional operators, and switch statements. It emphasizes the importance of using relational operators for conditions and the structure of if-else blocks, including nesting. The chapter also includes exercises to practice these concepts through programming tasks.

Uploaded by

1001 Gaming
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views15 pages

Decision Control in C Programming

Chapter 3 discusses decision control instructions in programming, detailing three methods for making decisions: if-else statements, conditional operators, and switch statements. It emphasizes the importance of using relational operators for conditions and the structure of if-else blocks, including nesting. The chapter also includes exercises to practice these concepts through programming tasks.

Uploaded by

1001 Gaming
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Chapter 3: Decision Control Instruction 51

and this ;
}
}
else
do this ;

(f) if ( condition )
do this ;
else
{
if ( condition )
do this ;
else
{
do this ;
and this ;
}
}

Summary
(a) There are three ways for taking decisions in a program. First way is
to use the if-else statement, second way is to use the conditional
operators and third way is to use the switch statement.
(b) The condition associated with an if statement is built using
relational operators <, >, <=, >=, == and !=.
(c) The default scope of if statement is only the next statement. So, to
execute more than one statement they must be written in a pair of
braces.
(d) An ‘if block’ need not always be associated with an ‘else block’.
However, an ‘else block’ must always be associated with an if.
(e) An if-else statement can be nested inside another if-else statement.

Exercise
[A] What will be the output of the following programs:
(a) # include <stdio.h>
int main( )
{
52 Let Us C

int a = 300, b, c ;
if ( a >= 400 )
b = 300 ;
c = 200 ;
printf ( "%d %d\n", b, c ) ;
return 0 ;
}
(b) # include <stdio.h>
int main( )
{
int a = 500, b, c ;
if ( a >= 400 )
b = 300 ;
c = 200 ;
printf ( "%d %d\n", b, c ) ;
return 0 ;
}
(c) # include <stdio.h>
int main( )
{
int x = 10, y = 20 ;
if ( x == y ) ;
printf ( "%d %d\n", x, y ) ;
return 0 ;
}
(d) # include <stdio.h>
int main( )
{
int x = 3 ;
float y = 3.0 ;
if ( x == y )
printf ( "x and y are equal\n" ) ;
else
printf ( "x and y are not equal\n" ) ;
return 0 ;
}
(e) # include <stdio.h>
int main( )
{
Chapter 3: Decision Control Instruction 53
int x = 3, y, z ;
y = x = 10 ;
z = x < 10 ;
printf ( "x = %d y = %d z = %d\n", x, y, z ) ;
return 0 ;
}
(f) # include <stdio.h>
int main( )
{
int i = 65 ;
char j = ’A’ ;
if ( i == j )
printf ( "C is WOW\n" ) ;
else
printf ( "C is a headache\n" ) ;
return 0 ;
}
[B] Point out the errors, if any, in the following programs:
(a) # include <stdio.h>
int main( )
{
float a = 12.25, b = 12.52 ;
if ( a = b )
printf ( "a and b are equal\n" ) ;
return 0 ;
}
(b) # include <stdio.h>
int main( )
{
int j = 10, k = 12 ;
if ( k >= j )
{
{
k=j;
j=k;
}
}
return 0 ;
}
54 Let Us C

(c) # include <stdio.h>


int main( )
{
if ( 'X' < 'x' )
printf ( "ascii value of X is smaller than that of x\n" ) ;
}
(d) # include <stdio.h>
int main( )
{
int x = 10 ;
if ( x >= 2 ) then
printf ( "%d\n", x ) ;
return 0 ;
}
(e) # include <stdio.h>
int main( )
{
int x = 10, y = 15 ;
if ( x % 2 = y % 3 )
printf ( "Carpathians\n" ) ;
}
(f) # include <stdio.h>
int main( )
{
int x = 30, y = 40 ;
if ( x == y )
printf ( "x is equal to y\n" ) ;
elseif ( x > y )
printf ( "x is greater than y\n" ) ;
elseif ( x < y )
printf ( "x is less than y\n" ) ;
return 0 ;
}
(g) # include <stdio.h>
int main( )
{
int a, b ;
scanf ( "%d %d", a, b ) ;
if ( a > b ) ;
Chapter 3: Decision Control Instruction 55
printf ( "This is a game\n" ) ;
else
printf ( "You have to play it\n" ) ;
return 0 ;
}
[C] Attempt the following:

(a) If cost price and selling price of an item are input through the
keyboard, write a program to determine whether the seller has
made profit or incurred loss. Also determine how much profit he
made or loss he incurred.
(b) Any integer is input through the keyboard. Write a program to find
out whether it is an odd number or even number.
(c) Any year is input through the keyboard. Write a program to
determine whether the year is a leap year or not.
(Hint: Use the % (modulus) operator)
(d) According to the Gregorian calendar, it was Monday on the date
01/01/01. If any year is input through the keyboard write a program
to find out what is the day on 1st January of this year.
(e) A five-digit number is entered through the keyboard. Write a
program to obtain the reversed number and to determine whether
the original and reversed numbers are equal or not.
(f) If the ages of Ram, Shyam and Ajay are input through the keyboard,
write a program to determine the youngest of the three.
(g) Write a program to check whether a triangle is valid or not, when
the three angles of the triangle are entered through the keyboard.
A triangle is valid if the sum of all the three angles is equal to 180
degrees.
(h) Write a program to find the absolute value of a number entered
through the keyboard.
(i) Given the length and breadth of a rectangle, write a program to find
whether the area of the rectangle is greater than its perimeter. For
example, the area of the rectangle with length = 5 and breadth = 4
is greater than its perimeter.
(j) Given three points (x1, y1), (x2, y2) and (x3, y3), write a program
to check if all the three points fall on one straight line.
(k) Given the coordinates (x, y) of center of a circle and its radius, write
a program that will determine whether a point lies inside the circle,
56 Let Us C

on the circle or outside the circle. (Hint: Use sqrt( ) and pow( )
functions)
(l) Given a point (x, y), write a program to find out if it lies on the X-
axis, Y-axis or on the origin.
4 More Complex
Decision Making
 Use of Logical Operators
The else if Clause
The ! Operator
Hierarchy of Operators Revisited
 A Word of Caution
 The Conditional Operators
 Summary
 Exercise

57
58 Let Us C

W e all face situations in real-life where the action that we carry out
is based on multiple conditions. For example, I will join a
company if the company allocates a metro location, gives me a good pay
package and permits a joining period of 4 weeks. In programming too
action performed may be based on result of multiple conditions. Such
programming situations can be handled elegantly using Logical
Operators. This chapter also explores the use of another type of
operators called Conditional Operators.

Use of Logical Operators


C allows usage of three logical operators, namely, &&, || and !. These
are to be read as ‘AND’, ‘OR’ and ‘NOT’, respectively.
There are several things to note about these logical operators. Most
obviously, two of them are composed of double symbols: || and &&.
Don’t use the single symbol | and &. These single symbols also have a
meaning. They are bitwise operators, which we would examine in
Chapter 21.
The first two operators, && and ||, allow two or more conditions to be
combined in an if statement. Let us see how they are used in a program.
Consider the following example:
Example 4.1: The marks obtained by a student in 5 different subjects are
input through the keyboard. The student gets a division as per the
following rules:
Percentage above or equal to 60 - First division
Percentage between 50 and 59 - Second division
Percentage between 40 and 49 - Third division
Percentage less than 40 - Fail
Write a program to calculate the division obtained by the student.
There are two ways in which we can write a program for this example.
These methods are given below.

/* Method – I */
# include <stdio.h>
int main( )
{
int m1, m2, m3, m4, m5, per ;

printf ( "Enter marks in five subjects " ) ;


Chapter 4: More Complex Decision Making 59
scanf ( "%d %d %d %d %d", &m1, &m2, &m3, &m4, &m5 ) ;
per = ( m1 + m2 + m3 + m4 + m5 ) * 100 / 500 ;

if ( per >= 60 )
printf ( "First division\n" ) ;
else
{
if ( per >= 50 )
printf ( "Second division\n" ) ;
else
{
if ( per >= 40 )
printf ( "Third division\n" ) ;
else
printf ( "Fail\n" ) ;
}
}

return 0 ;
}

This is a straight-forward program. Observe that the program uses


nested if-elses. Though the program works fine, it has three
disadvantages:
(a) As the number of conditions go on increasing the level of
indentation also goes on increasing. As a result, the whole program
creeps to the right. So much so that entire program is not visible on
the screen. So if something goes wrong with the program locating
what is wrong where becomes difficult.
(b) Care needs to be exercised to match the corresponding ifs and
elses.
(c) Care needs to be exercised to match the corresponding pair of
braces.

All these three problems can be eliminated by usage of ‘Logical


Operators’. The following program illustrates this:

/* Method – II */
# include <stdio.h>
int main( )
{
60 Let Us C

int m1, m2, m3, m4, m5, per ;

printf ( "Enter marks in five subjects " ) ;


scanf ( "%d %d %d %d %d", &m1, &m2, &m3, &m4, &m5 ) ;

per = ( m1 + m2 + m3 + m4 + m5 ) / 500 * 100 ;

if ( per >= 60 )
printf ( "First division\n" ) ;

if ( ( per >= 50 ) && ( per < 60 ) )


printf ( "Second division\n" ) ;

if ( ( per >= 40 ) && ( per < 50 ) )


printf ( "Third division\n" ) ;

if ( per < 40 )
printf ( "Fail\n" ) ;

return 0 ;
}

As can be seen from the second if statement, the && operator is used to
combine two conditions. ‘Second division’ gets printed if both the
conditions evaluate to true. If one of the conditions evaluate to false
then the whole thing is treated as false.
Two distinct advantages can be cited in favor of this program:
(a) The matching (or do I say mismatching) of the ifs with their
corresponding elses gets avoided, since there are no elses in this
program.
(b) In spite of using several conditions, the program doesn't creep to
the right. In the previous program the statements went on creeping
to the right. This effect becomes more pronounced as the number
of conditions goes on increasing. This would make the task of
matching the ifs with their corresponding elses and matching of
opening and closing braces much more difficult.

There is a negative side to the program too. Even if the first condition
turns out to be true, still all other conditions are checked. This will
Chapter 4: More Complex Decision Making 61
increase the time of execution of the program. This can be avoided using
the else if clause discussed in the next section.

The else if Clause


There is one more way in which we can write program for Example 4.1.
This involves usage of else if blocks as shown below.

/* else if ladder demo */


# include <stdio.h>
int main( )
{
int m1, m2, m3, m4, m5, per ;

per = ( m1+ m2 + m3 + m4+ m5 ) / 500 * 100 ;

if ( per >= 60 )
printf ( "First division\n" ) ;
else if ( per >= 50 )
printf ( "Second division\n" ) ;
else if ( per >= 40 )
printf ( "Third division\n" ) ;
else
printf ( "fail\n" ) ;

return 0 ;
}

You can note that this program reduces the indentation of the
statements. In this case, every else is associated with its previous if. The
last else goes to work only if all the conditions fail. Also, if a condition is
satisfied, other conditions below it are not checked. Even in else if
ladder, the last else is optional.
Note that the else if clause is nothing different. It is just a way of
rearranging the else with the if that follows it. This would be evident if
you look at the following code:

/* code using ifs */


if ( i == 2 )
printf ( "With you…" ) ;
else
{
62 Let Us C

if ( j == 2 )
printf ( "…All the time" ) ;
}

/* code using if - else if - else */


if ( i == 2 )
printf ( "With you…" ) ;
else if ( j == 2 )
printf ( "…All the time " ) ;

Another place where logical operators are useful is when we want to


write programs for complicated logics that ultimately boil down to only
two answers. For example, consider the following example:
Example 4.2: 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 should be insured or not.
Here after checking a complicated set of instructions the final output of
the program would be one of the two—either the driver should be
insured or the driver should not be insured. As mentioned above, since
these are the only two outcomes this problem can be solved using
logical operators. But before we do that, let us write a program that
does not make use of logical operators.

/* Insurance of driver - without using logical operators */


# include <stdio.h>
int main( )
{
char sex, ms ;
int age ;

printf ( "Enter age, sex, marital status " ) ;


scanf ( "%d %c %c", &age, &sex, &ms ) ;

if ( ms == 'M' )
printf ( "Driver should be insured\n" ) ;
Chapter 4: More Complex Decision Making 63
else
{
if ( sex == 'M' )
{
if ( age > 30 )
printf ( "Driver should be insured\n" ) ;
else
printf ( "Driver should not be insured\n" ) ;
}
else
{
if ( age > 25 )
printf ( "Driver should be insured\n" ) ;
else
printf ( "Driver should not be insured\n" ) ;
}
}

return 0 ;
}

From the program it is evident that we are required to match several ifs
and elses and several pairs of braces. In a more real-life situation there
would be more conditions to check leading to the program creeping to
the right. Let us now see how to avoid these problems by using logical
operators.
As mentioned above, in this example, we expect the answer to be either
‘Driver should be insured’ or ‘Driver should not be insured’. If we list
down all those cases in which the driver is insured, then they would be:
(a) Driver is married.
(b) Driver is an unmarried male above 30 years of age.
(c) Driver is an unmarried female above 25 years of age.
Since all these cases lead to the driver being insured, they can be
combined together using && and || as shown in the program below.

/* Insurance of driver - using logical operators */


# include <stdio.h>
int main( )
{
char sex, ms ;
64 Let Us C

int age ;

printf ( "Enter age, sex, marital status " ) ;


scanf ( "%d %c %c", &age, &sex, &ms ) ;

if ( ( ms == 'M') || ( ms == 'U' && sex == 'M' && age > 30 ) ||


( ms == 'U' && sex == 'F' && age > 25 ) )
printf ( "Driver should be insured\n" ) ;
else
printf ( "Driver should not be insured\n" ) ;

return 0 ;
}

In this program, it is important to note that:


 The driver will be insured only if one of the conditions enclosed in
parentheses evaluates to true.
 For the second pair of parentheses to evaluate to true, each
condition in the parentheses separated by && must evaluate to
true.
 Even if one of the conditions in the second parentheses evaluates to
false, then the whole of the second parentheses evaluates to false.
 The last two of the above arguments apply to third pair of
parentheses as well.
Thus, we can conclude that the && and || are useful in the following
programming situations:
(a) When it is to be checked in which range does a value fall.
(b) When after testing several conditions, the outcome is only one of
the two answers. (This problem is often called yes/no problem).
In some programming situations we may combine the usage of if— else
if—else and logical operators. This is demonstrated in the following
program.
Example 4.3: Write a program to calculate the salary as per the
following table:

You might also like