If Statement
If Statement
Md Shafiuzzaman
Lecturer, Dept. of CSE, NBIU
If Statement
The if in C is a decision-making statement that is used to execute a block
of code based on the value of the given expression. It is one of the core
concepts of C programming and is used to include conditional code in our
program.
Syntax of if Statement in C:
Relational operators
if(condition) are used here
{
// if body
// Statements to execute if condition is true
}
How if in C works?
The working of the if statement in C is as
follows:
return 0;
}
if...else statement
An if statement can be followed by
an optional else statement, which
executes when the Boolean
expression is false.
#include <stdio.h>
int main() {
int number;
printf("Enter an integer: ");
scanf("%d", &number);
if (number%2 == 0) {
printf("%d is an even integer.",number);
}
else {
printf("%d is an odd integer.",number);
}
return 0;
}
if-else-if Ladder
• The if else if statements are used when the user
has to decide among multiple options.
• The C if statements are executed from the top if (condition)
down. As soon as one of the conditions controlling statement;
the if is true, the statement associated with that if else if (condition)
is executed, and the rest of the C else-if ladder is statement;
bypassed. .
• If none of the conditions is true, then the final else .
statement will be executed. else
• if-else-if ladder is similar to the switch statement. statement;
if….
else if
Ladder
if-else-if Ladder
#include <stdio.h>
int main() {
int number;
printf("Enter a number: ");
scanf("%d", &number);
if (number > 0) {
printf("The number is positive.\n");
}
else if (number < 0) {
printf("The number is negative.\n"); }
else {
printf("The number is zero.\n"); }
return 0;
}
Start
Disadvantages of if Statement
➢ It contains only a single block. In case when there are multiply related if
blocks, all the blocks will be tested even when the matching if block is found
at the start.
➢ When there are a large number of expressions, the code of the if block gets
complex and unreadable.
➢ It is slower for a large number of conditions.