MAP

DECISION CONTROL STRUCTURE IN C LANGUAGE


The if-else statement:

The if-else statement is used to carry out a logical test and then take one of two possible actions depending on the outcome of the test (i.e. whether the outcome is true or false).The else position of the if-else statement is optional. Thus, in its simplest general form, the statement can be written.

If (expression)
 statement;

The expression must be placed in parenthesis, as shown. In this form, the statement will be executed only if the expression has non-zero value (i.e. true). If the expression has a value of zero (i.e. expression is false), then the statement will be ignored. The statement can be either simple or compound. In practice, it is often compound statement, which may include other control statements.




The general form of an if statement which include the else clause is

Text Box: If(expression) 
statement 1;
else
 statement 2;
If the expression has a non-zero value (i.e. if expression is true), then statement 1 will be executed. Otherwise,  (i.e. expression is false), statement 2 will be executed. It is possible to next if…else statement within one-another, just as we did with loops, there are several different forms that nested if…else two-layer nesting is : In this situation, one can complete if…else statement will be executed if expression is nonzero(true) and another complete if else statement will be executed if expression is false (zero). It is of course, possible that statement 1, statement2, statement3 and statement4 will contain another if…else statements. We would then have multi layer nesting. Some other forms of two layer are:


                       
 
If<exp1>                    
{
                        statement1;
}
else
{
                        if<exp2>
                        {
            statement2;
}
}





Text Box: if<exp1>
{
	if<exp2>
	{
		statement1;
}
else
 {
	statement2;
}
else 
{
statement3;
} Text Box: if<exp1>
{
statement1;
}
else
{
	if<exp2>	
{
		statement2;
}
	else
{
		statement3;
}
}


Text Box: if<expr1>
{
		if<exp2>
{
	statement1;
}
	else
		{
		statement2;
	}
}




 



LOOP CONTROL STRUCTURE

If we want to perform certain action for no of times or we want to execute same statement or a group of statement repeatedly then we can use different type of loop structure available in C. Basically there are 3 types of loop structure available in C
(1)   While loop
(2)   Do..while
(3)   For loop

While statement:

Text Box: Initialization;
While(exp)
{
 statement 1;
 statement 2;
 increment/ decrement;
}

The while statement is used to carry out looping operations. The general form of the statements

The enclose statements within two braces will be executed repeatedly as long as the expression evaluated as true. When the expression is evaluate a false or when condition will be false then it will come out from the loop and stop the execution of that loop. Initialization statement  initialize some memory variable with some value. Increment or decrement operator increase or decrease the value of operator is use by expression. This statement can be simple of compound, though it is typically a compound statement, it must include some features, which eventually offers the value of expression, thus provides a stopping condition for the loop.

The practice, the included expression is usually a logical expression that is either true or false. (remember that true corresponds to non-zero value and false corresponds to zero value). Thus the statement will continue to execute as long as the logical expression is true.

The part of while statement, which contains the statement, is called the body of the loop. Body of the loop may have one or more statements. The braces are needed only if the body contains two or more statements. However, it is a good practice to use braces even if the body has only one statement.
Suppose we want to display the consecutive digits 0,1,2,3…9 with one digit on the each line. This can be accomplished with the following program.
Text Box: #include<stdio.h>
main ()
{
int digit = 0;
while(digit<=9)
{
printf(“%d \n”,digit);
++digit ;
}
}
Initially, digit is assigned a value of 0. The while loop then displays the current value of digit, increases its value by 1 and then repeats the cycle, until the value of the loop will be repeated by 10 times, resulting in 10 consecutive lines of output. Each line will contain a successive integer value, beginning with and ending with 9. Thus when the program to run, the following output will be generated :
            0 1 2 3 4 5 6 7 8 9
Do-While statement :

Sometimes, however, it is desirable to have a loop with the test for continuation at the end or each pass. This can be accomplished by means of the do-while statement.
Text Box: Do
{
statement1;
statement2;
increment/decrement operator;
} while(expression);

The general form of do-while statement is

The enclosed  statement within 2 braces will be executed repeatedly as the value of expression is not zero. Notice that statement will always be executed at least once. Since the test for repetition does not occur until the end of the first pass through the loop. The statement can be either simple or compound, though most applications will require it to be a compound statement. It must include some feature which eventually alters the value of expression so that the looping action can terminate. Since the expression is evaluated at the bottom of the loop, the do…while loop construct provides an exit… controlled loop and therefore the body of the loop is always executed at least once.

In practice, expression is usually a logical expression, which is either true(with a non zero value) or a false(with a value of 0). The included statement will be repeated (i.e. another pass will be made through the loop) if the logical expression is true.

For most applications it is more natural to test for continuation of a loop at the beginning rather than at the end of the loop for this reason, the do…while statement is use less frequently than while statement. Suppose that we want to display consecutive 0,1,2,3,…9 with one digit on each line. This can be accomplished with the following program.


 



#include <stdio.h>
main()
{
                        int digit = 0;
            do
                        {
printf(“%d”, digit++);
            }while(digit<=9);
}



The digit is initially assigned a value of 0. The do while loop displays the current value of digit. Increases it value by 1, and then tests to see if the current value of digit exceeds 0. If so loop terminates; otherwise the loop continues, using the new value of digit. Note that the last is carried out at the end of each pass through the loop. The net effect is that the loop repeated 10 times, resulting in 10 successive lines of output. Thus, when
the program is run the following output is generated :
0  1  2  3  4   5  6  7  8  9

FOR statement :

The for statement is another entry controller that provides a more concise loop control structure. The general form of the for loop is :


 
For(initialization, test condition, increment)
{
statement 1;
statement 2;
}

The execution of the for statement is as follows :
1.            Initialization of the control variables is done first, using assignments statement such as I=0 and count=0. The variables I and count are known as loop controls.
2.            The value of the control variables is tested using the test condition. The test condition is relational expression, such as I>0 or I<10 that determines when the loop is terminated and the execution continues with statement that immediately follows the loop.
3.            When the body of the loop is executed, the control is transferred back to the for statement either evaluating the last statement is the loop. Now, the control variable is incremented using and assignment statement such as I=I+1 and if the new value of the control is satisfied under test condition, then the body of the loop is executed. This process continues till the value of the control variable fails to satisfy the test-condition.
(a)               
Text Box: For(x=0; x<9; x++)
{
	printf(“%d”, x);
printf(“\n”);
}

Consider the following segment of a program :
           
This for loop is executed 10 times and prints the digits 0 to 9 in one line.  The three sections within parentheses must be separated by a semicolons. Note that there is no semicolon at eh end of the increment section x++.

{
            Printf(“%d”,x0
            Printf(“/n”);
}

Text Box: For(x=9; x>=0; x--)
{
	Printf(“%d”,x0
	Printf(“/n”);
}

The for statement allows for negative increments. For example, the loop discussed above can be written as follows:

This loop is also executed 10 times. But the output would be from 9 to 0 instead of 0 to 9. Note that, braces are optional when the body of the loop contains only one statement.

Additional features of for loop :
The for loop in C has several capabilities that are not found in the other loop constructs. For example, more than one variable can be initialized at a time in the for statement.
            {
                        p=m/n;
                        printf(“%d%d%d \n”,n,m,p);
            }

Text Box: For(n=1,m=50; n<m; n++, m--)
	{
		p=m/n;
		printf(“%d%d%d \n”,n,m,p);
	}

           
This is perfectly valid. The multiple arguments in the increment section are separated by commas.

The third feature is that the test condition may have nay compound relation and the testing need not be limited only to the loop control variable. Consider the example below :
Text Box: Sum=0;
	For(I=1;I<20 && sum<100; I++)
	{	
		sum=sum+I;
		printf((“%d \n”, sum);
	}

           
The loop uses a compound test condition with the control variable; and external variable sum. The loop is executed as long as both the conditions I<20 and sum<100 are true. The sum is evaluated inside the loop.

It is also permissible to use expressions in the assignment statements of initialization and increment sections, For example, a statement of the type :
            For(z=(m+n)/2; x<0;x=x/2)
is perfectly valid.

Another unique aspect of the for loop is that one or more sections can be omitted, if necessary.
Text Box: M=0;
	for(;m!=100;)
	{
		printf(“%d \n”, m);
		m=m+5;
	}

Consider the following statements :

Both the initialization and increment sections are omitted in the for statement. The initialization has been done before the for statement and the control variable is incremented inside the loop. In such cases the sections are left blank. However, the semicolons separating the sections must remain. If the test condition is not present, the for statement sets up an infinite loop. Such loops can be broken using break or go-to statements in the loop. We can set up time delay loop using the null statement as follow:

            For(j=1000;j>0;j--) {}
The loop executed 1000 times without producing any output; it simply causes a time delay. Notice that the body of the loop contains only a semicolon, known as null statement. This can also be written as :

            For(I=1000; I>0; I--);
This implies that C compiler will not give an error message. If we place a semicolon by mistake at the end of a for statement. The semicolon will be considered as a null statement and the program may produce some nonsense.

Loops can be nested (i.e. embedded) one within another. The inner  and outer loops need not be generated by the same type of control structure. It is essential that one loop be completely embedded within the other. There can be no overlap. Also each loop must be controlled by a different index.

BREAK STATEMENT:


The break statement is used to terminate loops or to exit a switch. The break statement will break or terminate the inner-most loop. It can be used within a while, a do-while, a for or a switch statement. The break statement is written simply as break; Without any embedded expressions or statement. For example,
Text Box: For(I=1; I<=10; I++)
{
		if(I==5)
			break;
	printf(“\nI=%d”,I);
}
The output will be 1,2,3,4 and then break will terminate this loop and stop the execution of the for loop.

CONTINUE STATEMENT

The continue statement is used to skip or to bypass some step or iteration of looping structure. It does not terminate the loop but just skip or bypass the particular sequence of the loop structure. It is simply written as continue;.
Text Box: For(I=1; I<=10; I++)
{
if(I==5)
continue;
printf(“\nI=%d”,I);
}

                                   
The output of the above program will be 1,2,3,4,6,7,8,9,10. The 5th iteration of the loop will be skipped as we have define the continue for that iteration. So it will not print the value ‘5’.

SWITCH-CASE Statement :

The switch statement causes a particular group of statements to be chosen from several available groups. The selection is based upon the current value of an expression that is included within a switch statement. The general form of switch-case  statement is :
Text Box: Switch(expression)
{
Case expression1
	Statement1;
	Statement2;
Case expression2
	Statement1;
	Statement2;
Case expression3
	Statement1;
	Statement2;
}
Usually each of these expression will be written as either an integer constant or a character constant. Each individual statement following the case labels may be either simple or complex. Where expression1 1, expression 2,………,expression m represent constant, integer valued expression .When switch statement is executed the expression is evaluated and control is transferred directly to the group of statements whose case labels value matches the value of the expression. If none of the case-label values matches the value of the expression, then non of the groups within the switch statement w8ll be selected in this case control is transferred directly to the statement that follows the switch statement.
Example :
Text Box: Switch (choice=getchar())
{
	case ‘r’
	case ‘R’
		printf(“RED”);
		break;
	case ‘w’
	case ‘W’
		printf(“WHITE”);
		break;
	case ‘b’
	case ‘B’
		printf(“BLUE”);
	break;
}
Thus RED will be displayed if choice represents either r or R, WHITE will be display choice represents either w or W and BLUE will be displayed if choice represents either b or B. Nothing will be displayed if any other character has been assigned to choice. Notice that each group of statements has two case labels, to account for either upper or lower case. Also, note that each of the first two group ends with the break statement. The break statement causes control to be transferred out of the switch statement thus preventing more than one group of statement from being executed.

One of the labeled groups of statements within the switch statement may be labeled default. This group will be selected if none of the case labels matches the value of expression. The default group may appear anywhere within the switch statement. It need not necessary be placed at the end. If none the case labels matches the value of the expression and the default group is present, then the statement will take no action.
Text Box: Switch(choice=toupper(getchar())
{
	case  ‘R’ :
		printf(“RED”);
		break;
	 case ‘B’ :
		printf(“BLUE”);
		break;
	 case  ‘W’ :
		printf(“WHITE”);
		break;
	 default :
		 printf(“ERROR”);
		break;
}

Here is a variation of switch statement :

            The switch statement now contains a default group, which generates an error message if none of the case labels matches the original expression. Each switch statement now contains a default group, which generates an error message if none of the case labels matches the original expressions.

Each of the first three groups of statements now has only one case labels. Multiple case labels are not necessary in the example, since the library function toupper causes all incoming characters to be converted to the upper case. Hence choice will always be assigned an upper case character. In a special sense, the switch statement may be thought of as an alternative to the use of nested if-else statements, though it can only replace those if else statements that tests for equality. In such situations using the switch statement is generally much more convenient.

Notice that each group of statement ends with a break statement in order to transfer control out of the switch statement. The break statement is required within each of the first three groups in order to prevent the succeeding groups of statement from executing. This last group does not require a break statement since control will automatically be transferred out of the switch statement after the last group has been executed. This last break statement is included, however has a matter of good programming practice. So that it will be present, if another group of statement is added later.

 






THE GOTO STATEMENT :

The goto statement is used to alter the normal sequence of program execution by transferring control to some other part of the program. In its general for the goto statement is written as goto label; Where label is an identifier used to label the target statement to which control will be transferred.

Control may be transferred to any other statement within the program. The target statement must be labeled and the label must be followed by a color. Thus the target statement will appear as label : statement. Each labeled statement within the program must have unique label, i.e. no two statement can have same label.

The common application of goto are :

1.                  Branching around statement or groups of statements under conditions.
2.                  Jumping to the end of a loop under certain conditions, thus by passing the reminder of the loop during the loop during the current pass.
3.                  Jumping completely out of a loop under certain conditions, thus terminating the execution of the loop.
Branching ground statement can be accomplished with the if-else statement, jumping to the end of a loop can be carried out with the continue statement, and jumping out of a loop easily completed using the break statement. The uses of these structured features are preferable to the used of the goto statement because the use of goto tends to encourage logic that skips all over the program.

Occasional situations do arise, however, in which the goto statement can be useful. Consider, for example, a situation in which it is necessary to jump out of a doubly nested loop if a certain conditions are detected. This can be accomplished with two if break statements. One within each loop, though this is awaked. A batter solution in this particular situation might make user of the goto statement to transfer out of both loops at once.

 

0 comments:

Post a Comment

Twitter Delicious Facebook Digg Stumbleupon Favorites More