If, If-else, else-if
if statement:
An if
statement in C is a control structure used to perform conditional execution of code. It allows the program to execute a block of code only if a specified condition evaluates to true. If the condition is false, the code inside the if
block is skipped.
if (condition) {
// Code to execute if condition is true
}
- Example: Checking if a Number is Positive
#include <stdio.h>int main() {
int number;
// Prompt user for input
printf(“Enter a number: “);
scanf(“%d”, &number);
// If statement to check if the number is positive
if (number > 0) {
printf(“The number is positive.\n”);
}
return 0;
}
- output
Enter a number: 10
The number is positive.
- output
Enter a number: -10
NOTE: NOTHING TO PRINT
if-else statement:
if (condition) {
// Code if condition is true
} else {
// Code if condition is false
}
Example: Checking if a Number is Positive or Negative
#include <stdio.h>
int main() {
int number;
// Prompt user for input
printf(“Enter a number: “);
scanf(“%d”, &number);
// If statement to check if the number is positive or negative
if (number > 0) {
printf(“The number is positive.\n”);
}
else {
printf(“The number is negative.\n”);
}
return 0;
}
- output
Enter a number: 10
The number is positive.
- output
Enter a number: -10
The number is negative.
else if
if (condition1) {
// Code for condition1
} else if (condition2) {
// Code for condition2
} else {
// Code if none of the conditions are true
}