
If Else in C
In C, the if...else
statement is used to make decisions in your code — to run different blocks of code depending on whether a condition is true or false. ??
? Basic Syntax
#include <stdio.h>int main() { int num = 10; if (num > 0) { printf("Positive number\n"); } else { printf("Zero or negative number\n"); } return 0;}
Output:
Positive number
? if...else if...else
You can chain multiple conditions:
int age = 18;if (age < 13) { printf("Child\n");} else if (age < 20) { printf("Teen\n");} else { printf("Adult\n");}
? Real-World Example
int marks = 85;if (marks >= 90) { printf("Grade: A\n");} else if (marks >= 80) { printf("Grade: B\n");} else if (marks >= 70) { printf("Grade: C\n");} else { printf("Grade: F\n");}
?? Notes
The condition inside
if
must return true (non-zero) or false (zero)Use comparison operators like
==
,!=
,<
,>
,<=
,>=
Use logical operators like
&&
,||
,!
for complex conditions
Want to explore nested if
, ternary operator (? :
), or compare with switch
? I’ve got you covered!