
If and If-Else Statements in C
If and If-Else statements are used to make decisions in a C program based on conditions.
"Decision-making is crucial in programming, and If-Else statements help control program flow."
Syntax of If and If-Else Statements
if (condition) {
// Code executes if condition is true
} else {
// Code executes if condition is false
}
Examples of If and If-Else Statements
1. Simple If Statement
#include <stdio.h>
int main() {
int num = 10;
if (num > 0) {
printf("Number is positive.\n");
}
return 0;
}
2. If-Else Statement
#include <stdio.h>
int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);
if (num % 2 == 0) {
printf("Even Number\n");
} else {
printf("Odd Number\n");
}
return 0;
}
3. Nested If-Else Statement
#include <stdio.h>
int main() {
int age;
printf("Enter your age: ");
scanf("%d", &age);
if (age >= 18) {
if (age >= 65) {
printf("You are a senior citizen.\n");
} else {
printf("You are an adult.\n");
}
} else {
printf("You are a minor.\n");
}
return 0;
}
Best Practices for If-Else Statements
- Use **indentation** to improve readability.
- Always **use braces** `{}` even if there is only one statement.
- Avoid **deep nesting**, as it reduces readability.
Conclusion
If and If-Else statements help make decisions in programs, ensuring the execution of specific code blocks based on conditions.