Condition statement
Condition statement
Equal to a == b
Use else if to specify a new condition to test, if the first condition is false
The if Statement
Use the if statement to specify a block of code to be executed if a condition is
true .
Syntax :
if (condition) {
// block of code to be executed if the condition is true
}
Example:
#include <stdio.h>
int main() {
int x = 20;
int y = 18;
if (x > y)
{
printf("x is greater than y");
}
Syntax:
if (condition) {
// block of code to be executed if the condition is true
} else {
// block of code to be executed if the condition is false
}
Example:
#include <stdio.h>
int main()
{
int time = 20;
if (time < 18)
{
printf("Good day.");
}
else
{
printf("Good evening.");
}
return 0;
}
if (condition1)
{
// block of code to be executed if condition1 is true
}
else if (condition2)
{
// block of code to be executed if the condition1 is false and
}
else
{
// block of code to be executed if the condition1 is false and
}
Example:
#include <stdio.h>
int main()
{
int time = 22;
if (time < 10)
{
printf("Good morning.");
}
else if (time < 20) {
printf("Good day.");
}
else
{
printf("Good evening.");
}
C Switch Statement:
Instead of writing many if..else statements, you can use the switch statement.
Syntax:
switch(expression)
{
case x:
The value of the expression is compared with the values of each case
The break statement breaks out of the switch block and stops the execution
The default statement is optional, and specifies some code to run if there is
no case match
Example
#include <stdio.h>
int main()
{
int day = 4;
switch (day) {
case 1:
printf("Monday");
break;
case 2:
printf("Tuesday");
break;
case 3:
printf("Wednesday");
break;
return 0;
}
This will stop the execution of more code and case testing inside the block.
When a match is found, and the job is done, it's time for a break. There is no need
for more testing.
#include <stdio.h>
int main() {
int day = 4;
switch (day) {
return 0;
}
int main() {
char operation;
double n1, n2;
switch(operation)
{
case '+':
printf("%f + %f = %f",n1, n2, n1+n2);
break;
case '*':
printf("%f * %f = %f",n1, n2, n1*n2);
break;
case '/':
printf("%f / %f = %f",n1, n2, n1/n2);
break;
return 0;
}
Output:
int main()
{
char ch;
/* Switch value of ch */
switch(ch)
{
case 'a':
printf("Vowel %c",ch);
break;
case 'e':
printf("Vowel %c",ch);
break;
case 'i':
printf("Vowel %c",ch);
break;
case 'o':
printf("Vowel %c",ch);
break;
case 'u':
printf("Vowel %c",ch);
break;
case 'A':
printf("Vowel %c",ch);
break;
case 'E':
printf("Vowel %c",ch);
break;
case 'I':
return 0;
}