C Decision Making Statements
C decision statements are used to make a decision, based on some conditions.
Types of decision-making statements
The if-else statement
The else-if ladder statement
The switch case statement
If-else Statement
The if statement is used to execute a block of code only if the specified condition is true in C programming.
Syntax of If-else Statement
if(expression)
{
//code to be executed
}else
{
//code to be executed
}
Example of if-else Statement
#include<stdio.h>
int main()
{
int age=19;
if(age>=18)
{
printf("You are eligible to vote");
}
else
{
printf("You are not eligible to vote");
}
return 0;
}
You are eligible to vote
If else-if ladder Statement
The if else-if ladder statement is used to execute one code in comparison of multiple conditions in C programming.
Syntax of else-if ladder Statement
if(condition1)
{
//code to be executed if condition1 is true
}
else if(condition2)
{
//code to be executed if condition2 is true
}
else if(condition3)
{
//code to be executed if condition3 is true
}
...
else
{
//code to be executed if all the conditions are false
}
Example of else-if ladder Statement
#include<stdio.h>
int main()
{
char vowel;
printf("Enter the character=");
scanf("%c",&vowel);
if(vowel=='i' && vowel=='I')
{printf("%c is a vowel \n",vowel);}
else if(vowel=='o' && vowel=='O')
{printf("%c is a vowel \n",vowel);}
else if(vowel=='u' && vowel=='U')
{printf("%c is a vowel \n",vowel);}
else if(vowel=='a' && vowel=='A',vowel)
{printf("%c is a vowel \n");}
else
{printf("%c is not a vowel",vowel);}
return 0;
}
Enter the character=i
u is a vowel
The switch…case statement
A switch statement is used to compare a variable value against a list values and execute the block of statements associated with the matched case.
Syntax of switch statement
switch(expression)
{
case value_1:
code to be executed;
break;//optional
case value_2:
code to be executed;
break;//optional
case value_3:
code to be executed;
break;//optional
.
.
.
case value_n:
code to be executed;
break;//optional
default:
code to be executed;
}
Example switch statement
#include<stdio.h>
int main()
{
int number;
printf("Enter the Number=");
scanf("%d",&number);
switch(number)
{
case 10:
printf("Number is equal to %d",number);
break;
case 20:
printf("Number is equal to %d",number);
break;
case 30:
printf("Number is equal to %d",number);
break;
default:
printf("Number is not equal to 10, 20 and 30");
}
return 0;
}
Enter the number=89
Number is not equal to 10, 20 and 30
Exercises & Assignments |
---|
No Content Found. |
Interview Questions & Answers |
---|
No Content Found. |