Decision-making with if
In C programming, the `if` statement is used for decision-making based on certain conditions. It allows you to execute a block of code if a specified condition is true, and optionally, execute a different block of code if the condition is false.
The basic syntax of the `if`statement in C is as follows:
if (condition) {
// code to execute if condition is true
}
The `condition` is an expression that evaluates to either true or false. If the condition is true, the code block enclosed within the curly braces will be executed. If the condition is false, the code block will be skipped, and the program will continue with the next statement after the `if` block.
Here's an example to illustrate the usage of `if` statement:
#include <stdio.h>
int main() {
int num = 10;
if (num > 0) {
printf("The number is positive.\n");
}
printf("Program complete.\n");
return 0;
}
In this example, if the value of `num` is greater than 0, the message "The number is positive." will be printed. Otherwise, it will be skipped, and the message "Program complete." will always be printed.
You can also use an `else` clause with the `if` statement to specify a block of code to execute when the condition is false. Here's an 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");
}
printf("Program complete.\n");
return 0;
}
In this example, if the value of `num` is greater than 0, the first `printf` statement will be executed. Otherwise, the second `printf` statement within the `else` block will be executed.
You can also use multiple `else if` clauses to test multiple conditions.
Here's an 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");
}
printf("Program complete.\n");
return 0;
}