Decision control statement
Types of decision control statements:-
- Simple if
- If else
- Else if ladder
- Nested concept of if statement i.e. nested if
- Switch case :-- with uses of break and continue statement
IF STATEMENT
SYNTEX OF IF STATEMENT :
- If(condition)
- {Statement 1..Statement 2.Statement 3..And so on many more conditions….}Statement Y;
EXPLANATION OF THIS SYNTEX OF STATEMENT
Else if ladder
SYNTEX OF ELSE IF LADDER If
- ( text expression )
- {statement 1;Statement 2;}else if ( test statement 2 ){statement block N ;}else if ( test expression 3){statement block M ;}……..and so on else{ statement block Z }
NESTED IF STATEMENT
SYNTEX OF NESTED IF STATEMENT
- If( text expression ){statement 1 ;If {test expression 2 ){printf( “ this is the best site : “CODEMOB” );}}Statement Y ;
SWITCH STATEMENT
- When there is only one variable to evaluate in the expression
- When one possibility is to be selected on the basis of input. Switch case statement advantage include
- Easy to debug , read , understand and maintain
- Execute faster than its equivalent if-else construct.
Example of switch case is
/*C
program to design calculator with basic operations using switch.*/
#include <stdio.h>
int main()
{
int num1,num2;
float result;
char ch; //to store operator choice
printf("Enter first number: ");
scanf("%d",&num1);
printf("Enter second number: ");
scanf("%d",&num2);
printf("Choose operation to perform (+,-,*,/,%): ");
scanf(" %c",&ch);
result=0;
switch(ch)
{
case
'+':
result=num1+num2;
break;
case
'-':
result=num1-num2;
break;
case
'*':
result=num1*num2;
break;
case
'/':
result=(float)num1/(float)num2;
break;
case
'%':
result=num1%num2;
break;
default:
printf("Invalid operation.\n");
}
printf("Result:%d %c %d=%f\n",num1,ch,num2,result);
return 0;
}
Output-
First run: Enter first number: 10 Enter second number: 20 Choose operation to perform (+,-,*,/,%): + Result: 10 + 20 = 30.000000 Second run: Enter first number: 10 Enter second number: 3 Choose operation to perform (+,-,*,/,%): / Result: 10 / 3 = 3.333333 Third run: Enter first number: 10 Enter second number: 3 Choose operation to perform (+,-,*,/,%): > Invalid operation. Result: 10 > 3 = 0.000000
0 Comments