/* Method - I */
include
int main()
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) * 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-else s. 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) It is difficult to match the corresponding if s and else s.
(c) It is difficult 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
int main()
{
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;
In the second if statement, the && operator is used to combine two conditions. ‘Second division’ gets printed only if both the conditions evaluate to
true.
All the three disadvantages cited above have been overcome in this program. However, there is a negative side to the program too. Even if the
first condition turns out to be true, all other conditions are still checked. This will 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
Let us now rewrite program for Example 4.1 using else if blocks.
/* else if ladder demo */
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”);
Using if - else if - else reduces the indentation of the statements. Here the last else goes to work only if all 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.
Use of Logical Operators - Yes / No Problem
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—yes or no. The following example illustrates this:
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.
The final outcome of the program would be—either the driver should be insured or the driver should not be insured. So the program can be
conveniently written using logical operators. For this let us first identify those cases in which the driver is insured. They are—Driver is married,
Driver is an unmarried male above 30 years of age, and 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
int main()
char sex, ms;
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 expression in second pair of parentheses to evaluate to true, each condition in the expression separated by && must evaluate to true.
Even if one of the conditions in the second parentheses evaluates to false, then the whole expression evaluates to false.
The last two of the above arguments apply to third pair of parentheses as well.
In some programs 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:
Figure 4.1
Here is the program…
include
int main()
char g;
int yos, qual, sal = 0;
printf (“Enter Gender, Years of Service and Qualifications (0 = G, 1 = PG):”);
scanf (“%c%d%d”, &g, &yos, &qual);
if (g == ’m’ && yos >= 10 && qual == 1)
sal = 15000;
else if ((g == ’m’ && yos >= 10 && qual == 0) ||
(g == ’m’ && yos < 10 && qual == 1))
sal = 10000;
else if (g == ’m’ && yos < 10 && qual == 0)
sal = 7000;
else if (g == ’f’ && yos >= 10 && qual == 1)
sal = 12000;
else if (g == ’f’ && yos >= 10 && qual == 0)
sal = 9000;
else if (g == ’f’ && yos < 10 && qual == 1)
sal = 10000;
else if (g == ’f’ && yos < 10 && qual == 0)
sal = 6000;
printf (“\nSalary of Employee = %d\n”, sal);
return 0;
I hope you can follow the implementation of this program on your own.
The ! Operator
The third logical operator is the NOT operator, written as ! . This operator reverses the result of the expression it operates on. So if the expression
evaluates to true, then applying ! operator to it results into a flase. Vice versa, if the expression evaluates to false, then applying ! to it makes it
true. Here is an example showing use of ! operator.
! (y < 10)
If y is less than 10, the result will be false, since (y < 10) is true.
The NOT operator is often used to reverse the logical value of a single variable, as in the expression
if (! flag)
This is another way of saying:
if (flag == 0)
Figure 4.2 summarizes the working of all the three logical operators.
Figure 4.2
Hierarchy of Operators Revisited
Since we have now added the logical operators to the list of operators we know, it is time to review these operators and their priorities. Figure 4.3
summarizes the operators we have seen so far. The higher the position of an operator is in the table, higher is its priority. (A full-fledged
precedence table of operators is given in Appendix B.)
Figure 4.3
The Conditional Operators
The conditional operators ? and : are sometimes called ternary operators since they take three arguments. In fact, they form a kind of
foreshortened if-then-else. Their general form is,
expression 1 ? expression 2 : expression 3
What this expression says is: “if expression 1 is true, then the value returned will be expression 2 , otherwise the value returned will be expression
3 ”. Let us understand this with the help of a few examples.
(a) int x, y;
scanf (“%d”, &x);
y = (x > 5 ? 3: 4);
This statement will store 3 in y if x is greater than 5, otherwise it will store 4 in y.
(b) char a;
int y;
scanf (“%c”, &a);
y = (a >= 65 && a <= 90 ? 1: 0);
Here 1 would be assigned to y if a >=65 && a <=90 evaluates to true, otherwise 0 would be assigned.
The following points may be noted about the conditional operators:
(a) It's not necessary that the statement after ? or: be only arithmetic statements. This is illustrated in the following examples:
Ex.: int i;
scanf (“%d”, &i);
(i == 1 ? printf (“Amit”) : printf (“All and sundry”));
Ex.: char a = ’z’;
printf (“%c”, (a >= ’a’ ? a : ’!’));
(b) The conditional operators can be nested as shown below.
int big, a, b, c;
big = (a > b ? (a > c ? 3: 4) : (b > c ? 6: 8));
(c) Check out the following conditional expression:
a > b ? g = a : g = b;
This will give you an error ‘Lvalue Required’. The error can be overcome by enclosing the statement in the : part within a pair of parentheses. This
is shown below.
a > b ? g = a : g = b;
In absence of parentheses, the compiler believes that b is being assigned to the result of the expression to the left of second = . Hence it reports
an error.
(d) The limitation of the conditional operators is that after the ? or after the : , only one C statement can occur.
Problem 4.1
A year is entered through the keyboard, write a program to determine whether the year is leap or not. Use the logical operators && and || .
Program
/* Check whether a year is leap or not */
include
int main()
int year;
printf (“\nEnter year:”);
scanf (“%d”, &year);
if (year % 400 == 0 || year % 100 != 0 && year % 4 == 0)
printf (“Leap year\n”);
else
printf (“Not a leap year\n”);
return 0;
Output
Enter year: 1900
Not a leap year
Problem 4.2
If a character is entered through the keyboard, write a program to determine whether the character is a capital letter, a small case letter, a digit or
a special symbol.
The following table shows the range of ASCII values for various characters:
Program
/* Check type of character entered from the keyboard */
include
int main()
char ch;
printf (“\nEnter a character from the keyboard:”);
scanf (“%c”, &ch);
if (ch >= 65 && ch <= 90)
printf (“The character is an uppercase letter\n”);
if (ch >= 97 && ch <= 122)
printf (“The character is a lowercase letter\n”);
if (ch >= 48 && ch <= 57)
printf (“The character is a digit\n”);
if ((ch >= 0 && ch < 48) || (ch > 57 && ch < 65)
|| (ch > 90 && ch < 97) || ch > 122)
printf (“The character is a special symbol\n”);
return 0;
Output
Enter a character from the keyboard: A
The character is an uppercase letter
Problem 4.3
If the three sides of a triangle are entered through the keyboard, write a program to check whether the triangle is valid or not. The triangle is valid
if the sum of two sides is greater than the largest of the three sides.
Program
/* Check whether a triangle is valid or not */
include
int main()
int side1, side2, side3, largeside, sum;
printf (“\nEnter three sides of the triangle:”);
scanf (“%d %d %d”, &side1, &side2, &side3);
if (side1 > side2)
if (side1 > side3)
sum = side2 + side3; largeside = side1;
else
sum = side1 + side2; largeside = side3;
}
else
if (side2 > side3)
sum = side1 + side3; largeside = side2;
else
sum = side1 + side2; largeside = side3;
if (sum > largeside)
printf (“The triangle is a valid triangle\n”);
else
printf (“The triangle is an invalid triangle\n”);
return 0;
Output
Enter three sides of the triangle: 3 4 5
The triangle is a valid triangle
[A] If a = 10, b = 12, c = 0, find the values of the expressions in the following table:
[B] What will be the output of the following programs:
(a) # include
int main()
int i = 4, z = 12;
if (i = 5 || z > 50)
printf (“Dean of students affairs\n”);
else
printf (“Dosa\n”);
return 0;
(b) #include
int main()
int i = 4, j = -1, k = 0, w, x, y, z;
w = i || j || k;
x = i && j && k;
y = i || j && k;
z = i && j || k;
printf (“w = %d x = %d y = %d z = %d\n”, w, x, y, z);
return 0;
(c) # include
int main()
int x = 20, y = 40, z = 45;
if (x > y && x > z)
printf (“biggest = %d\n”, x);
else if (y > x && y > z)
printf (“biggest = %d\n”, y);
else if (z > x && z > y)
printf (“biggest = %d\n”, z); return 0;
(d) # include
int main()
int i = -4, j, num;
j = (num < 0 ? 0: num * num);
printf (“%d\n”, j);
return 0;
}
(e) # include
int main()
int k, num = 30;
k = (num > 5 ? (num <= 10 ? 100: 200): 500);
printf (“%d\n”, num);
return 0;
[C] Point out the errors, if any, in the following programs:
(a) # include
int main()
char spy = ’a’, password = ’z’;
if (spy == ’a’ or password == ’z’)
printf (“All the birds are safe in the nest\n”);
return 0;
(b) # include
int main()
int i = 10, j = 20;
if (i = 5) && if (j = 10)
printf (“Have a nice day\n”);
return 0;
(c) # include
int main()
int x = 10, y = 20;
if (x >= 2 and y <= 50)
printf (“%d\n”, x);
return 0;
(d) # include
int main()
int x = 2;
if (x == 2 && x != 0);
printf (“Hello\n”);
else
printf (“Bye\n”);
return 0;
(e) # include
int main()
int j = 65;
printf (“j >= 65 ? %d: %c\n”, j);
return 0;
(f) # include
int main()
int i = 10, j;
i >= 5 ? j = 10: j = 15;
printf (“%d %d\n”, i, j);
return 0;
(g) # include
int main()
int a = 5, b = 6;
(a == b ? printf (“%d\n”, a));
return 0;
(h) # include
int main()
{
int n = 9;
(n == 9 ? printf (“Correct\n”);: printf (“Wrong\n”););
return 0;
[D] Attempt the following questions:
(a) If the three sides of a triangle are entered through the keyboard, write a program to check whether the triangle is isosceles, equilateral, scalene
or right angled triangle.
(b) In digital world colors are specified in Red-Green-Blue (RGB) format, with values of R, G, B varying on an integer scale from 0 to 255. In print
publishing the colors are mentioned in Cyan-Magenta-Yellow-Black (CMYK) format, with values of C, M, Y, and K varying on a real scale from 0.0
to 1.0. Write a program that converts RGB color to CMYK color as per the following formulae:
Note that if the RGB values are all 0, then the CMY values are all 0 and the K value is 1.
(c) A certain grade of steel is graded according to the following conditions:
(i) Hardness must be greater than 50
(ii) Carbon content must be less than 0.7
(iii) Tensile strength must be greater than 5600
The grades are as follows:
Grade is 10 if all three conditions are met
Grade is 9 if conditions (i) and (ii) are met
Grade is 8 if conditions (ii) and (iii) are met
Grade is 7 if conditions (i) and (iii) are met
Grade is 6 if only one condition is met
Grade is 5 if none of the conditions are met
Write a program, which will require the user to give values of hardness, carbon content and tensile strength of the steel under consideration and
output the grade of the steel.
(d) The Body Mass Index (BMI) is defined as ratio of the weight of a person (in kilograms) to the square of the height (in meters). Write a program
that receives weight and height, calculates the BMI, and reports the BMI category as per the following table:
[E] Attempt the following questions:
(a) Using conditional operators determine:
(1) Whether the character entered through the keyboard is a lower case alphabet or not.
(2) Whether a character entered through the keyboard is a special symbol or not.
(b) Write a program using conditional operators to determine whether a year entered through the keyboard is a leap year or not.
(c) Write a program to find the greatest of the three numbers entered through the keyboard. Use conditional operators.
(d) Write a program to receive value of an angle in degrees and check whether sum of squares of sine and cosine of this angle is equal to 1.
(e) Rewrite the following program using conditional operators.
include
int main()
float sal;
printf (“Enter the salary”);
scanf (“%f”, &sal);
if (sal >= 25000 && sal <= 40000)
printf (“Manager\n”);
else
if (sal >= 15000 && sal < 25000)
printf (“Accountant\n”);
else
printf (“Clerk\n”);
return 0;
More complex decision making can be done using logical operators
Logical operators are &&, || and !
Logical operators are useful in 2 situations:
1) Checking ranges 2) Solving yes/no problem
One more form of decision control instruction is:
Hierarchy:
! * / % + - < > <= >= && || =
Unary operator - needs only 1 operand. Ex. ! sizeof
Binary operator - needs 2 operands. Ex. + == != && || - * / % < > <= >=
sizeof is an operator. It gives number of bytes occupied by an entity
Usage of sizeof operator:
a = sizeof (int)
b = sizeof (num);
! (a <= b) is same as (a > b). ! (a >= b) is same as (a < b)
a = !b does not change value of b
a = !a means, set a to 0 if it is 1 and set it to 1 if it is 0
lvalue required error means something is wrong on LHS of =
Conditional operators ?: are ternary operators. General form: expression1 ? expression2: expression3
?: can have only 1 statement each
?: can be nested
?: always go together.: is not optional
Always parenthesize assignment operation if used with ?:
If you wish to find averages of 100 sets of three numbers, would you actually execute the program 100 times? Obviously not, there has to be a
better way out. This chapter will show you how to accomplish this…
Loops
The while Loop
Tips and Traps
More Operators
Programs
Exercises
KanNotes
The programs that we have developed so far used either a sequential or a decision control instruction. These programs were of limited nature,
because when executed, they always performed the same series of actions, in the same way, exactly once. In programming, we frequently need to
perform an action over and over, often with variations in the details each time. The mechanism which meets this need is the ‘Loop Control
Instruction’, and loops are the subject of this chapter.
Loops
The versatility of computer lies in its ability to perform a set of instructions repeatedly. This involves repeating some portion of the program either a
specified number of times or until a particular condition is satisfied. This repetitive operation is done through a loop control instruction. There are
three ways to repeat a part of a program. They are:
(a) Using a while statement
(b) Using a for statement
(c) Using a do-while statement
Let us begin by understanding the while loop.
The while Loop
The while loop is ideally suited for situations where we wish to repeat some instructions a fixed number of times. For example, we may wish to
calculate simple interest for 3 sets of values of principal, number of years and rate of interest. Here is the program that can achieve this…
/* Calculation of simple interest for 3 sets of p, n and r */
include
int main()
int p, n, count;
float r, si;
count = 1;
while (count <= 3)
printf (“\nEnter values of p, n and r ”);
scanf (“%d %d %f”, &p, &n, &r);