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:
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:
C if statement – Interview Questions
Q 1: What is the if statement in C?
Ans: The if statement executes a block of code when a specified condition is true.
Q 2: What type of expression is used in an if condition?
Ans: A relational or logical expression that evaluates to true or false.
Q 3: Can we use multiple conditions in an if statement?
Ans: Yes, using logical operators like && and ||.
Q 4: Is curly brace {} mandatory in an if statement?
Ans: No, but it is recommended when there are multiple statements.
Q 5: What happens if the if condition is false?
Ans: The code inside the if block is skipped.
C if statement – Objective Questions (MCQs)
Q1. What is the correct syntax for an if statement in C?
Q2. What type of value does the condition inside an if statement evaluate to?
Q3. What happens if the condition in an if statement is false?
Q4. Which of the following is a valid example of an if statement?
Q5. What will be the output of this code?
int x = 10;
if (x == 10)
printf("Ten");