How to Use If Else in C: Simple Guide with Examples
In C, use
if to run code when a condition is true, and else to run code when it is false. The syntax is if (condition) { ... } else { ... }. This lets your program choose between two paths based on conditions.Syntax
The if else statement lets you run different code based on a condition.
- if (condition): Checks if the condition is true.
- { ... }: Code inside braces runs if the condition is true.
- else: Runs if the
ifcondition is false. - { ... }: Code inside braces runs if the
elsepart is executed.
c
if (condition) { // code runs if condition is true } else { // code runs if condition is false }
Example
This example checks if a number is positive or not and prints a message accordingly.
c
#include <stdio.h> int main() { int number = 5; if (number > 0) { printf("Number is positive\n"); } else { printf("Number is zero or negative\n"); } return 0; }
Output
Number is positive
Common Pitfalls
Common mistakes when using if else in C include:
- Forgetting braces
{ }when you have multiple statements insideiforelse. This causes only the first statement to be controlled by the condition. - Using
=(assignment) instead of==(comparison) in the condition. - Missing semicolons
;after statements.
c
/* Wrong: missing braces causes only first printf to be conditional */ if (number > 0) printf("Positive\n"); printf("Checked number\n"); // runs always /* Right: braces group both statements */ if (number > 0) { printf("Positive\n"); printf("Checked number\n"); }
Quick Reference
Tips for using if else in C:
- Always use braces
{ }for clarity and to avoid bugs. - Use
==to compare values, not=. - Indent your code inside
ifandelseblocks for readability. - You can chain multiple conditions using
else if.
Key Takeaways
Use
if to run code when a condition is true and else when it is false.Always use braces
{ } to group multiple statements inside if or else blocks.Use
== for comparison, not = which assigns values.Indent your code inside conditions for better readability.
You can add more conditions with
else if for multiple choices.