In C programming language, you can use nested if statements to create more complex conditional logic. A nested if statement is simply an if statement inside another if statement. The syntax of a nested if statement is as follows:
if (condition1) {
// code to execute when condition1 is true
if (condition2) {
// code to execute when both condition1 and condition2 are true
}
else {
// code to execute when condition1 is true but condition2 is false
}
}
else {
// code to execute when condition1 is false
}
Here, the inner if statement is only executed if the outer if statement’s condition is true. If the inner if statement’s condition is also true, its code block is executed. Otherwise, the else block of the inner if statement is executed. If the outer if statement’s condition is false, the else block of the outer if statement is executed. For example, let’s say we have two integer variables x and y, and we want to print a message that says whether x is positive, negative, or zero, based on the value of y. We can use nested if statements as follows:
if (y > 0) {
if (x > 0) {
printf("x is positive.\n");
}
else if (x < 0) {
printf("x is negative.\n");
}
else {
printf("x is zero.\n");
}
}
else if (y < 0) {
if (x > 0) {
printf("x is negative.\n");
}
else if (x < 0) {
printf("x is positive.\n");
}
else {
printf("x is zero.\n");
}
}
else {
printf("y is zero.\n");
}
In this example, we have used nested if statements to handle three cases based on the value of y: y > 0, y < 0, and y = 0. For each case, we have used another set of if statements to determine whether x is positive, negative, or zero.
Learners TV is a website that is designed to educate users and provide instructional material on particular subjects and topics.