The if statement lets a C program execute code only when a condition is true. Add else for the alternative path, or use an else if ladder when several conditions must be tested in order.
if (condition) {
// runs when condition is true
} else {
// runs when condition is false
}
In C, a condition evaluates as false when its value is zero and true when its value is non-zero. Relational operators such as <, >= and == are commonly used to build conditions.
#include <stdio.h>
int main(void) {
int number;
printf("Enter a number: ");
if (scanf("%d", &number) != 1) {
printf("Invalid input.\n");
return 1;
}
if (number <= 10) {
printf("The number is less than or equal to 10.\n");
} else {
printf("The number is greater than 10.\n");
}
return 0;
}
Key change: only one of the two blocks runs.
An else if ladder is clearer than deeply nesting several if statements when only one range should match.
#include <stdio.h>
int main(void) {
int mark;
printf("Enter a mark from 0 to 100: ");
if (scanf("%d", &mark) != 1) {
printf("Invalid input.\n");
return 1;
}
if (mark < 0 || mark > 100) {
printf("Mark must be between 0 and 100.\n");
} else if (mark >= 80) {
printf("First Division\n");
} else if (mark >= 60) {
printf("Second Division\n");
} else if (mark >= 40) {
printf("Third Division\n");
} else {
printf("Fail\n");
}
return 0;
}
The checks run from the highest range downward. Once one condition is true, the remaining branches are skipped.
#include <stdio.h>
int main(void) {
int number;
printf("Enter a non-negative integer: ");
if (scanf("%d", &number) != 1) {
printf("Invalid input.\n");
return 1;
}
if (number >= 0) {
if (number % 2 == 0) {
printf("%d is even.\n", number);
} else {
printf("%d is odd.\n", number);
}
} else {
printf("The number is negative.\n");
}
return 0;
}
Here the second condition is tested only after the program confirms that the number is non-negative.
== to compare values; = assigns a value.Student grade Highest of three numbers Tariff by consumption range
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.
18-08-2023 | |
| Write an if-else statement to check if the grade is above or equal to 60 | |