The if statement in C is a control flow statement that allows the execution of a block of code if a specified condition is true. If the condition evaluates to a non-zero value (true), the code inside the if block is executed; otherwise, it is skipped.
Syntax:
if (condition)
{
// Code to execute if condition is true
}
Explanation:
- condition: This is an expression that evaluates to a boolean value (true or false).
- The code inside the curly braces {} will execute only if the condition is true.
Example 1:
#include <stdio.h>
int main() {
int age = 18;
// Checking if the person is eligible to vote
if (age >= 18)
{
printf("You are eligible to vote.");
}
return 0;
}
Explanation:
- Condition: age >= 18 is the condition being checked.
- Since age is 18, which is equal to 18, the condition evaluates to true.
Output:
You are eligible to vote.
Example 2: If number is positive
#include <stdio.h>
int main() {
int number = 15;
// Checking if the number is positive
if (number > 0)
{
printf("Number is positive");
}
return 0;
}
Explanation:
- Condition: number >= 0 is the condition being checked.
- Since number is greater than 0, then condition evaluates to true.
Output:
Number is positive