You are on page 1of 14

Decision Making and Branching

HK Rana, Dept. of CSE, GUB 29-Oct-21


Decision making statements are as follows:

 If statement
 Conditional Operator statement
 Switch statement

Depending upon the conditions to be tested if can be:

 Simple if
 if…..else
 Nested if…else
 else…if ladder

HK Rana, Dept. of CSE, GUB 29-Oct-21


Simple if

if(test condition)
{

statement; true
Condition statement

}
false

HK Rana, Dept. of CSE, GUB 29-Oct-21


Simple if

#include<stdio.h>
int main()
{
int num;
scanf("%d", &num);
if(num>=0) printf("num is positive");
if(num<0) printf("num is negative");
return 0;
}

HK Rana, Dept. of CSE, GUB 29-Oct-21


if…..else

if(condition)
{ false
true
Statement 1; Statement 2 Condition Statement 1

}
else
{
Statement 2;
}

HK Rana, Dept. of CSE, GUB 29-Oct-21


if-else

#include<stdio.h>
int main()
{
int num;
scanf("%d", &num);
if(num>=0) printf("num is positive");
else printf("num is negative");
return 0;
}

HK Rana, Dept. of CSE, GUB 29-Oct-21


Nested if…else

if(condition 1)
{
if(condition 2)
{
Statement 1;
}
else
{
Statement 2;
}
}
else
{
Statement 3;
}

HK Rana, Dept. of CSE, GUB 29-Oct-21


Nested if…else
scanf(“%d %d %d”,&a,&b,&c);
if( a>b)
{
if(a>c)
printf(“ a is greater”);
else
printf(“ c is greater”);
}
else
{
if(b>c)
{
Printf(“b is greater”);
}
else
{
Printf(“c is greater”);
}
}

HK Rana, Dept. of CSE, GUB 29-Oct-21


else…if ladder
 if(expression)
statement;
else if (expression)
statement;
else if (expression)
statement;
else
statement;

HK Rana, Dept. of CSE, GUB 29-Oct-21


else…if ladder
#include<stdio.h> …
int main( ) …
{ …
int num; else
scanf("%d", &num); printf("Fail");
if(num>=80) return 0;
printf("A+\n"); }
else if(num>=75)
printf("A\n");
else if(num>=70)
printf("A-\n");
HK Rana, Dept. of CSE, GUB 29-Oct-21
Conditional Operator statement
 Uses ternary operator “?:”
 expression1?expression2:expression3;
 z= (a>b)? a: b;
 Can be used anywhere an expression can be

HK Rana, Dept. of CSE, GUB 29-Oct-21


switch case
switch (expression) {
case constant:
statement 1;
break;
case constant:
statement 2;
break;
default: statement 3;
}

HK Rana, Dept. of CSE, GUB 29-Oct-21


switch case
scanf(„%d”,&num);
switch(num)
{
case 1:
printf(“Sunday”);
break;
case 2: printf(“Monday”); break;
case 3: printf(“Tuesday”); break;
case 4: printf(“Wednesday”); break;
case 5: printf(“Thursday”); break;
case 6: printf(“Friday”); break;
case 7: printf(“Saturday”); break;
default: printf(“wrong choice”); break;
}

HK Rana, Dept. of CSE, GUB 29-Oct-21


Thank you!

HK Rana, Dept. of CSE, GUB 29-Oct-21

You might also like