C else statement
Created By: chatGPT
C programming provides the
else
statement as part of its control flow structure, which allows you to execute a block of code when the condition in the if
statement is false. The else
statement is often paired with an if
to handle alternative scenarios in your program. Here’s a simple demonstration of how to use the else
statement.if (condition) {
// code to be executed if condition is true
} else {
// code to be executed if condition is false
}
Consider the following example where we check a number to determine if it's positive or negative.
#include <stdio.h>
int main() {
int number;
printf("Enter a number: ");
scanf("%d", &number);
if (number > 0) {
printf("The number is positive.\n");
} else {
printf("The number is negative or zero.\n");
}
return 0;
}
In this code snippet, we first prompt the user to enter a number and then check if that number is greater than zero. If it is, a message confirming that the number is positive is printed. If the condition is not met, the
else
statement executes, indicating that the number is either negative or zero.// Sample Output:
// Enter a number: 5
// The number is positive.
// Enter a number: -3
// The number is negative or zero.