Lecture 6 NestedIf&Switch
Lecture 6 NestedIf&Switch
if-else statement
else part is optional
The else is associated with closest else-less if
if(n>0)
Even though the else is indented with the
if(a>b) z=a; first if, by rule it will be associated with
else z=b; the nearest if
Braces must be used to force association with the first
if(n>0)
{
if(a>b) z=a;
}
else z=b;
Nested if
#include<stdio.h>
int main(void)
{
int id; else
printf("Please enter last 3 digits of your {
id:\n"); if(id<61)
scanf("%d", &id); printf("B1\n");
printf("You are in ");
if(id%2) else
{ printf("B2\n");
if(id<60) }
printf("A1\n");
else return 0;
printf("A2\n"); }
}
Blocks of Code
Surround the statements in a block with opening and ending curly
braces.
One indivisible logical unit
Can be used anywhere a single statement may
Multiple statements
Common programming error:
Forgetting braces of compound statements/blocks
Blocks of Code
if(expression) {
statement1;
statement2;
…
statementN;
}
else {
statement1;
statement2;
…
statementN;
}
If expression is true all the statements with if will be executed
If expression is false all the statements with else will be executed
if-else if statement
if(expression)
statement;
else if (expression)
statement;
else if (expression)
statement;
else
statement;
if-else if statement
Multi-way decision
expressions are evaluated in order
If the expression of any if is true
the statement associated with it is executed
Multiple statements can be associated using curly braces
the whole chain is terminated
If none of the expressions are true
else part is executed
Handles none of the above/ default case
Optional
if-else if statement
#include<stdio.h>
int main( )
{
int num; else
scanf("%d", &num); printf("0.0");
if(num>=80) return 0;
printf("5.0\n"); }
else if(num>=75)
printf("4.75\n");
else if(num>=70)
printf("4.50\n");
Use of logical operator
#include<stdio.h>
int main( ){
char ch;
scanf("%c", &ch);
if(ch>='A' && ch<='Z')
printf("%c\n", ch+('a'-'A'));
else if(ch>='a' && ch<='z')
printf("%c\n", ch-('a'-'A'));
else
printf("Invalid\n");
return 0;
}
Short Circuit Evaluation
if(a!=0 && num/a)
{
}