decision making in C programming
Learn decision making in C programming step by step with clear examples and exercises.
Why This Matters
Understanding decision making in C programming is crucial as it forms the backbone of many complex programs and algorithms. By learning how to control the flow of your code based on certain conditions, you will be better equipped to solve real-world problems, prepare for coding interviews, and debug complex programs.
Prerequisites
Before diving into decision making in C programming, it is essential that you have a good grasp of:
- Basic C syntax (variables, operators, functions)
- Control structures (loops and simple decision making with if-else statements)
- Data types and arrays
- File I/O operations
- Understanding of pointers and dynamic memory allocation (optional but recommended for more complex problems)
Core Concept
If Statement
The if statement in C programming allows you to execute a block of code only when a specific condition is true. The syntax for an if statement is:
if (condition) {
// code to be executed if the condition is true
}
For example, let's write a simple program that checks if a number is positive or negative:
#include <stdio.h>
int main() {
int num;
printf("Enter an integer: ");
scanf("%d", &num);
if (num > 0) {
printf("The number is positive.\n");
} else {
printf("The number is negative or zero.\n");
}
return 0;
}
If-Else Statement
If we want to execute different blocks of code for true and false conditions, we can use the if-else statement. The syntax is:
if (condition) {
// code to be executed if the condition is true
} else {
// code to be executed if the condition is false
}
For example, let's modify the previous program to also handle zero as a special case:
#include <stdio.h>
int main() {
int num;
printf("Enter an integer: ");
scanf("%d", &num);
if (num > 0) {
printf("The number is positive.\n");
} else if (num < 0) {
printf("The number is negative.\n");
} else {
printf("The number is zero.\n");
}
return 0;
}
Nested If Statements
Nested if statements allow you to create more complex decision-making structures. In a nested if, an if statement is placed inside another if or else block:
if (condition1) {
// code for condition1
if (condition2) {
// code for both condition1 and condition2
} else {
// code for condition1 but not condition2
}
} else {
// code for not condition1
}
Logical Operators
Logical operators allow you to combine multiple conditions in an if statement. The most common logical operators are && (and) and || (or). For example:
if (x > 5 && y < 10) {
// code if both x > 5 and y < 10 are true
}
If-Else If Ladder
An if-else if ladder is a series of nested if-else statements that check multiple conditions in sequence. The first condition checked is the first if, and if it's false, the program moves to the next else if. This continues until a matching condition is found or all conditions have been checked:
if (condition1) {
// code for condition1
} else if (condition2) {
// code for condition2
} else if (condition3) {
// code for condition3
} ...
else {
// code for none of the conditions
}
Switch Case
When we have multiple conditions to check, it's more efficient to use a switch statement. The syntax for a switch statement is:
switch (expression) {
case constant_1:
// code to be executed if the expression equals constant_1
break;
case constant_2:
// code to be executed if the expression equals constant_2
break;
...
default:
// code to be executed if the expression doesn't match any cases
}
For example, let's write a program that maps numbers from 1 to 7 to their corresponding days of the week:
#include <stdio.h>
int main() {
int day;
printf("Enter a number between 1 and 7: ");
scanf("%d", &day);
switch (day) {
case 1:
printf("Sunday\n");
break;
case 2:
printf("Monday\n");
break;
case 3:
printf("Tuesday\n");
break;
case 4:
printf("Wednesday\n");
break;
case 5:
printf("Thursday\n");
break;
case 6:
printf("Friday\n");
break;
case 7:
printf("Saturday\n");
break;
default:
printf("Invalid input. Please enter a number between 1 and 7.\n");
}
return 0;
}
Worked Example
Let's write a program that calculates the grade of a student based on their marks in an exam:
#include <stdio.h>
int main() {
int marks;
printf("Enter your marks: ");
scanf("%d", &marks);
if (marks >= 90) {
printf("Grade: A+\n");
} else if (marks >= 80) {
printf("Grade: A\n");
} else if (marks >= 70) {
printf("Grade: B+\n");
} else if (marks >= 60) {
printf("Grade: B\n");
} else if (marks >= 50) {
printf("Grade: C\n");
} else if (marks >= 40) {
printf("Grade: D\n");
} else {
printf("Sorry, you failed.\n");
}
return 0;
}
Common Mistakes
- Forgetting semicolons: Semicolons are important in C programming as they terminate statements. Forgetting a semicolon can lead to syntax errors.
- Not using braces: It's essential to use braces
{ }to enclose the code blocks for if, else, and switch statements. Without them, your program may behave unexpectedly.
- Comparing with assignment operator (=) instead of equality operator (==): Always use the equality operator to compare values in C programming.
- Not breaking out of a switch case: If you don't use
breakstatements inside yourswitchcases, the program will execute all subsequent cases until it encounters abreak.
- Misusing logical operators: Be careful when using logical operators like
&&and||, as they have different precedence levels and can lead to unexpected results if not used correctly.
Practice Questions
- Write a program that checks if a number is even or odd using an
if-elsestatement. - Modify the grade calculation program to handle marks from 0 to 100 and output grades A+, A, B+, B, C, D, E, F accordingly.
- Write a program that checks if a year is a leap year using a
switchstatement. - Write a program that asks the user for two integers and checks if they are equal or not using nested
ifstatements. - Write a program that calculates the factorial of a number using recursion and an
ifstatement to check for base cases. - Write a program that sorts three numbers in ascending order using
if-elsestatements. - Write a program that checks if a given character is a vowel or consonant using a
switchstatement. - Write a program that asks the user for their age and determines if they are eligible to vote based on their country's voting age requirement (e.g., 18 in the United States).
FAQ
What happens if I forget the braces in an if-else statement?
If you forget the braces in an if-else statement, the code outside the if block will be executed regardless of the condition's truth value. This can lead to unexpected behavior and bugs.
Can I use multiple conditions in an if statement?
Yes, you can use multiple conditions in an if statement using logical operators like && (and) or || (or). However, it's often more readable to break down complex conditions into separate if-else statements.
What is the purpose of the default case in a switch statement?
The default case in a switch statement catches any values that don't match any other cases. If you omit the default case, the program will not output anything for unmatched values unless you explicitly handle them with an else clause.
Why should I use braces in if-else statements?
Using braces in if-else statements ensures that your code is properly indented and easier to read. It also prevents unexpected behavior due to missing or extra blocks of code.
What are the common logical operators in C programming?
The most common logical operators in C programming are && (and), || (or), and ! (not). These operators can be used in if statements to combine multiple conditions.