if STATEMENTS ( c )

 

C allows decisions to be made by evaluating a given expression as true or false. Such an expression involves the relational and logical operators. Depending on the outcome of the decision, program execution proceeds in one direction or another. The C statement that enables these tests to be made is called the if statements.

 

 

The if statements may be implemented in different forms depending on the complexity of conditions to be tested. They are :

 

  1. Simple if statement
  2. if . . . else statement
  3. Nested if . . . else statement
  4. else if ladder

 

Simple if Statement

 

The simple if statement is used to specify conditional execution of program statement or a group of statements enclosed in braces. The syntax is :

 

          if (test condition)

          {

statement-block ;

          }

          statement-x ;

 

 

When an if statement is encountered, test condition is evaluated first and if it is true, the statement-block will be executed. If the test condition is false, the statement-block will be skipped and the execution will jump to the statement-x.

 

When the test condition is true, both the statement-block and the statement-x are executed in sequence. The test condition is always enclosed within a pair of parenthesis. The statement-block may be a single statement or a group of statements.

 

The figure below shows the flowchart of simple if statement :

 

Table below shows the various expressions that are used as conditions inside an if statement :

 

Conditional Expression

Meaning

For e.g.,

Value of a

For e.g.,

Value of b

Result

a == b

a is equal to b

5

5

5

3

True

False

a != b

a is not equal to b

5

5

3

5

True

False

a < b

a is less than b

3

5

5

3

True

False

a > b

a is greater than b

5

3

3

5

True

False

a <= b

a is less than or equal to b

3

3

5

5

3

3

True

True

False

a >= b

a is greater than or equal to b

5

5

3

3

5

5

True

True

False

 

Two or more conditions may be combined in an if statement using a logical AND operator (&&) or a logical OR operator (||). It can compare any number of variables in a single if statement.    Table below shows the various expressions that are used as conditions inside an if statement :

 

Conditional Expression

 

Meaning

For e.g.,

Value of a

For e.g.,

Value of b

For e.g.,

Value of c

 

Result

((a>b) && (b>c))

a is greater than b AND b is greater than c

30

20

10

True

30

10

20

False

10

30

20

False

10

20

30

False

((a>b) || (b>c)

a is greater than b OR b is greater than c

30

20

10

True

30

10

20

True

10

30

20

True

10

20

30

False

 

Note : There is only one statement in the if block, the braces are optional. But if there is more than one statement you must use the braces.

 

 

 

 

Registration


A password will be e-mailed to you.

Feedback Form

Name (required)

Email (required)

Feedback