Conditional Statements
In C, conditional statements are the backbone of decision-making in your programs. They allow you to control the flow of execution based on specific conditions. This section dives deep into two essential conditional structures: if / else and switch. By mastering these, you’ll be able to build programs that respond intelligently to varying inputs and scenarios.
If / Else Statements
The if / else statement is the simplest and most fundamental conditional structure in C. It lets you execute a block of code if a condition is true, and an alternative block if the condition is false. This construct is your go-to for basic decision logic.
Syntax and Structure
The basic syntax is:
<code class="language-c">if (condition) {
<p> // Code to run if condition is true</p>
<p>} else {</p>
<p> // Code to run if condition is false</p>
<p>}</code>
You can also chain multiple conditions using else if:
<code class="language-c">if (condition1) {
<p> // Code block 1</p>
<p>} else if (condition2) {</p>
<p> // Code block 2</p>
<p>} else {</p>
<p> // Code block 3 (if none of the above conditions are true)</p>
<p>}</code>
Practical Examples
Example 1: Checking for Even or Odd Numbers
<code class="language-c">#include <stdio.h>
<p>int main() {</p>
<p> int number = 7;</p>
<p> if (number % 2 == 0) {</p>
<p> printf("The number is even.\n");</p>
<p> } else {</p>
<p> printf("The number is odd.\n");</p>
<p> }</p>
<p> return 0;</p>
<p>}</code>
Output when number = 7: The number is odd.
Example 2: Grade Determination
<code class="language-c">#include <stdio.h>
<p>int main() {</p>
<p> int score = 85;</p>
<p> if (score >= 90) {</p>
<p> printf("Grade: A\n");</p>
<p> } else if (score >= 80) {</p>
<p> printf("Grade: B\n");</p>
<p> } else if (score >= 70) {</p>
<p> printf("Grade: C\n");</p>
<p> } else {</p>
<p> printf("Grade: F\n");</p>
<p> }</p>
<p> return 0;</p>
<p>}</code>
Output when score = 85: Grade: B
Example 3: Simple User Input Validation
<code class="language-c">#include <stdio.h>
<p>int main() {</p>
<p> int age;</p>
<p> printf("Enter your age: ");</p>
<p> scanf("%d", &age);</p>
<p> if (age < 0) {</p>
<p> printf("Error: Age cannot be negative.\n");</p>
<p> } else {</p>
<p> printf("Your age is: %d\n", age);</p>
<p> }</p>
<p> return 0;</p>
<p>}</code>
This program validates user input for age, ensuring it’s non-negative.
Key Points to Remember
- Always use braces
{}for code blocks to avoid ambiguity (especially when adding more conditions later). - Condition expressions must evaluate to
true/false. In C, non-zero values aretrue, and zero isfalse. - The
elseblock is optional if you don’t need to handle thefalsecase (though it’s common practice to include it for clarity).
Switch Statements
The switch statement provides a more readable alternative to multiple if / else statements when dealing with multiple discrete values. It’s particularly useful for handling integer or character-based options efficiently.
Syntax and Structure
The syntax for a switch statement is:
<code class="language-c">switch (expression) {
<p> case constant1:</p>
<p> // Code block for constant1</p>
<p> break;</p>
<p> case constant2:</p>
<p> // Code block for constant2</p>
<p> break;</p>
<p> ...</p>
<p> default:</p>
<p> // Code block for unmatched values</p>
<p>}</code>
- The
expressionis evaluated once. - The value is compared to each
caselabel. - When a match is found, the corresponding block executes, and
breakexits theswitch(preventing “fall-through” to subsequent cases).
Practical Examples
Example 1: Simple Menu Selection
<code class="language-c">#include <stdio.h>
<p>int main() {</p>
<p> int choice;</p>
<p> printf("Choose a number (1-3): ");</p>
<p> scanf("%d", &choice);</p>
<p> switch (choice) {</p>
<p> case 1:</p>
<p> printf("You chose 1.\n");</p>
<p> break;</p>
<p> case 2:</p>
<p> printf("You chose 2.\n");</p>
<p> break;</p>
<p> case 3:</p>
<p> printf("You chose 3.\n");</p>
<p> break;</p>
<p> default:</p>
<p> printf("Invalid choice.\n");</p>
<p> }</p>
<p> return 0;</p>
<p>}</code>
Output when choice = 2: You chose 2.
Example 2: Handling Character Grades
<code class="language-c">#include <stdio.h>
<p>int main() {</p>
<p> char grade = 'B';</p>
<p> switch (grade) {</p>
<p> case 'A':</p>
<p> printf("Grade: A\n");</p>
<p> break;</p>
<p> case 'B':</p>
<p> printf("Grade: B\n");</p>
<p> break;</p>
<p> case 'C':</p>
<p> printf("Grade: C\n");</p>
<p> break;</p>
<p> default:</p>
<p> printf("Unknown grade.\n");</p>
<p> }</p>
<p> return 0;</p>
<p>}</code>
Output when grade = 'B': Grade: B
Example 3: Using switch with Integers
<code class="language-c">#include <stdio.h>
<p>int main() {</p>
<p> int day = 3;</p>
<p> switch (day) {</p>
<p> case 1:</p>
<p> printf("Monday\n");</p>
<p> break;</p>
<p> case 2:</p>
<p> printf("Tuesday\n");</p>
<p> break;</p>
<p> case 3:</p>
<p> printf("Wednesday\n");</p>
<p> break;</p>
<p> default:</p>
<p> printf("Invalid day.\n");</p>
<p> }</p>
<p> return 0;</p>
<p>}</code>
Output when day = 3: Wednesday
Key Points to Remember
- Each
casemust have abreakstatement (orreturn) to prevent “fall-through” (i.e., the program continuing to execute the nextcase). - The
defaultcase is optional and executes when nocasematches the expression. - Use
switchfor discrete values (e.g., integers, characters) but avoid it for ranges or complex conditions.
When to Use Switch vs If-Else
Here’s a comparison table to help you decide:
| Scenario | Use if-else |
Use switch |
|---|---|---|
| Multiple discrete integer values | ❌ (less readable) | ✅ (more readable and concise) |
Range checks (e.g., x > 5) |
✅ (natural) | ❌ (not suitable) |
| Character or string comparisons | ✅ (with strcmp for strings) |
✅ (for single characters) |
| Complex conditions | ✅ (e.g., nested conditions) | ❌ (not designed for this) |
Note: For strings, switch is not directly supported (use if with strcmp or strcmp in the condition).
Summary
In this section, we’ve covered two essential conditional structures in C: if / else and switch.
- The
if / elsestatements are your go-to for simple and compound conditions, allowing precise control over program flow based on boolean expressions. - The
switchstatement excels at handling multiple discrete values efficiently, making your code more readable when dealing with a set of fixed options.
Both constructs are foundational for writing robust and maintainable C programs. Remember to:
- Use braces
{}for code blocks. - Always include
breakinswitchcases to avoid fall-through. - Choose
if / elsefor complex logic andswitchfor discrete value handling.
By mastering these concepts, you’ll be able to build decision-driven logic that responds confidently to your program’s needs. 💡