Upload
sam-martin
View
212
Download
0
Embed Size (px)
DESCRIPTION
cp
Citation preview
BITS PilaniPilani Campus
Computer ProgrammingModule-4 (Lecture-2)
Virendra Singh ShekhawatDepartment of Computer Science & Information Systems
BITS PilaniPilani Campus
BITS Pilani, Pilani Campus
Topics to be Covered:
Conditional constructs to handle multiple branches
If—else –if , switch—case
Conditional Statements: Multiple Branches
• Conditional statements may have more than one branches
– Add an extra condition i.e. numbers can be equal, in the problem of finding max and min of two numbers.
BITS Pilani, Pilani Campus
numbers.
• If numbers are not equal then only max and min are valid
• Otherwise it should display “The numbers are equal”
3
Conditional Statements: Multiple Branches
• The program fragment for modified problem is as follows:
int x, y, max, min;
scanf(“%d%d”,&x,&y);
if(x!=y)
BITS Pilani, Pilani Campus
if(x!=y)
if(x>y) { max = x; min = y;}
else {max = y; min = x;}
else printf(“Numbers are equal”);
4
Conditional Statements: Multiple Branches
• Extend the max min problem from two numbers to three numbers i.e. x, y and z Exercise:
Convert it into if-else statements
BITS Pilani, Pilani Campus
5
Conditional Statements: Multiple Branches
Consider the problem to print number of days in a given
month
Solution: Using if—else – if if(month==4||month==6||month==9||month==11)
printf(“Month has 30 days”);
BITS Pilani, Pilani Campus
printf(“Month has 30 days”);else if (month == 1||month == 3||month == 5||month == 7||
month == 8||month == 10||month == 12)printf(“Month has 31 days”);
else if (month == 2)
printf(“Month has 28 or 29 days”);
else
printf(“Invalid month value”);
6
switch –case Statement: Multiple Branches
int month;
scanf(“%d”,&month);
switch(month) {
case 4: case 6: case 9: case 11: printf(“ 30 days”); break;
BITS Pilani, Pilani Campus
case 1: case 3: case 5: case 7: case 8: case 10: case 12:
printf(“31 days”); break;
case 2: printf(“28 or 29 days”); break;
default: printf(“ Not a valid month”);
}
7
Switch –case Statement in C
• For multiple branches with simple uniform conditions, switch-case statement can be used
– The conditions must be in the form of equality (i.e. x == c) on Integer/character
– The break statement is used to indicate that the
BITS Pilani, Pilani Campus
– The break statement is used to indicate that the next case need not be tested
– If none of the cases match then the default case is executed
8
Switch Statement: Flow Chart
switch( )exprcase 1
case 2
Statement Block-1; break;
BITS Pilani, Pilani Campus
9
case 3
case 4
default
Statement Block-3; break;
Statement Block-4; break;.....
Default Statement Block;