C - Decision Making
Learn C - Decision Making step by step with clear examples and exercises.
Why This Matters
Welcome to this engaging guide on C programming's decision making! This tutorial is designed to provide you with a deep understanding of how to make your programs more intelligent and responsive using various control statements in C. By the end, you will be well-equipped to tackle real-world coding challenges and impress during interviews.
Why This Matters
Decision making is an essential aspect of programming that allows us to create dynamic solutions tailored to specific conditions. In C, we use various control statements such as if, if...else, switch, and loops to make our programs more flexible and adaptable to different scenarios. Understanding these concepts will help you write robust, efficient, and error-free code.
Prerequisites
Before diving into decision making in C, it's essential that you have a solid grasp of the following topics:
- Basic syntax and data types in C
- Variables and constants
- Input/output using
printfandscanffunctions - Basic operators (arithmetic, relational, logical, etc.)
- Control structures like
if,else, and loops
Core Concept
In this section, we'll explore various decision-making statements in C, including the if, if...else, switch, and loop constructs. We'll also discuss how to use these statements effectively to create dynamic programs that can handle a variety of conditions.
if Statement
The if statement is used to execute a block of code only when a specific condition is true. Here's an example:
#include <stdio.h>
int main() {
int age = 20;
if (age >= 18) {
printf("You are eligible to vote.\n");
}
return 0;
}
In this example, the program checks whether the user's age is greater than or equal to 18. If true, it prints "You are eligible to vote." Otherwise, nothing happens.
if...else Statement
The if...else statement allows us to execute different blocks of code based on multiple conditions. Here's an example:
#include <stdio.h>
int main() {
int grade = 85;
if (grade >= 90) {
printf("You got A+.\n");
} else if (grade >= 80) {
printf("You got A.\n");
} else if (grade >= 70) {
printf("You got B+\n");
} else {
printf("You need to work harder.\n");
}
return 0;
}
In this example, the program checks the user's grade and prints an appropriate message based on their score. If the user's grade is greater than or equal to 90, they get an A+. If it's between 80 and 89, they get an A. If it's between 70 and 79, they get a B+. Otherwise, they are told to work harder.
switch Statement
The switch statement is used when we have multiple conditions to check and the possible outcomes can be represented as constants or enumerated values. Here's an example:
#include <stdio.h>
int main() {
char day = 'S';
switch (day) {
case 'M':
printf("Today is Monday.\n");
break;
case 'T':
printf("Today is Tuesday.\n");
break;
case 'W':
printf("Today is Wednesday.\n");
break;
case 'S':
printf("Today is Saturday.\n");
break;
default:
printf("Invalid day of the week.\n");
}
return 0;
}
In this example, the program checks the day of the week and prints an appropriate message. If the day is Monday, Tuesday, Wednesday, or Saturday, it prints the corresponding message. If the day is not valid (e.g., Sunday), it prints "Invalid day of the week."
Worked Example
Let's consider a real-world example: writing a program that calculates the cost of a meal based on the number of items ordered and their price per item. Here's how you can do it:
#include <stdio.h>
int main() {
int numItems = 5;
float itemPrice = 20.0f, taxRate = 0.10f;
// Calculate the cost before tax
float costBeforeTax = numItems * itemPrice;
// Calculate the total cost including tax
float totalCost = costBeforeTax + (costBeforeTax * taxRate);
printf("The cost of %d items at $%.2f each is $%.2f before tax.\n", numItems, itemPrice, costBeforeTax);
printf("The total cost including tax is $%.2f.\n", totalCost);
return 0;
}
In this example, the program calculates the cost of a meal based on the number of items ordered and their price per item. It first calculates the cost before tax, then adds the tax to find the total cost. The output will look like:
The cost of 5 items at $20.00 each is $100.00 before tax.
The total cost including tax is $110.00.
Common Mistakes
- Forgetting to include the semicolon after the control statement: Remember that every C statement must end with a semicolon, even if it's a control statement like
if,else, orswitch.
- Not using braces properly: Always enclose the block of code for each control statement within braces (
{}). This helps avoid unexpected behavior when you add or remove statements inside the block.
- Comparing integers with floating-point numbers without casting: When comparing integers with floating-point numbers, it's essential to cast one of them to a float to avoid potential issues. For example:
if ((float)numItems == 5.0f).
- Not handling all cases in a switch statement: Make sure you handle every possible case in your
switchstatement, or use thedefaultclause to catch any unhandled cases.
Practice Questions
- Write a program that asks for the user's age and checks whether they are eligible to vote based on their country of residence (e.g., 18 in the US, 20 in India).
- Write a program that calculates the area of a rectangle given its length and width. If the length or width is negative, print an error message and exit the program.
- Write a program that finds the largest number among three input numbers using
if,else if, andelse. - Write a program that checks whether a given year is a leap year (a year divisible by 4 but not by 100, or divisible by 400).
FAQ
- Why do I need to use braces in C?
- Using braces helps avoid unexpected behavior when adding or removing statements inside a block. It makes the code easier to read and maintain.
- What's the difference between
ifandif...elsein C?
- The
ifstatement executes a single block of code if the condition is true, while theif...elsestatement allows you to execute different blocks based on multiple conditions.
- Why do I need to cast one of the operands when comparing integers with floating-point numbers in C?
- Casting one of the operands helps avoid potential issues caused by implicit conversions between integer and floating-point numbers, which can lead to unexpected results.
- What's the purpose of the
defaultclause in a switch statement?
- The
defaultclause is used to handle cases that don't match any specified case in the switch statement. It ensures that all possible cases are accounted for.