Decision
making in C involves controlling the flow of a program based on certain
conditions or criteria. This control flow allows the program to execute
different sets of instructions or take specific actions based on the evaluation
of conditions.
Decision Making can occur in these forms:
• if statement
• switch statement
• conditional
operator statement (? : operator)
• goto statement
if statement:
The
if statement may be implemented in different forms depending on the complexity
of conditions to be tested. The different forms are,
1. Simple if
statement
2. if. else statement
3. Nested if. else
statement
4. Using else if
statement
Example:
The marks obtained by a student in 5 different subjects are input
through the keyboard. The student gets a division as per the following rules:
Percentage above or equal to 60 - First division
Percentage between 50 and 59 - Second division
Percentage between 40 and 49 - Third division
Percentage less than 40 - Fail
A program to calculate the division obtained by the student using
if else is as follows:
# include <stdio.h>
void main( )
{
int m1, m2, m3, m4, m5, per ; //declaring variables
printf ( "Enter marks in five subjects " ) ;
scanf ( "%d %d %d %d %d", &m1, &m2, &m3,
&m4, &m5 ) ; //input
per = ( m1 + m2 + m3 + m4 + m5 ) * 100 / 500 ;
if ( per >= 60 )
printf (
"First division\n" ) ;
else
{
if ( per
>= 50 )
printf (
"Second division\n" ) ;
else
{
if ( per
>= 40 )
printf (
"Third division\n" ) ;
else
printf (
"Fail\n" ) ;
}
}
}
Switch Statement:
the ‘switch’ statement is a control flow statement that allows a program to evaluate the value of a variable or expression and execute code blocks based on different possible values of that variable or expression.
Here is a code to clear the concept-
#include<stdio.h>
int
main()
{
int
i=2;
switch (i)
{
case
1:
printf("Case1
");
break;
case
2:
printf("Case2
");
break;
case
3:
printf("Case3
");
break;
case
4:
printf("Case4
");
break;
default:
printf("Default
");
}
return
0;
}
Output:
Case
2
1 Comments
fantastic
ReplyDelete