Decision Making and Branching
Conditional Statements
Branching: if Statement
Example
Branching: if - else Statement
Sample Program: Grade Calculation
//Program showing the use of if-else
#include<stdio.h>
int main()
int marks;
printf("\n enter the marks:");
scanf("%d",&marks);
if (marks >= 80)
printf ("A\n") ;
printf("Good Job Done");
else if (marks >= 70)
printf ("B") ;
else if (marks >= 60)
printf ("C") ;
else
printf ("Failed\n") ;
printf("Study Hard");
return 0;
}
Find Larger of Two Numbers
//Larger of two numbers
#include<stdio.h>
int main()
{
int x,y;
printf("\n enter two numbers:");
scanf("%d%d",&x,&y);
if (x>y)
printf("%d is larger",x);
else
printf("%d is larger",y);
return 0;
}
Largest of three numbers
//Largest of three numbers
#include<stdio.h> //Largest of three numbers
int main() #include<stdio.h>
{ int main()
{
int x,y,z; int x,y,z;
printf("\n enter the three numbers:"); printf("\n enter the three numbers:");
scanf("%d%d%d",&x,&y,&z); scanf("%d%d%d",&x,&y,&z);
if ((x >= y) && (x >= z))
int max; printf ("\n The largest number is: %d",
if (x>=y) x);
max=x; if ((y >= x) && (y >= z))
printf ("\n The largest number is: %d",
else y);
max=y; if ((z >= x) && (z >= y))
if (max>=z) printf ("\n The largest number is: %d",
z);
printf("%d is largest",max); return 0;
else }
printf("%d is largest",z);
return 0;
}
Equality (==) & Assignment (=) Operator
Nesting of if-else Structure
Dangling else problem
More Examples
Answers
Branching with Conditional Operator ?:
More Examples
Branching with switch statement
Branching with switch statement
Branching with switch statement
The break statement
The break statement
}
Example: switch statement
Example: switch statement
Sample Program
//switch statement
#include<stdio.h>
int main()
{
char letter;
printf("\n enter the character: ");
scanf("%c",&letter);
switch(letter)
{
case 'A':printf("\n A");
case 'B':printf("\n B");
break;
case 'Z':printf("\n Z");
break;
default:
printf("\n Anything");
break;
return 0;
}
}
Sample Program
//switch statement
#include<stdio.h>
int main()
{
char letter;
printf("\n enter the character: ");
//scanf("%c",&letter);
switch(letter=getchar())
{
case 'A':printf("\n A");
case 'B':printf("\n B");
break;
case 'Z':printf("\n Z");
break;
default:
printf("\n Anything");
break;
return 0;
}
}
Sample Program
//Evaluating Expressions
#include<stdio.h> case '*':
int main() result=op1*op2;
{
printf("\n Result is %f",result);
break;
float op1,op2,result;
case '/':
char operation;
printf("\n enter the first operand:");
if (op2!=0.0)
scanf("%f",&op1); {
printf("\n enter the second operand:"); result=op1/op2;
scanf("%f",&op2); printf("\n Result is %f",result);
getchar(); }
printf("\n enter the operation:"); else
scanf("%c",&operation); printf("\n Division by 0 Error");
switch(operation)
break;
{
case '+':
default:printf("\n Invalid Operation.");
result=op1+op2; }
printf("\n Result is %f",result); return 0;
break; }
case '-':
result=op1-op2;
printf("\n Result is %f",result);
break;