Conditions in C are expressions that evaluate to either true or false. They are used in control structures like if statements to determine the flow of the program.
Relational operators are used to compare two values. Here are the common relational operators in C:
int a = 5;
int b = 10;
// Example 1
if (a > b) {
// Code executes if a is greater than b
}
// Example 2
if (a == 5) {
// Code executes if a is equal to 5
}
Examples of Multiple Conditions in C
int x = 5;
int y = 10;
// Using AND (&&) operator
if (x > 0 && y > 0) {
// Code executes if both x and y are greater than 0
}
// Using OR (||) operator
if (x == 0 || y == 0) {
// Code executes if either x or y is equal to 0
}
Examples of Using if Alone
int age = 25;
if (age >= 18) {
// Code executes if age is 18 or older
}
Examples of Using if with else
int score = 75;
if (score >= 60) {
printf(“Passed!\n”);
} else {
printf(“Failed!\n”);
}
Examples of Using if with else if
int marks = 80;
if (marks >= 90) {
printf(“Grade A\n”);
} else if (marks >= 80) {
printf(“Grade B\n”);
} else if (marks >= 70) {
printf(“Grade C\n”);
} else {
printf(“Grade D\n”);
}
Examples of Using switch
int choice = 2;
switch (choice) {
case 1:
printf(“Option 1 selected\n”);
break;
case 2:
printf(“Option 2 selected\n”);
break;
default:
printf(“Invalid option\n”);
}
Examples of Using Nested if
int num = 15;
if (num > 0) {
if (num % 2 == 0) {
printf(“Positive and even\n”);
} else {
printf(“Positive and odd\n”);
}
} else if (num < 0) {
printf(“Negative\n”);
} else {
printf(“Zero\n”);
}
See the video below how to use IF statements when programming in C:
Published by Active Learning, Dec 2023