C program If Statement
C program If Statement
2
• The logical conditions created by the logic statements can be used to
perform different actions and execute different decisions and tasks
depending on the condition
• C programming has the several conditional statements
• if
• else
• else if
• switch
3
if Statement
• if statement is used to specify a block of codes to be executed if the
specified condition is truesyntax
Syntax
if (condition){
//Block of codes to be executed
}
NOTE
• The word if must be in lowercase
• IF or If or iF
• This will generate error!!
4
Example
5
else Statement
• else is used to specify a block of code to be executed if the same
condition is false
• else is used alongside the if statement
Syntax
if (condition){
//Block of codes to be executed if condition is true
}
else{
//Block of codes to be executed condition is false
}
6
Example
7
else if statement
• else if is used to specify a new condition if the first condition is false
Syntax
if (condition1){
//Block of codes to be executed if condition is true
}
else if (condition2){
//Block of codes to be executed condition 1 is false
}
else{
//Block of codes to be executed condition 1 and 2 are false
}
8
Example
9
Ternary Operator
• This can be used to replace multiple lines of code into a single line. It
is used to replace if else statement with a single line of code
Syntax
variable = (condition) ? expressionTrue : expressionFalse;
• Example:
int time = 20;
(time < 18) ? printf("Good day.") : printf("Good evening.");
10
SWITCH STATEMENT
11
switch statement
• switch statement is used to specify blocks of statements that need to
be executed
• It is used to replace many if-else statements by using switch-case
approach
12
switch statement (2)
• The switch statement is executed once
• The value of the expression is compared to a value of each case in the
switch statement
• The break statement terminates each switch block and terminates
(stops) execution
• The default case is optional and it is executed once there is no match
in any of the switch statements
13
switch statement (3)
Syntax
switch (expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
14
Example
15
....END….
Thank you
…………..
16