The conditional branching statements help to jump from one part of the program to another depending on whether a particular condition is satisfied or not.
CONDITIONAL BRANCHING STATEMENTS
The conditional branching statements help to jump from one part of the program to another depending on whether a particular condition is satisfied or not. These decision control statements include:
• if statement
• if-else statement
• if-else-if statement
• switch statement
The if statement is the simplest form of decision control statements that is frequently used in decision making. The general form of a simple if statement is shown in Figure 3.2.
The if block may include one statement or n statements enclosed within curly brackets. First the test expression is evaluated. If the test expression is true, the statement of if block (statement 1 to n) are executed otherwise these statements will be skipped and the execution will jump to statement x.
The statement in an if block is any valid C language statement and the test expression is any valid C language expression that may include logical operators. Note that there is no semicolon after the test expression. This is because the condition and statement should be put together as a single statement
Programming Tip: Properly indent the statements that are dependent on the previous statements.
#include <stdio.h>
int main()
{
int x=10; // Initialize the value of x
if ( x>0) // Test the value of x
x++; // Increment x if it is > 0
printf("\n x = %d", x); // Print the value of x
return 0;
}
Output
x = 11
In the above code, we take a variable x and initialize it to 10. In the test expression we check if the value of x is greater than 0. If the test expression evaluates to true then the value of x is incremented and is printed on the screen. The output of this program is
x = 11
Observe that the printf statement will be executed even if the test expression is false.
1. Write a program to determine whether a person is eligible to vote.
#include <stdio.h>
#include <conio.h>
int main()
{
int age;
printf("\n Enter the age: ");
scanf("%d", &age);
if (age >= 18)
printf("\n You are eligible to vote");
getch();
return 0;
}
Output
Enter the age: 28
You are eligible to vote
Note
In case the statement block contains only one statement, putting curly brackets becomes optional. If there is more than 1 statement in the statement block, putting curly brackets becomes mandatory.
2. Write a program to determine the character entered by the user.
#include <stdio.h>
#include <ctype.h>
#include <conio.h>
int main()
char ch;
printf("\n Press any key: ");
scanf("%c", &ch);
if (isalpha (ch) >0)
printf("\n The user has entered a character");
if (isdigit (ch) >0)
printf("\n The user has entered a digit");
if (isprint (ch) >0)
printf("\n The user has entered a printable character");
if (ispunct (ch) >0)
printf("\n The user has entered a punctuation mark");
if (isspace (ch)>0)
printf("\n The user has entered a white space character");
getch();
return 0;
}
Output
Press any key: 3
The user has entered a digit
Now let us write a program to detect errors during data input. But before doing this we must remember that when the scanf() function completes its action, it returns the number of items that are successfully read. We can use this returned value to test if any error has occurred during data input. For example, consider the following function:
scanf("%d %f %c", &a, &b, &c);
If the user enters:
1 1.2 A
then the scanf () function will return 3, since three values have been successfully read. But had the user entered,
1 abc A
then the scanf() function will immediately terminate when it encounters abc as it was expecting a floating point value and print an error message. So after understanding this concept, let us write a program code to detect an error in data input.
#include <stdio.h>
main ()
{
int num;
char ch;
printf("\n Enter an int and a char value: ");
// Check the return value of scanf()
if (scanf("%d %c", &num, &ch) ==2)
printf("\n Data read successfully");
else
printf("\n Error in data input") ;
}
Output
Enter an int and a char value: 2 A
Data read successfully
We have studied that the if statement plays a vital role in conditional branching. Its usage is very simple, the test expression is evaluated, if the result is true, the statement(s) followed by the expression is executed else if the expression is false, the statement is skipped by the compiler.
But what if you want a separate set of statements to be executed if the expression returns a zero value? In such cases we use an if-else statement rather than using simple if statement. The general form of a simple if-else statement is shown in Figure 3.3.
Programming Tip: Align the matching if-else clauses vertically.
In the syntax shown, we have written statement block. A statement block may include one or more statements. According to the if-else construct, first the test expression is evaluated. If the expression is true, statement block 1 is executed and statement block 2 is skipped. Otherwise, if the expression is false, statement block 2 is executed and statement block 1 is ignored. Now in any case after the statement block 1 or 2 gets executed the control will pass to statement x. Therefore, statement x is executed in every case.
3. Write a program to find whether the given number is even or odd.
#include <stdio.h>
#include <conio.h>
int main()
{
int num;
clrscr();
printf("\n Enter any number: ");
scanf("%d", &num);
if (num%2 = = 0)
printf("\n %d is an even number", num);
else
printf("\n %d is an odd number", num);
return 0;
}
Output
Enter any number: 11
11 is an odd number
4. Write a program to enter any character. If the entered character is in lower case then convert it into upper case and if it is a lower case character then convert it into upper case.
#include <stdio.h>
#include <conio.h>
int main()
{
char ch;
clrscr();
printf("\n Enter any character: ");
x transcanf("%c", &ch);
if (ch >='A' && ch<='Z')
printf("\n The entered character was in upper case. In lower case it is: %c", (ch+32));
else
printf("\n The entered character was in lower case. In upper case it is: %c", (ch-32));
return 0;
}
Output
Enter any character: a
The entered character was in lower case. In upper case it is: A
5. Write a program to enter a character and then determine whether it is a vowel or not.
#include <stdio.h>
#include <conio.h>
int main()
{
char ch;
clrscr();
printf("\n Enter any character: ");
scanf("%c", &ch);
if (ch = 'a' || ch == 'e' || ch== 'i' || ch== 'o' || ch== 'u' || ch== 'A' || ch== 'E' || ch=='I' || ch=='O' || ch== 'U')
printf("\n %c is a VOWEL", ch);
else
printf("\n %c is not a vowel");
getch();
return 0;
}
Output
Enter any character: v
v is not a vowel
6. Write a program to find whether a given year is a leap year or not.
#include <stdio.h>
#include <conio.h>
int main()
{
int year;
clrscr();
printf("\n Enter any year: ");
scanf("%d", &year);
if ((year %4 = = 0) && ((year%100 ! = 0) || (year%400 == 0)))
printf("\n Leap Year");
else
printf("\n Not A Leap Year");
return 0;
}
Output
Enter any year: 1996
Leap Year
Pitfall A very common pitfall while using if statements is to use assignment operator (=) instead of comparison operator (= =). For example, consider the statement
if (a = 10)
printf("%d", a);
Here, the statement does not test whether a is equal to 10 or not. Rather the value 10 is assigned to a and then the value is returned to the if construct for testing. Since the value of a is non-zero, the if construct returns a 1.
Programming Tip: Do not use floating point numbers for checking for equality in the test expression.
The compiler cannot detect such kinds of errors and thus the programmer should carefully use the operators. The program code given below shows the outcome of mishandling the assignment and the comparison operators.
#include <stdio.h>
main()
{
int x 2, y = 3;
if (x = y)
printf("\n_EQUAL");
else
printf("\n NOT EQUAL") ;
}
Output
EQUAL
#include <stdio.h>
main()
{
int x 2, y = 3;
if (x = = y)
printf("\n_EQUAL"); Yis
else
printf("\n NOT EQUAL") ;
}
Output
NOT EQUAL
C language supports if-else-if statements to test additional conditions apart from the initial test expression.
The if-else-if construct works in the same way as a normal if statement. If-else-if construct is also known as nested if construct. Its construct is given in Figure 3.4.
It is not necessary that every if statement should have an else block as C supports simple if statements. After the first test expression or the first if branch, the programmer can have as many else-if branches as he wants depending on the expressions that have to be tested. For example, the following code tests whether a number entered by the user is negative, positive, or equal to zero.
Programming Tip: Braces must be placed on separate lines so that the block of statements can be easily identified.
7. Write a program to demonstrate the use of nested if structure.
#include <stdio.h>
int main()
{
int x, y;
printf("\n Enter two numbers: ");
scanf("%d %d", &x, &y);
if (x = = y)
printf("\n The two numbers are equal");
else if (x > y)
printf("\n %d is greater than %d", x, y);
else
printf("\n %d is smaller than %d", x, y);
return 0;
}
Output
Enter two numbers: 12 23
12 is smaller than 23
8. Write a program to test whether a number entered is positive, negative or equal to zero.
#include <stdio.h>
int main()
{
Programming Tip: Keep the logical expressions simple and short. For this, you may use nested if statements.
int num;
printf("\n Enter any number: ");
scanf("%d", &num);
if (num= =0)
printf("\n The number is equal to zero");
else if (num>0)
printf("\n The number is positive");
else
printf("\n The number is negative");
return 0;
}
Output
Enter any number: 0
The number is equal to zero
9. A company decides to give bonus to all its employees on Diwali. A 5% bonus on salary is given to the male workers and 10% bonus on salary to the female workers. Write a program to enter the salary and sex of the employee. If the salary of the employee is less than Rs 10,000 then the employee gets an extra 2% bonus on salary. Calculate the bonus that has to be given to the employee and display the salary that the employee will get.
#include <stdio.h>
#include <conio.h>
int main()
{
char ch;
float sal, bonus, amt_to_be_paid;
printf("\n Enter the sex of the employee (m or f): ");
scanf("%c", &ch);
printf("\n Enter the salary of the employee: ");
scanf("%f", &sal);
if (ch = = 'm')
bonus = 0.05 sal;
else
bonus = 0.10 * sal;
if (sal < 10000)
bonus += 0.20 * sal;
amt_to_be_paid = sal + bonus;
printf("\n Salary = %f", sal);
printf("\n Bonus = %f", bonus);
printf("\n********************") ;
printf("\n Amount to be paid: %f", amt_to_be_paid);
getch();
return 0;
}
Output
Enter the sex of the employee (m or f): f
Enter the salary of the employee: 12000
Salary = 12000
Bonus = 1200
****************************
Amount to be paid: 13200
In the program to test whether a number is positive or negative, if the first test expression evaluates to a true value then rest of the statements in the code will be ignored and after executing the printf statement which displays "The number is equal to zero", the control will jump to return 0 statement. Consider the following code which shows usage of the if-else-if statement.
Note
The AND operand (&&) is used to form a compound relation expression. In C, the following expression is invalid.
if (60 ≤ marks ≤ 75)
The correct way to write is as follows:
if ((marks ≥ 60) && (marks ≤ 75))
10. Write a program to display the examination result.
#include <stdio.h>
int main()
{
int marks;
printf("\n Enter the marks obtained: ");
scanf("%d", &marks);
if (marks >= 75)
printf("\n DISTINCTION");
Programming Tip: Try to use the most probable condition first so that unnecessary tests are eliminated and the efficiency of the program is improved.
else if ( marks >= 60 && marks <75)
printf("\n FIRST DIVISION");
else if ( marks >= 50 && marks<60)
printf("\n SECOND DIVISION");
else if ( marks >= 40 && marks < 50)
printf("\n THIRD DIVISION");
else
printf("\n FAIL");
return 0;
}
Output
Enter the marks obtained: 55
SECOND DIVISION
11. Write a program to calculate tax, given the following conditions:
• if income is less than 1,50, 000 then no tax
• if taxable income is in the range 1,50,001-300,000 then charge 10% tax
• if taxable income is in the range 3,00,001-500,000 then charge 20% tax
• if taxable income is above 5,00,001 then charge 30% tax
#include <stdio.h>
#include <conio.h>
#define MIN1 150001
#define MAX1 300000
#define RATE1 0.10
#define MIN2 300001
#define MAX2 500000
#define RATE2 0.20
#define MIN3 500001
#define RATE3 0.30
int main()
{
double income, taxable_income, tax;
clrscr();
printf("\n Enter the income: ");
scanf("%1f", &income);
taxable_income = income - 150000;
if (taxable_income <= 0)
printf("\n NO TAX");
else if (taxable_income >= MIN1 && taxable income < MAX1)
tax = (taxable_income - MIN1) * RATE1;
else if (taxable_income >= MIN2 && taxable income < MAX2)
tax = (taxable_income - MIN2) * RATE2;
else
tax = (taxable_income - MIN3) * RATE3;
rintf("\n TAX = %1f", tax);
getch();
return 0;
}
Output
Enter the income: 900000
TAX = 74999.70
12. Write a program to find the greatest of three numbers.
#include <stdio.h>
#include <conio.h>
int main()
{
int numl, num2, num3, big=0;
clrscr();
printf("\n Enter the first number: ");
scanf("%d", &num1);
printf("\n Enter the second number: ");
scanf("%d", &num2);
printf("\n Enter the third number: ");
scanf("%d", &num3);
if (numl>num2)
{
if (num1>num3)
printf("\n %d is greater than %d and %d", numl, num2, num3);
else
printf("\n %d is greater than %d and %d", num3, num1, num2);
}
else if (num2>num3)
printf("\n %d is greater than %d and %d", num2, num1, num3);
else
Programming Tip: It is always recommended to indent the statements in the block by at least three spaces to the right of the braces.
printf("\n %d is greater than %d and %d", num3,num1,num2);
return 0;
}
Output
Enter the first number: 12
Enter the second number: 23
Enter the third number: 9
23 is greater than 12 and 9
13. Write a program to input three numbers and then find the largest of them using && operator.
#include <stdio.h>
#include <conio.h>
int main()
{
int numl, num2, num3;
clrscr();
printf("\n Enter the first number: ");
scanf("%d", &num1);
printf("\n Enter the second number: ");
scanf("%d", &num2);
ared printf("\n Enter the third number: ");
scanf("%d", &num3);
if (num1>num2 && num1>num3)
printf("\n %d is the largest number", num1);
if (num2>num1 && num2>num3)
printf("\n %d is the largest number", num2);
else
printf("\n %d is the largest number", num3);
getch();
return 0;
}
Output
Enter the first number: 12
Enter the second number: 23
Enter the third number: 9
23 is the largest number
14. Write a program to enter the marks of a student in four subjects. Then calculate the total, aggregate, and display the grades obtained by the student.
#include <stdio.h>
#include <conio.h>
int main()
{
int marks1, marks2, marks3, marks4, total = 0; float avg =0.0;
clrscr();
printf("\n Enter the marks in Mathematics: ");
scanf("%d", &marks1);
printf("\n Enter the marks in Science: ");
scanf("%d", &marks2);
printf("\n Enter the marks in Social Science: ");
scanf("%d", &marks3);
printf("\n Enter the marks in Computer Science: Science:”);
scanf("%d", &marks4);
total = marks1 + marks2 + marks3 + marks4;
avg = (float) total/4;
printf("\n TOTAL = %d", total);
printf("\n AGGREGATE = %.2f", avg);
if (avg>= 75)
printf("\n DISTINCTION");
else if (avg>=60 && avg<75)
printf("\n FIRST DIVISION");
else if (avg>=50 && avg<60)
printf("\n SECOND DIVISION");
else if (avg>=40 && avg<50)
printf("\n THIRD DIVISION");
else
printf("\n FAIL");
return 0;
}
Output
Enter the marks in Mathematics: 90
Enter the marks in Science: 91
Enter the marks in Social Science: 92
Enter the marks in Computer Science: 93
TOTAL 366
AGGREGATE = 91.00
DISTINCTION
15. Write a program to calculate the roots of a quadratic equation.
#include <stdio.h>
#include <math.h>
#include <conio.h>
void main()
{
int a, b, C;
float D, deno, root1, root2;
clrscr();
printf("\n Enter the values of a, b, and c :");
scanf("%d %d %d", &a, &b, &c);
D = (b* b) - (4 a * c) ;
deno 2* a;
if (D > 0)
{
printf("\n REAL ROOTS");
root1 = (-b + sqrt (D)) / deno;
root2 = (-b - sqrt (D)) / deno;
printf("\n ROOT1 %f \t ROOT 2 root1, root2);
else if (D = = 0)
{
printf("\n EQUAL ROOTS");
root1 = -b/deno;
printf("\n ROOT1 = %f\t ROOT 2 = %f", rootl, root1);
}
else
printf("\n IMAGINARY ROOTS");
getch();
}
Output
Enter the values of a, b, and c: 3 4 5
IMAGINARY ROOTS
Let us now summarize the rules for using if, if-else, and if-else-if statements.
Rule 1: The expression must be enclosed in parentheses.
Rule 2: No semicolon is placed after the if /if-else/ if-else-if statement. Semicolon is placed only at the end of statements in the statement block.
Rule 3: A statement block begins and ends with a curly brace. No semicolon is placed after the opening/closing braces.
Dangling Else Problem
With nesting of if-else statements, we often encounter a problem known as dangling else problem. This problem is created when there is no matching else for every if statement. In such cases, C always pair an else statement to the most recent unpaired if statement in the current block. Consider the following code which shows such a scenario.
Programming Tip: While forming the conditional expression, try to use positive statements rather than using compound negative statements.
if (a > b)
if (a > c)
else
printf("\n a is greater than b and c");
else
printf("\n a is not greater than b and c");
The problem is that both the outer if statement and the inner if statement might conceivably own the else clause. The C solution to pair the if-construct with the nearest if may not always be correct. So the programmer must always see that every if statement is paired with an appropriate else statement.
Comparing Floating Point Numbers
Never test floating point numbers for exact equality. This is because floating point numbers are just approximations, so it is always better to test floating point numbers for 'approximately equal' rather than testing for exactly equal.
We can test for approximate equality by subtracting the two floating point numbers (that are to be tested) and comparing their absolute value of the difference against a very small number, epsilon. For example, consider the code given below which compares two floating point numbers. Note that epsilon is chosen by the programmer to be small enough so that the two numbers can be considered equal.
#include <stdio.h>
#include <math.h>
#define EPSILON 1.0e-5
int main()
{
double num1 = 10.0, num2 = 9.5;
double res1, res2;
res1 = num2/num1 * numl;
res2 = num2;
/* fabs() is a C library function that returns the floating point absolute value */
if (fabs (res2 - res1) < EPSILON)
printf("EQUAL");
else
printf("NOT EQUAL");
return 0;
}
Also note that adding a very small floating point value to a very large floating point value or subtracting floating point numbers of widely differing magnitudes may not have any effect. This is because adding/subtracting two floating point numbers that differ in magnitude by more than the precision of the data type used will not affect the larger number.
A switch case statement is a multi-way decision statement that is a simplified version of an if-else block that evaluates only one variable. The general form of a switch statement is shown in Figure 3.5.
Programming Tip: It is always recommended to use default label in a switch statement.
Table 3.1 compares general form of a switch statement with that of an if-else statement.
Here, statement blocks refer to statement lists that may contain zero or more statements. These statements in the block are not enclosed within opening and closing braces.
The power of nested if-else statements lies in the fact that it can evaluate more than one expression in a sin- gle logical structure. Switch statements are mostly used in two situations:
• When there is only one variable to evaluate in the expression
• When many conditions are being tested for
When there are many conditions to test, using the if and else-if construct becomes a bit complicated and confusing. Therefore, switch case statements are often used as an alternative to long if statements that compare a variable to several integral values (integral values are those values that can be expressed as an integer, such as the value of a char). Switch statements are also used to handle the input given by the user.
We have already seen the syntax of the switch statement. The switch case statement compares the value of the variable given in the switch statement with the value of each case statement that follows. When the value of the switch and the case statement matches, the statement block of that particular case is executed.
Did you notice the keyword default in the syntax of the switch case statement? Default is also a case that is executed when the value of the variable does not match with any of the values of the case statement, i.e., the default case is executed when no match is found between the values of switch and case statements and thus there are no statements to be executed. Although the default case is optional, it is always recommended to include it as it handles any unexpected cases.
In the syntax of the switch case statement, we have used another keyword break. The break statement must be used at the end of each case because if it were not used, then the case that matched and all the following cases will be executed.
Programming Tip: C supports decision control statements that can alter the flow of a sequence of instructions. A switch-case statement is a multi-way decision statement that is a simplified version of an if-else block that evaluates only one variable.
For example, if the value of switch statement matched with that of case 2, then all the statements in case 2 as well as rest of the cases including default will be executed. The break statement tells the compiler to jump out of the switch case statement and execute the statement following the switch case construct. Thus, the keyword break is used to break out of the case statements. It indicates the end of a case and prevents the program from falling through and executing the code in all the rest of the case statements.
Consider the following example of switch statement.
char grade = 'C';
switch (grade)
{
case '0':
printf("\n Outstanding");
break;
case 'A':
printf("\n Excellent");
break;
case 'B':
printf("\n Good");
break;
case 'C':
printf("\n Fair");
break;
case 'F':
printf("\n Fail");
break;
default:
printf("\n Invalid Grade");
break;
}
Output
Fair
16. Write a program to demonstrate the use of switch statement without a break.
#include <stdio.h>
int main()
{
int option = 1;
switch (option)
{
case 1: printf("\n In case 1");
case 2: printf("\n In case 2");
default: printf("\n In case default");
}
return 0;
}
Output
In case 1
In case 2
In case default
Had the value of option been 2, then the output would have been
In case 2
In case default
And if option was equal to 3 or any other value then only the default case would have been executed, thereby printing
In case default
To summarize the switch case construct, let us go through the following rules:
Programming Tip: Keep the logical expressions simple and short. For this, you may use nested if statements.
Programming Tip: Default is also a case that is executed when the value of the variable does not match with any of the values of case statements.
• The control expression that follows the keyword switch must be of integral type (i.e., either be an integer or any value that can be converted to an integer).
• Each case label should be followed with a constant or a constant expression.
• Every case label must evaluate to a unique constant expression value.
• Case labels must end with a colon.
• Two case labels may have the same set of actions associated with them.
• The default label is optional and is executed only when the value of the expression does not match with any labelled constant expression. It is recommended to have a default case in every switch case statement.
• The default label can be placed anywhere in the switch statement. But the most appropriate position of default case is at the end of the switch case statement.
• There can be only one default label in a switch statement.
• C permits nested switch statements, i.e., a switch statement within another switch statement.
17. Write a program to determine whether an entered character is a vowel or not.
#include <stdio.h>
int main()
{
char ch;
printf("\n Enter any character: ");
scanf("%c", &ch);
switch (ch)
{
case 'A':
case 'a':
printf("\n % c is VOWEL", ch);
break;
case 'E':
case 'e':
printf("\n % c is VOWEL", ch);
break;
case 'I':
case 'i':
printf("\n % c is VOWEL", ch);
break;
case 'O':
case 'o':
printf("\n c is VOWEL", ch);
break;
case 'U':
case 'u':
printf("\n % c is VOWEL", ch);
break;
default: printf("%c is not a vowel", ch);
}
return 0;
}
Output
Enter any character: E
E is a VOWEL
Note that there is no break statement after case A, so if the character 'A' is entered, then the control will execute the statements given in case 'a'.
18. Write a program to enter a number from 1-7 and be display the corresponding day of the week using to switch case statement.
#include <stdio.h>
#include <conio.h>
int main()
{
int day;
clrscr();
printf("\n Enter any number from 1 to 7: ");
scanf("%d", &day) ;
switch (day)
{
case 1: printf("\n SUNDAY");
break;
case 2: printf("\n MONDAY");
break;
case 3: printf("\n TUESDAY");
break;
case 4: printf("\n WEDNESDAY");
break;
case 5: printf("\n THURSDAY");
break;
case 6: printf("\n FRIDAY");
break;
case 7: printf("\n SATURDAY");
break;
default: printf("\n Wrong Number");
}
return 0;
}
Output
Enter any number from 1 to 7: 5
THURSDAY
19. Write a program that accepts a number from 1 to 10. Print whether the number is even or odd using a switch case construct.
#include <stdio.h>
void main()
{
int num;
printf("\n Enter any number (1 to 10): ");
scanf("%", &num);
switch (num)
{
case 1:
case 3:
case 5:
case 7:
case 9:
printf("\n ODD");
break;
case 2:
case 4:
case 6:
case 8:
case 10:
printf("\n EVEN");
default:
printf("\n INVALID INPUT");
break;
}
}
OR
#include <stdio.h>
void main()
{
int num, rem;
printf("\n Enter any number (1 to 10): ");
scanf("%", &num);
rem = num%2;
switch (rem)
{
case 0:
printf("\n EVEN");
break;
case 1:
printf("\n ODD");
break;
}
}
Output
Enter any number from 1 to 10: 7
ODD
Advantages of Using a Switch Case Statement
Switch case statement is preferred by programmers due to the following reasons:
• Easy to debug
• Easy to read and understand
• Ease of maintenance as compared with its equivalent if-else statements
• Like if-else statements, switch statements can also be nested
Programming in C: Unit I (c): Decision Control and Looping Statements : Tag: : with Example C Programs - Conditional Branching Statements
Programming in C
CS3251 2nd Semester CSE Dept 2021 | Regulation | 2nd Semester CSE Dept 2021 Regulation