c programming control flow statements

A statement is an instruction that causes an action to be performed when executed. The C statements end with ‘;’.

In C there are 6 types of statements are available.

  1. Selection statement
  2. Iteration statement
  3. Jumping statements
  4. Label statements
  5. Expression statement
  6. Block statement

Decision control instructions in C

We have seen that a C program is a set of statements which are normally executed sequentially in the order in which they appear. By default, the instructions in a program are executed sequentially.

In serious programming situations, we want a set of instructions to be executed in one situation, and a different set of instructions to be executed in another situation. This kind of situation is dealt with in C programs using decision control instruction.

A decision control instruction can be implemented in C using

If statement

The if statement is a powerful decision-making statement and is used to control the flow of execution of the statement.The keyword if tells the compiler that what follows is a decision control instruction.

The condition following the keyword if is always enclosed within a pair of parentheses. If the condition, whatever it is true, then the statement is executed.If the condition is not true, then the statement is not executed.

As a general rule, we express a condition using C’s ‘relational and logical operators’. The if statement may be implemented in different forms depending on the complexity of conditions to be tested. The different forms are:

Simple if Statement

The below figure describes the general form of a simple if statement. The ‘statement-block’ may be a single statement or a group of statements. If the condition is true, the statement block will be executed otherwise the statement-block will be skipped and the execution will jump to the statement-x. Remember, when the condition is true both the statement-block and statement-x are executed in sequence.

[quote]Note: In simple, if statement, only one statement is there no need to open body.[/quote]

Simple if syntax:[quote]

if ( condition )
{

       statement-block;
}

Statement-x;[/quote]

if-else Statement

The if statement by itself will execute a single statement or a group of statements when the if condition true. When the condition is false, can we execute another group of statements? This is the purpose of else statement. The if-else statement is an extension of the simple if statement. The below figure describes a general form of if else. If the condition is true, the true-block statement(s), immediately following the if statements are executed; otherwise, the false-block statement(s) are executed.

If-else syntax

if ( condition )
{ 
   TRUE-Block…statement (s);
}
else
{
  FALSE-Block……statement (s);
}
Nested if-else Statement

When a series of decisions are involved, we may have to use more than one if-else statement in nested form. If the condition-1 is false, the statement-3 will be executed; otherwise, it continues to perform the second condition. If the condition-2 is true, the statement-1 will be evaluated; otherwise, the statement-2 will be evaluated and then the control jumps to statement-4.

[quote]Note: Else is always matching with the most recent unpaired if.[/quote]

if ( condition-1 )
{
     if( condition-2 )
     {
        statement1;
     }
     else
     {
          statement2;
      }
}
else
{
     statement3;
}
statement4;
Different Forms of if – else
if ( condition)

statement1;

if ( condition ) {

    statement1;

     ………….n;

}

if ( condition)

statement1;

else

statement2;

if ( condition) {statement1;

……..n;

}

else {

 statement1;

………n;

}

Conditional operator

The conditional operators ? and : are sometimes called ternary operators since they take three arguments. Their general form is,
expression 1 ? expression 2 : expression 3;

What this expression says is: “if expression 1 is true ( that is if its value is nonzero), then the value returned will be expression 2, otherwise the value returned will be expression 3”.

[quote]Note:

[/quote]

Switch statement

The control statement that allows us to make a decision from the number of choices is called a switch.

Rules for switch statement:

[quote]Note:

[/quote]

The integer expression following the keyword switch is any C expression that will yield an integer value or characters. It could be an integer constant or an expression that evaluates to an integer. The keyword case is followed by an integer or a character constant. Each of these values should be unique. Block-1, block-2.. are statement lists and may contain zero or more statements. There is no need to put braces around these blocks. Note that case labels must end with a colon (:).

What happens when we executed a program containing a switch? First, the integer expression following the keyword switch is evaluated, and compared against the values constant1, constan2,… if a matching case is found then the block of statements that follows the case is executed up to break(optional if it is there) or all statements from matching case including default, and transferring the control to the statement-x following the switch.

The default is an optional case. It will be executed if the value of the integer expression does not match with any of the case values. If not present, no action takes place if all matches fail and the control goes to the statement-x.

switch ( integer expression )
{
     case constant1:
       block-1;
       break;
     case constant2:
       block-2;
       break;
     ………….
     default:
      statement;
      break;
}
statement-x;

goto statement

The goto statement to branch unconditionally from one point to another point in the program. The goto requires a label in order to identify the place where the branch is to be made.

A label is any valid variable name and must be followed by a colon. The label is placed immediately before the statement where the control is to be transferred. The general form of goto and label statements is shown below:

Note that a goto breaks the normal sequential execution of the program. If the lable: is before the statement goto label; a loop will be formed and some statements will be executed repeatedly. Such a jump is known as a backward jump. On the other hand, if the label: is placed after the goto label; some statements will be skipped and jump is known as a forward jump.

goto label;
  ………….
  ………….
label:
  statement;label:
  statement;
.…………
………….
goto label;

Decision making and looping

In all programs written so far, execution begins at the start of the main( ) function and proceeds line by line until the end of the program. But if you want to print something repeatedly, say printing something on screen five times, you can include 5 print statements. But if you want to print 100 times it cannot be done like this. To do repetitive tasks, we use loops.

In C there are three types of loops. Such as,

Looping Process includes four steps. They are As follows,

while Loop

The while statement will be executed repeatedly as long as the Expression Remains true. Its syntax is as follows,

The body of the loop will be executed repeatedly as long as the condition remains true. When the while is reached, the computer evaluates condition. If it is found to be false, the body of the loop will not be executed, and the loop ends. Otherwise, the body of the loop will be executed, and then the condition is checked again and so on until the condition becomes false.

The syntax for while:

while(condition)
{    
  ..statement1;
   body of loop;
}
/* Ex1: calculating sum of first 5 Natural numbers */ 
#include <stdio.h> 
void main() 
{ 
    int i,sum=0;sum=0; 
    i=1; /* initialization */ 
    while( i<=5) /* condition */ 
    { 
        sum=sum+i; 
        i=i+1; /* incrementing */ 
    } 
    printf("sum=%d",sum); 
}

The code given above finds the sum of the first 5 Natural numbers. The execution of this while statement is don as follows,

do-while Loop

It is similar to while loop except that it always executes at least once. The test of expression for repeating is done after each time body of the loop is executed. The syntax for do-while is as follows,

Syntax for do-while:

do
{     
   ….statement1;
   body of loop;
}while(condition);
/* Ex2: calculating sum of first 5 Natural numbers */ 
#include <stdio.h> 
void main() 
{ 
    int i,n,sum; 
    printf("ENTER A NUMBER"); 
    scanf("%d",&n); sum=0; 
    i=1; /* initialization */ 
    do{ 
        sum=sum+i; 
        i=i+1; /* incrementing */ 
    } while( i<=n); /* condition */ 
    printf("\nsum=%d",sum); 
}

[quote]Output:
ENTER A NUMBER 5
sum=15[/quote]

The below example is used to find sum numbers from 1 to given input numbers this do-while loop is executed as given below,

for Loop

For statement is another type of looping statement. the difference between for and while, the do-while statement is that, in while statements that the number of passes is not known in advance whereas in for- statement the number of passes is known in advance. The general syntax to for loop is

Syntax of for loop:

for( initialization; condition ; iteration )
{
      ….statement1;
     body of loop;
}

This loop contained three parts; these are

It is possible to omit all the three expressions in the for a statement but it is necessary to have two semicolons. If assignment expression and unary expression are omitted, then another way should be present to initialize and modify the initial value. If the conditional expression is omitted then it is assumed that it has a static value 1 witch it true.

This static value makes the looping structure to be executed infinitely until terminated by using a break or return statement.

/* Ex1: calculating sum of first 5 Natural numbers */ 
#include <stdio.h> 
void main() 
{ 
    int i,n,sum; 
    printf("ENTER A NUMBER"); 
    scanf("%d",&n); 
    sum=0; 
    for( i=1 ; i<=n ; i++ ) 
    { 
        sum=sum+i; 
    } 
    printf("\nsum=%d",sum); 
}

[quote]Output:
ENTER A NUMBER 5
sum=15[/quote]

The above loop where i=1 is an expression that specifies the initial value and that controls the looping action. i<=5 is a condition, that is tested at each pass. The program is executed until this condition remains true. i++ is a unary expression, that is either increment or decrement to change the initial value. The conditional expression is evaluated and tested at the beginning while unary expression is evaluated at the end of each pass.

Nesting the loops

Nesting of the loop, that is one loop statement placing into another loop.

while ( condition )
{
       while loop body;
       for( initialization; condition ; iteration )
       {
             for loop body;
        }
}

break and continue

break and continue are an unconditional statement which is used within a program to alter the flow of control.

break: ‘break’ is a keyword used to terminate the loop or exit from a switch statement. It is written as,
statements; break;

/* Ex1: Take char intput from user choice and prints */ 
#include <stdio.h> 
void main() 
{ 
    char choice; 
    scanf("%c",&choice); 
    switch(choice) 
    { 
        case 'y': 
            printf("yes"); 
            break; 
        case 'n': 
            printf("no"); 
            break; 
    } 
}

Here break statement is used in order to transfer control out of switch statement.

#include <stdio.h> 
void main() 
{ 
    int i; i=1; 
    while( i<5 ) 
    { 
        if( i%2==0) 
        break; 
        i++; 
    } 
}

when i=2, i%2==0
Hence, the break statement is executed and the loop terminates.

continue: ‘Continue’ is a keyword used to Skip the same specific statement in the loop body. It must be used with while, for and do-while.

#include <stdio.h> 
void main() 
{ 
    int i; 
    i=0; 
    while(i <= 100) 
    { 
        i+=2; 
        if( i>40 && i<60) 
            continue; 
        printf("%d ",i); 
    } 
}

In the above loop, when the value of ‘i’ is 42, continue statement is executed. So, i=i+2 is skipped and control is transferred to the beginning of while loop.