Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

C Judgment

C Judgment

A decision structure requires the programmer to specify one or more conditions to be evaluated or tested, along with a statement (required) to execute if the condition is true and an optional statement to execute if the condition is false.

C treats anynon-zeroandnon-nullvalue as true, and treatszeroor null as false.

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

Decision Statements

C provides the following types of decision statements. Click the links to see the details of each statement.

Statement Description
if statement A if statement if statement consists of a Boolean expression followed by one or more statements.
if...else statement A if statement An if statement can be followed by an optional else statement, which executes when the Boolean expression is false.
Nested if statements You can use one if or else if if statement inside another if or else if if statement.
switch statement A switch A switch statement allows testing a variable against multiple values.
Nested switch statements You can use one switch You can use another **switch** statement inside a switch statement.

? : operator (ternary operator)

We have explained the conditional operator ? :in a previous chapter, which can be used to replace if...else an if...else statement. Its general form is as follows:



Exp1 ? Exp2 : Exp3;

Here, Exp1, Exp2, and Exp3 are expressions. Note the use and position of the colon.

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

Example

The following example determines whether an input number is odd or even

Example

#include

<

stdio.h

int

main

(

)

{

int

num

;

printf

(

"

Enter a number :

"

)

;

scanf

(

"

%d

"

,&

num

)

;

(

num

%

2

==

0

)

?

printf

(

"

Even

"

)

:

printf

(

"

Odd

"

)

;

}