The generalized grammar for if / else if / else statements is as follows. First, the series must begin with an if. You cannot begin with else if or else, they must be connected to a starting if. Second, if's and else if's must be followed directly by a set of parenthesis and a conditional expression within the parenthesis. Recall that a conditional expression will yield a zero (representing true) or non-zero (representing false) result or will simply be a literal zero or non-zero value. The if, else if, and else will all be followed by a connected statement block, marked by the open and closing pair of curly brackets. Example syntax for each is given here.
if (expression) {
// the statements to execute if the expression is true
}
if (expression) {
// the statements to execute if the expression is true
}
else {
// the statements to execute if the expression is false
}
if (expression1) {
// the statements to execute if expression1 is true
}
else if (expression2) {
// the statements to execute if expression2 is true
}
// ...
else if (expressionN) {
// the statements to execute if expressionN is true
}
else {
// the statements to execute if expression1, expression2, and expression3 are all false
}
if (number < 0) {
printf("Negative");
}
if (number < 100) {
printf("Less than 100");
}
if (number >= 100) {
printf("Greater than or equal to 100");
}
if (number < 0) {
printf("Negative");
}
else if (number < 100) {
printf("Less than 100");
}
else if (number >= 100) {
printf("Greater than or equal to 100");
}