๐ C If-Else Statement – Conditional Logic Explained
The if-else statement in C is used to perform different actions based on different conditions. It’s like giving your program a choice: “If this is true, do this, otherwise do that.”
๐น Basic Syntax of if-else
if (condition) { // Code if condition is true } else { // Code if condition is false }
๐ Example: Basic If-Else
This example checks if a number is positive or negative.
#include <stdio.h> int main() { int number = -10; if (number >= 0) { printf("The number is positive.\n"); } else { printf("The number is negative.\n"); } return 0; }
๐ Example: If-Else with User Input
This program asks the user to enter a number and then decides if it’s even or odd.
#include <stdio.h> int main() { int num; printf("Enter a number: "); scanf("%d", &num); if (num % 2 == 0) { printf("The number is even.\n"); } else { printf("The number is odd.\n"); } return 0; }
๐น Nested If-Else
You can put one if-else
inside another to make more complex decisions.
๐ Example: Nested If-Else
This checks if a number is positive, negative, or zero.
#include <stdio.h> int main() { int number = 0; if (number > 0) { printf("Positive number.\n"); } else { if (number < 0) { printf("Negative number.\n"); } else { printf("It's zero!\n"); } } return 0; }
๐ฏ Quick Tips
- if checks a condition.
- else runs if the condition is false.
- Conditions use comparison operators like
==
,>
,<
,!=
, etc. - You can nest multiple
if-else
blocks for detailed logic.
๐ Try It Yourself!
Modify the examples with your own numbers and conditions. Observe how the flow changes. Logic is fun when you play with it!