Thursday, August 23, 2018

Decision N Control Structures


Decision Structures

Every programming language provides some kind of mechanism to control flow of program during its operation. Two such mechanisms are decision making structures and flow control structures in C language.

These two mechanisms have keywords and structures and allow programmer to

-          Transfer control to another segment of code [goto statement]

-          Transfer control to another functions [if, if..else]

-          To repeat certain tasks number of times [while(), do…while(), for() ]

-          To make decisions about program flow [switch_case_default ]

in C language.

The if statement

This statement is used where only one condition is to be checked. The general form of if statement is as shown below. Here condition is any valid C language expression.

The single statement if structure does not need { & }.

Examples:

if ( condition )

          statement;

if (ans == ‘y’)

     printf(“Program exits…\n”);

Mulitiple statements if structure need { & }.

 

if ( condition )

{

          statement1;

          statement2;

          ……

}

if ( addData == TRUE )

{

     name = StudentName;

     age = StudentAge;

     ……

}

The if-else statement

This if-else statement breaks program flow into two parts. The general form of if-else statement is as shown below. Here condition is any valid C language expression.

The single statement if-else structure does not need { & }.

Examples:

if ( condition )

          statement1;

else

          statement2;

 

if ( a > b)

     printf(“a is bigger.\n”);

else

     printf(“b is bigger.\n”);

Mulitiple statements if-else structure need { & }.

 

if ( condition ){

          statement1;

          statement2;

          ……

          }

else {

          statement1;

          statement2;

          ……

          }

if ( Gender == MALE ){

     Affix = “Mr.”;

     Salary = 25000;

     ……

     }

else {

     Affix = “Mrs.”;

     Salary = 20000;

     ……

     }

The Nested ifs

The if statement may be nested as deeply as you need to nest it. One block of code will only be executed if two conditions are true.

The single statement if structure does not need { & }.

Examples: both ifs are true then big=a;

if ( condition1 )

          if ( condition2 )

                   statement;

if (a > b)

     if (a > b)

          big = a;

It is also possible to nest if else for any deeper level [with compiler limitation] to achieve many branch code. It is evident by seeing below picture and the example table. Such nested if-else structures must be ended with else statement, otherwise code gets hang.

The single statement nested if-else structure does not need { & }.

Examples:

if ( condition1 )

          statement1;

else if ( condition 2 )

          statement2;

else if ( condition 3 )

          statement3;

…..

else

          statementN;

if ( a >90)

     printf(“a is bigger than 90\n”);

else if ( a > 80)

     printf(“a is bigger than 80\n”);

else if ( a > 70)

     printf(“a is bigger than 70\n”);

……..

else

     printf(“a is smaller than 10\n”);

The Ternary Operator

The shorthand notation of if else construct is called as ternary operator. This is the place where three expressions are used in single construct.

The single statement if-else structure does not need { & }.

Examples:

if ( exp1 )

          exp2;

else

          exp3;

 

if ((num % 2 )==0)

     even = TRUE;

else

     even = FALSE;

Equivalent Ternary Operator

 

exp1 ? exp2 : exp3 ;

even = ((num % 2 )==0) ? TRUE : FALSE ;

The switch constructor

The state machines needs to change their state according to present mode of system, viz., monitor mode to control mode or decision mode or execution mode etc. In such cases switch constructor is used. The evident example for usage of this constructor is menu block, where it has to change its state according to option chosen.

The goto statement

This keyword just transfer control to another segment of code unconditionally and can be placed anywhere in code block. Therefore, minimizing its use is best option as it makes debug and code reading very hard. It is recommend only when jump is within short code block, say one screen length code.

Control Structures

Often in code computations, it needs to perform a set of instructions repeatedly. This involves repeating either some portion of the program a specified number of times or until a particular condition is being satisfied. This repetitive operation is done through a loop control statement.

C language has three distinct structures, for controlling repetition:

  1. The for loop
  2. The do…while loop
  3. The whie loop

Any of these can repeat either an instruction, a series of instructions, or an entire program.

for LOOP

Use for loop when you know the exact number of repetitions you want to perform. The syntax of the loop is given in below figure. The three elements of loop are separated by semi-colon as they are three statements of it.

for ( initialization; condition; action)

{

Statements;

}

This step is carrying out only once & is optional.

Loop repeats due to this test & is mandatory.

This optional step helps to take action on some elements.

 

All sections may contain many elements.

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

{

printf(“%d”,i);

}

 

for (        ; num < 10 ; num++, k+=2)

{

printf(“%d”,num);

}

 

for (        ; i < 10 ;               )

{

printf(“%d”,i);

}

In embedded systems small delay is created using simple for loop which does nothing for certain milliseconds period. The only semi-colon [or null statement] is body of the for loop, so the loop repeats for 1000 times and does nothing but increments delay value by one.

for (int delay =0 ; delay < 1000 ; delay++)  ;

The dangerous for loop construct is without any elements in all three expressions. Such loop hangs the system as condition is always satisfied and thus it never comes out of it.

for ( ;  ;  ) { printf(“Inside Infinite Loop\n”);

Nested for LOOP

When one for loop is performed within another, they are said to be nested. Such Nested Loops are used to create data table or traverse through arrays.

for (int  i =0 ; i < 10 ; i++)        //outer loop

{

     for (int j=0; j < 10 ; j+=2)      //inner loop

     {

     printf(“*”);

     }

}

do..while Loop

Use this loop when code do not know the exact number of repetitions but want to perform the loop at least once. Here loop is execute once in beginning even if condition is false, and such loop is used to repeat the code until the program decides there is no more input. Note that while() statement ends with semicolon.

do{

          statement1;

          statement2;

          statement2;

          ……

     } while ( condition ) ;

do{

     printf(“Input Temp Value”);

     get it, convert it & display it;

     printf(“yet another one?”);

     ans = getchar();

     } while(ans==‘y’ || ans == ‘Y’);

 

int n = 2 ;

do {

     printf(“ INDIA is great!”);

     n -- ;

     }while ( n < 1 );

This code shows how do..while structure executes its code at least once. Initially n=2, loop enters, printf() prints, n = 2-1=1, now condition is checked, 1<1 = False, so loop exited.

Output:

INDIA is great!

 

     

 

The while Loop

Use this structure when loop is to be executed only when test condition is true, otherwise skip the loop. Therefore, the test condition done first then loop body follows it.

while ( condition ) {

          statement1;

          statement2;

          statement2;

          ……

          }

int n = 1;

while (n <= 100) {

     printf ( “ %d ” , n ) ;

     }

above code is in infinite loop as n =1 and test condition is always true!

The break statement

This statement is use to terminate the loop. When break keyword is encounter inside any loop, control automatically passes to the first statement after the loop. This provides a convenient way to terminate the loop if an error or other irregular condition is encounter. This is a reserved word or keyword hence it is used as statement by simply writing break and terminate with semi-colon. The break statement can be used within – while loop, do..while loop and for loop.

while ( i <= num/2  )

      {

     if ( num % i == 0 )

          {

          flag = 0;

          printf ( “ Number is not a prime.”);

          break;

          } //end of if()

     i ++ ;

     } //end of while()

if(flag)

     printf ( “ Number is a Prime” );

 

 

The continue statement

This statement is use to bypass certain set of code lines in the loop. When continue keyword encountered inside any loop, control automatically passes to the beginning of the loop. This is a reserved word or keyword, hence is used as statement [by simply writing continue and terminate with semi-colon]. The continue statement can be used within – while loop, do..while loop and for loop.

num = 10;

for ( i =1;  i <= num ; i++ )

      {

     if ( i % 5 == 0 )

//if num% 5 bypass below code

          continue;

     else

          printf ( “ %6d ” , i );

     }

 

output:

1    2    3    4    6    7   8   9

 

The exit() function

This in-built library function terminates the program and gives control back to shell or kernel. This function can be call from anywhere in C program to terminate the program without any pre-requisite conditions. This function actually declared in <stdio.h> file, so it is mandatory to include this header file. Otherwise compiler reports error, and code does not compile. This function can be call with error code, so that program handler can read it to know the exit status: whether healthy exit or with some error [command in Cygwin:echo $? after program run].

{….

num = 10;

for ( i =1;  i <= num ; i++ )

      {

     if ( i % 5 == 0 )

//if num% 5 bypass below code

          exit();

     else

          printf ( “ %6d ” , i );

     }

getch(); // to pause program

}//end of main()

output:

1    2    3    4   

[getch() is bypassed & console returns to shell prompt]

 


Previous Page Main Contents Next Page

No comments:

Post a Comment