Pages

Saturday, February 27, 2010

THE if STATEMENT

Introduction

The if statement is the first selection structure. if is used when a question requires a yes or no answer. If you want to choose an answer from several possibilities then use the switch statement.

Program/Example

The general format for an if statement is:

if ( condition )
simple or compound statement.

Following are the properties of an if statement:

  1. If the condition is true then the simple or compound statements are executed.

  2. If the condition is false it does not do anything.

  3. The condition is given in parentheses and must be evaluated as true (nonzero value) or false (zero value).

  4. If a compound statement is provided, it must be enclosed in opening and closing braces.

Following are the test conditions:

    (7)// a non-zero value returns True.
(0)// zero value returns False.
(i==0) // True if i=0 otherwise False.
(i = 0) // False because value of the expression is
zero.

SCOPE OF AN if CLAUSE

The scope of an if clause determines a range over which the result of the condition affects. The scope of an if clause is on the statement which immediately follows the if statement. It can be a simple statement or compound statement.

Case 1:

if (a>b)
i = i + 1; // s1
j = j + 1; // s2

Case 2:

if (a>b)
{
i = i + 1; // s1
j = j + 1; // s2
}

If in Case 1 the if condition is true, then s1 is executed because s1 is a simple statement.

If in Case 2 the if condition is true, then both statements s1 and s2 are executed because s1 and s2 are enclosed in a compound statement.




No comments:

Post a Comment