C Programming If Statement Multiple Conditions | C Programming Tutorials
C programming if statement multiple conditions. In this C tutorial, you are going to learn how to use multiple conditions which lead to same result in C using if statement.
C Programming: If Statement Multiple Conditions
In a case in which if any one condition out of many is satisfied certain action must be performed, if statement with (||) OR operator can be used.Example
#include <stdio.h>
int main()
{
printf("Enter any alphabet: ");
scanf("%c",&character);
if(character == 'a' || character == 'e' || character == 'i' || character == 'o' || character == 'u')
{
printf("Character is vowel");
}
return 0;
}
Output:
Enter any alphabet: a Aplahabet is vowel
Explanation
In above C program, an aplhabet is accepted from user and stored it into variablecharacter
. If the value of variable character
is any of values (letters) 'a', 'e', 'i', 'o', 'u' then the if statement code block will be executed and message Character is vowel printed. To set multiple conditions which lead to execution of same code block if statement is used alogn with OR operator is used. Note that it needs only one condition to be satisfied out of many while using OR operator.
Another case is where multiple conditions need to be satisfied all together. In this case, if statement is used with AND operator.
Example
#include <stdio.h>
int main()
{
int number;
printf("Enter any number betwen 0 and 10 inclusive: ");
scanf(" %d",&number);
if((number > 0 && number < 10) || (number == 0 || number == 10))
{
printf("Number is between 0 and 10");
}
return 0;
}
Output
Enter any number betwen 0 and 10 inclusive: 4 Number is between 0 and 10To illustrate multiple conditions inside single if statment above example was considered. But it can be done easily with shorted code than in previous example.
#include <stdio.h>
int main()
{
int number;
printf("Enter any number betwen 0 and 10 inclusive: ");
scanf("%d",&number);
if(number >= 0 && number <= 10)
{
printf("Number is between 0 and 10");
}
return 0;
}
This code works the same. If you found this tutorial helpful please consider sharing it where ever you can :)
Comments