Conditional statements are a fundamental concept in programming that allow a program to make decisions based on certain conditions. They help control the flow of execution by determining which blocks of code should run under specific circumstances.
2. Introduction
•Conditional statements allow us to make decisions in programs based on conditions.
•It helps control the flow of execution depending on whether a condition is true or false.
3. Types of Conditional Statements in C
•1. If statement
•2. If-else statement
•3. Nested If-else statement
•4. Switch statement
4. If Statement
• Syntax:
if (condition) {
// Code to be executed if the condition is true
};
• Example:
int num = 10;if (num > 5) {
printf("Number is greater than 5");
};
5. If-Else Statement
• Syntax:
• if (condition) { // Code to be executed if condition is true} else { //
Code to be executed if condition is false}
• Example:
int num = 3;if (num > 5)
{ printf("Number is greater than 5");}
else { printf("Number is less than or equal to 5");}
6. Nested If-Else Statement
• Syntax:
• if (condition1) { if (condition2) { // Code for condition2 } else {
// Code for else condition2 }} else { // Code for else condition1}
• Example:
• int num = 15;if (num > 10) { if (num % 2 == 0) { printf("Number is
even and greater than 10"); } else { printf("Number is odd and greater
than 10"); }}
7. Switch Statement
• Syntax:
• switch (expression) { case value1: // Code to be executed if expression equals value1 break; case
value2: // Code to be executed if expression equals value2 break; default: // Code to be executed
if expression doesn't match any case}
• Example:
int num = 2;switch (num) {
case 1:printf("Number is 1");
break; case 2: printf("Number is 2");
break;
default: printf("Number is neither 1 nor 2");}
8. Comparison of If-Else and Switch
•If-Else:
•Flexible and can evaluate complex conditions.
•Suitable for a range of different data types.
•Switch:
•Best for handling multiple discrete values of the same variable.
•More efficient when dealing with multiple case conditions.
9. Common Errors in Conditional Statements
•Forgotten Break:
•Omitting the break in a switch can cause unwanted fall-through.
•Incorrect Condition:
•Using the wrong operators or logic in conditions.
•Unreachable Code:
•Placing code after a return or break in the wrong places.
10. Conclusion
•Summary:
•Conditional statements are crucial for making decisions in C programs.
•We have learned about if, if-else, nested if-else, and switch statements.
•Takeaway:
•Proper usage of conditional statements helps control the flow of logic based on
conditions.