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
.
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!