Decision Making in C
Hey there! In this guide, we'll explore decision-making in C. Decision-making structures allow you to execute different blocks of code based on certain conditions. Let's dive in!
- Decision-making structures allow you to execute different blocks of code based on certain conditions.
- C provides several constructs for decision-making, including
if,else,else if, andswitch.
Video Explanationโ

1. The if Statementโ
Syntax:โ
if (condition) {
// code to be executed if condition is true
}
Example:โ
#include <stdio.h>
int main() {
int num = 10;
if (num > 0) {
printf("The number is positive.\n");
}
return 0;
}
2. The if...else Statementโ
Syntax:โ
if (condition1) {
// code to be executed if condition1 is true
} else {
// code to be executed if condition1 is false
}
Example:โ
#include <stdio.h>
int main() {
int num = -5;
if (num > 0) {
printf("The number is positive.\n");
} else {
printf("The number is not positive.\n");
}
return 0;
}
3. The if...else if...else Statementโ
Syntax:โ
if (condition1) {
// code to be executed if condition1 is true
} else if (condition2) {
// code to be executed if condition2 is true
} else {
// code to be executed if both conditions are false
}
Example:โ
#include <stdio.h>
int main() {
int num = 0;
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;
}
4. The switch Statementโ
Syntax:โ
switch (expression) {
case value1:
// code to be executed if expression == value1
break;
case value2:
// code to be executed if expression == value2
break;
default:
// code to be executed if expression doesn't match any case
}
Example:โ
#include <stdio.h>
int main() {
int day = 3;
switch (day) {
case 1:
printf("Monday\n");
break;
case 2:
printf("Tuesday\n");
break;
case 3:
printf("Wednesday\n");
break;
default:
printf("Not a valid day\n");
}
return 0;
}
5. Nested if Statementsโ
Example:โ
#include <stdio.h>
int main() {
int num = 15;
if (num > 10) {
printf("The number is greater than 10.\n");
if (num > 20) {
printf("The number is also greater than 20.\n");
}
}
return 0;
}
6. Conditional Operatorsโ
C++ also supports conditional operators for compact decision-making.
Ternary Operatorโ
(condition) ? expression1 : expression2;
Example:โ
#include <stdio.h>
int main() {
int num = 10;
const char* result = (num > 0) ? "Positive" : "Non-positive";
printf("%s\n", result);
return 0;
}
Understanding decision-making structures in C is crucial for controlling the flow of your program and executing different actions based on conditions. Happy coding!
Track Your Progress
Done with this topic? Mark it as complete to track your progress.