if: If statement

Package: language

Syntax

if (expression) statement1 [else statement2]

Elements

expression
A boolean valued expression.
statement1, statement2
The statements to be executed (possibly compound, i.e., enclosed in curly braces).

Description

The if statement is used to execute a statement only if the specified condition is true. An optional else clause may be given to execute a different statement if the condition is false.

Examples

1. Add X to Y only if X is less than Y.

if (x < y)
    y += x

2. If X is less than 10 print "small", else print "big".

if (x < 10)
    print ("small")
else
    print ("big")

3. The else if construct.

if (str == "+")
    val += x
else if (str == "-")
    val -= x
else if
    ...

4. Nesting, use of braces.

if (i > 0) {
    if (i < 10) {
        print ("0")
        sum = sum * 10 + i
    } else
        print (" ")
}

See also

for, case, break, next