C Decision Making

Decision-making structures require the programmer to specify one or more conditions to be evaluated or tested, along with statements to be executed if the condition is true (required) and statements to be executed if the condition is false (optional).

The C language treats anynon-zeroandnon-nullThe value is assumed to betrue, takezeroornullassumed to befalse。

The following is the general form of a typical decision-making structure in most programming languages:

C 中的判断语句

Decision Statements

The C language provides the following types of decision-making statements. Click the links to view the details of each statement.

statementDescription
if statementaif statementConsists of a Boolean expression followed by one or more statements.
if...else statementaif statementcan be followed by an optionalelse statement, the else statement executes when the Boolean expression is false.
Nested if StatementsYou can in aiforelse ifuse another within a statementiforelse ifstatement.
switch statementaswitchThe statement allows testing whether a variable equals multiple values.
Nested switch StatementsYou can in aswitchuse another within a statementswitch statement.

? : operator (ternary operator)

We have already explained in previous chaptersConditional Operator ? :, can be used to replaceif...elsestatement. Its general form is as follows:

Exp1 ? Exp2 : Exp3;

Here, Exp1, Exp2, and Exp3 are expressions. Note the usage and placement of the colons.

The value of the ? expression is determined by Exp1. If Exp1 is true, then Exp2 is evaluated, and the result is the value of the entire expression. If Exp1 is false, then Exp3 is evaluated, and the result is the value of the entire expression.

Example

The following example determines whether a number is odd or even by inputting a number

Example

#include<stdio.h> int main() { int num; printf("Enter a number:"); scanf("%d",&num); (num%2==0)?printf("Even number"):printf("Odd number"); }
other extensions