Thursday, November 12, 2020

CONTROL FLOW STATEMENTS - Selection / Branching Statements - Iteration / looping statements

The order in which statements are executed in a running program is called the flow of control.

Control flow relates to the order in which the operations of a program are executed.

Control statements embody the decision logic that tells the executing program what action to carry out next depending on the values of certain variables or expression statements.


Selection / Branching Statements

1. IF- Statement:

It is the basic form where the if statement evaluate a test condition and direct program execution depending on the result of that evaluation.

Syntax:

            If (Expression)

            {

            Statement 1;

            Statement 2;

            }

Where a statement may consist of a single statement, a compound statement or nothing as an empty statement. The Expression also referred so as test condition must be enclosed in parenthesis, which cause the expression to be evaluated first, if it evaluate to true (a non zero value), then the statement associated with it will be executed otherwise ignored and the control will pass to the next statement.

Example:

            if (a>b)

            {

            printf (“a is larger than b”);

            }

2.  IF-ELSE Statement:

An if statement may also optionally contain a second statement, the "else clause", which is to be executed if the condition is not met. Here is an example:

The form of a two-way decision is as follows:

if(TestExpr)

            stmtT;

else

            stmtF;

Example:

                    if(n > 0)

                         average = sum / n;

               else        

                              {

                               printf("can't compute average\n");

                               average = 0;

                                         }

3. NESTED-IF- Statement:

It's also possible to nest one if statement inside another. (For that matter, it's in general possible to nest
any kind of statement or control flow construct within another.)

The syntax for the nested if is as follows:

if(TestExprA)

            if(TestExprB)



                        stmtBT;

            else

                        stmtBF;

else

            stmtAF;


For example, here is a little piece of code which decides roughly which quadrant of the compass you're walking into, based on an x value which is positive if you're walking east, and a y value which is positive if you're walking north:

                    if(x > 0)

               {

                               if(y > 0)

                                              printf("Northeast.\n");

                               else        

                                              printf("Southeast.\n");

                               }

               else        

                               {

                               if(y > 0)

                                              printf("Northwest.\n");

                               else         

                                            printf("Southwest.\n");

                               }

4. Switch Case

This is another form of the multi way decision. It is well structured, but can only be used in certain cases where;

       Only one variable is tested, all branches must depend on the value of that variable. The variable must be an integral type. (int, long, short or char).

       Each possible value of the variable can control a single branch. A final, catch all, default branch may optionally be used to trap all unspecified cases.

The general format of a switch statement is



            switch(expr)

            {

            case constant1: stmtList1;

            break;

            case constant2: stmtList2;

            break;

            case constant3: stmtList3;

            break;

            ………………………….

            ………………………….

            default:
            stmtListn;

            }

Hopefully an example will clarify things. This is a function which converts an integer into a vague description. It is useful where we are only concerned in measuring a quantity when it is quite small.

int number;

switch(number) {

        case 0 : 

             printf("None\n");

             break;

        case 1 :             

            printf("One\n");               

            break;

        case 2 :               

            printf("Two\n");              

            break;

        case 3 :

        case 4 :

        case 5 :

                printf("Several\n");              

                break;

        default :

             printf("Many\n");              

break;      

}

Each interesting case is listed with a corresponding action. The break statement prevents any further statements from being executed by leaving the switch. Since case 3 and case 4 have no following break, they continue on allowing the same action for several values of number.

Both if and switch constructs allow the programmer to make a selection from a number of possible actions.

Unconditional Branching statements:

1. The goto Statement

The goto statement is another type of control statement supported by C.

The control is unconditionally transferred to the statement associated with the label specified in the goto statement.

The form of a goto statement is:

                        goto    
                             label_name;

Ex: goto end;

2. The break Statement

We have already met break in the discussion of the switch statement. It is used to exit from a loop or a switch, control passing to the first statement beyond the loop or a switch.

With loops, break can be used to force an early exit from the loop, or to implement a loop with a test to exit in the middle of the loop body. A break within a loop should always be protected within an if statement which provides the test to control the exit condition.

3. The continue Statement

This is similar to break but is encountered less frequently. It only works within loops where its effect is to force an immediate jump to the loop control statement.

       In a while loop, jump to the test statement.

       In a do while loop, jump to the test statement.

       In a for loop, jump to the test, and perform the iteration.

Like a break, continue should be protected by an if statement. You are unlikely to use it very often.



Take the following example:

int i;

for (i=0;i<10;i++)

{

if (i==5)

continue;

printf("%d",i);

if (i==8)

break;

}

This code will print 1 to 8 except 5.

Continue means, whatever code that follows the continue statement WITHIN the loop code block will not be exectued and the program will go to the next iteration, in this case, when the program reaches
i=5 it checks the condition in the if statement and executes 'continue', everything after continue, which are the printf statement, the next if statement, will not be executed.

Iteration / looping statements:

Loop allows one to execute a statement or block of statements repeatedly.

C has three loop constructs: while, for, and do-while.

The first two are pre-test loops and do-while is a post-test loop.

1. While Loop

Loops generally consist of two parts: one or more control expressions which (not surprisingly) control the execution of the loop, and the body, which is the statement or set of statements which is executed over and over.

The general syntax of a while loop is :




                Initialization

            while( expression )
            {
                        Statement1
                        Statement2
                        Statement3
                                   
            }

The most basic loop in C is the while loop. A while loop has one control expression, and executes as long as that expression is true. 


This example repeatedly doubles the number 2 (2, 4, 8, 16, ...) and prints the resulting numbers as long as they are less than 1000:

            int x = 2;

            while(x < 1000)

                        {

                        printf("%d\n", x);

                        x = x * 2;

                        }


2. Do  while Loop

 This is very similar to the while loop except that the test occurs at the end of the loop body. This
guarantees that the loop is executed at least once before continuing. Such a setup is frequently used where data is to be read. The test then verifies the data, and loops back to read again if it was unacceptable.


      The form of this loop construct is as follows:

            do

            {

            stmT;

            }while(TestExpr);



do

{   

   printf("Enter 1 for yes, 0 for no :");

        scanf("%d", &input_value);

} while (input_value != 1 && input_value != 0)

3. For Loop



The general syntax of a for loop is

for( Initialization;expression;Increments/decrements )

{

                        Statement1

                        Statement2

                        Statement3                  

}

Initialization This part of the loop is the first to be executed. The statement(s) of this part are executed only once. This statement involves a loop control variable.

expression  represents a test expression that must be true for the loop to continue execution.

Statement is a single or block of statements.

Increment/decrement The statements contained here are executed every time through the loop before the loop condition is tested. This statement also involves a loop control variable.

Ex: 

            for (i = 0; i < 10; i = i + 1)

                        printf ("i is %d\n", i);

0 comments:

Post a Comment

Data Structures with C++



NET/SET/CS PG



Operating Systems



Computer Networks



JAVA



Design and Analysis of Algorithms



Programming in C++

Top