CONTROL STRUCTURES
INTRODUCTION: ‘C’ program is a set of statement, which normally executed sequentially in the order in which they appears. In practice we have a number of situations where we may have to change the order of execution of statements until certain specified conditions are met. This involves a kind of decision making to see whether a particular condition has occurred or not and then direct the computer to execute certain statements accordingly.
A) DECISION MAKING STATEMENTS
(a) The if statement:
The if statement is used to specify conditional execution of program statement, or a group of statements enclosed in braces.
syn: if(condition)
{
True-block statements;
}
In a following sample program, if the user enters a number divisible by 3, a message has to be printed. If it is not
divisible by 3, then the message need not be printed.
/* EX-9: ILLUSTRATION OF IF STATEMENT */ |
#include { int i; clrscr(); printf("\n Enter a number: "); scanf("%d",&i); if(i%3==0) printf("\n The number you have entered is divisible by 3"); getch(); } |
(b) The if-else statement:
When two groups of statements are given and it is desired that one of them be executed if the condition is true and the
other group be executes if that condition is not true. In such a situation, the if-else statement can be used.
syn: if(condition)
{
True-block statements;
}
else
{
False-block statements;
}
/* EX-10: ILLUSTRATING IF-ELSE STATEMENT */ |
#include { int a,b; printf("\n Enter the value of a: "); scanf("%d",&a); printf("\n Enter the value of b: "); scanf("%d",&b); if(a>b) printf("\n\t %d is greater than %d", a,b); else printf("\n\t %d is greater than %d", b,a); getch(); } |
C) Ternary operator:
This can be used to replace the statements of the if-else. Ternary operator connects three operands. The first operands
always evaluated first. It is usually a conditional expression that uses the logical operators. The next two operands are any
other valid expressions, which can be single constants, variables or general expressions. The complete conditional expression
consists of all three operands connected by the conditional operator symbols ? and :.
/* EX-11: ILLUSTRATING TERNARY OPERATOR */ |
#include { int i,j,larger; clrscr(); printf("\nInput two integers: \n"); scanf("%d %d",&i,&j); larger = i > j ? i : j ; printf("\n The larger of two numbers : %d", larger); getch(); } |
Note: If the value of i is greater than j then the value of i will store into the variable larger,
otherwise the value of j will store into the variable large.
d) Nested if-else statement:
SYN : if(condition-1)
{
if(condition-2)
{
statement(s)-1;
}
else { statement(s)-2;
}
else { statement(s)-3;
}
|
#include { char g,name[30]; int a; clrscr(); printf("\nEnter your name: "); gets(name); printf("\nEnter gender code: "); fflush(stdin); scanf("%c",&g); if(g=='f' || g=='F' || g=='m' || g=='M') { printf("\nEnter age: "); scanf("%d",&a); if(g=='m' || g=='M') if(a>=21) printf("\n\tHellow Mr. %s",name); else printf("\n\t Hellow Master. %s",name); if(g=='f' || g=='F') if(a>=18) printf("\nHello Miss. %s",name); else printf("\nHellow Kumari. %s",name); } else printf("\n\n\n\t\tInvalid gender code, Enter m/f only"); getch(); } |
e) Multiple if-else statement (or) else-if ladder:
When multipath decisions are involved, a chain of if statement associated with each else is an if. It’s construct is as follows.
syn: if(condition-1)
statement(S)-1;
else if(condition-2)
statement(s)-2;
else if(condition-3)
else
statement(s)-3);
/* EX-13: ILLUSTRATING ELSE-IF LADDER */ |
#include { int mark; clrscr(); printf("\n Enter the student's mark: "); (canf("%d",&mark); if(mark>=80) printf("\n Grade = \"Distinction\""); else if(mark>=60) printf("\n Grade = \"First Class\""); else if(mark>=50) printf("\n Grade = \"Second Class\""); else if(mark>=40) printf("\n Grade = \"Third Class\""); else printf("\n Grade = \"Fail\""); getch(); } |
(f) The switch statement:
C has a built-in multiway decision statement known as a switch. The switch statement tests the value of a given variable (or expression) against a list of case values and when a match is found, a block of statements associated with that case is executed.
The break statement at the end of each block signals the end of a particular case and causes an exit from the switch
statement.
The default is an optional case. When present, it will be executed if the value of the expression does not match with any of the case values. The expression is an integer or character.
syn : switch(expression)
{
case value-1 : statement(s);
break;
case value-2 : statement(s);
break; . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . .
case value-n : statement(s);
break; default : statement(s);
break;
}
|
#include { int choice; clrscr(); printf("\n\n\n\t CHOICE OF DESTINATION \n"); printf("\n\t\t 1 - MERCURY"); printf("\n\t\t 2 - VENUS"); printf("\n\t\t 3 - MARS"); printf("\n\n\t Enter the number corresponding to your choice: "); scanf("%d",&choice); switch(choice) { case 1: clrscr(); puts("\n\n\t Mercury is closest to the sun"); puts("\n\t So the weather may be quite not hot there"); break; case 2: clrscr(); puts("\n\n\t Venus is the second planet from the sun"); puts("\n\t The weather may be hot and poisonous"); break; case 3: clrscr(); puts("\n\n\t Mars is the closest planet to the earth"); puts("\n\t The weather has been excellent till now"); break; default: puts("\n\n\t\t \"UNKNOWN DESTINATION\""); break; } /* End of switch */ getch(); } /* End of main */ |
/* EX-15: PGM TO DEMONSTRATE THE USE OF SWITCH STATEMENT USING |
CHARACTER EXPRESSION */ #include { char choice; clrscr(); puts("\n\n\t CHOICE OF YOUR DESTINATION"); puts("\n\t\t G - Generator"); puts("\n\t\t O - Operator"); puts("\n\t\t D - Destroyer"); printf("\n\n\t Press the letter corresponding to your choice: "); scanf("%c",&choice); switch(choice) { case 'g': case 'G': puts("\n\n\t\tSelected choice is GENERATOR"); break; case 'o': case 'O': puts("\n\n\t\tSelected choice is OPERATOR"); break; case 'd': case 'D': puts("\n\n\t\tSelected choice is DESTROYER"); break; default: puts("\n\n\n\t\tINVALID CHOICE"); break; } getch(); } |
break statement:
The break statement transfers the control to the end of the construct. In looping constructs, it transfers control to the next statement after the looping construct. In nested loop construct, the break statement terminates the inner most loop only.
continue statement:
The continue statement is used to bypass the remainder of the current pass through a loop. The loop does not terminate when a continue statement is encountered. Instead, the remaining loop statements are skipped and the computer proceeds directly to the next pass through the loop.
/* EX-16: PGM TO DEMONSTRATE THE USE OF CONTINUE STATEMENT */ |
#include #define MAX 5 /* MAX is a predefined constant, having the value of 5 */ main() { int n,i=1,sum=0; clrscr(); printf("\n\t INPUT ANY 5 INTEGER NOS."); for(i=0;i |
Note :
1. #defined MAX 5 is a predefined constant, where MAX having the value 5.
2. %i is an access specifier for unsigned integer.
Sample Run :
Enter an integer: 2
Enter an integer: -4
You have entered a negative number
Enter an integer: 4
Enter an integer: 11
Enter an integer: 7
The sum of the positive integers entered = 24
goto statement:
The goto statement is used to alter the normal sequence of program execution by unconditionally transferring control to some other part of the program. This statement is written as goto label;
Here, label is an identifier used to identify the target statement to which the control would be transferred. The target statement must be labeled and a colon must follow it. The target statement will appear as: label: statement;
B) LOOP CONSTRUCTS:
Loops in ‘C’ cause a section of the program to be executed repeatedly while an expression is true. When the expression becomes false, the loop terminates and the control passes on to the statement following the loop. A loop consists of two segments, one is known as the control statement and the other is the body of the loop.
The ‘C’ language provides three loop constructs for performing loop operations.
They are:
1. The do..while loop constructs
2. The while loop constructs
3. The for loop constructs
(a) do..while loop:
The do..while loop, evaluates the condition after execution of the statements in its construct. The statements within the do..while loop are executed at least once. So, the do..while loop is called a bottom-tested loop.
Syn :
do
{
statement(s);
}
while (condition);
/* EX-17: ILLUSTRAION OF DO-WHILE LOOP */ |
#include { int x=10; clrscr(); do { printf("\n%d",x); x++; /* Short form of x=x+1; */ } while(x<20); getch(); } |
Note : After run this program once, change the condition as while (x<=8) and check out the output.
(b)while loop:
The while loop is often used, when the numbers of times the loop is to be executed is not known in advance. The while loop is top-tested i.e., it evaluates the condition before executing any of the statements in its body.
Syn :
while(condition)
{
statement(s);
}
/* EX-18: ILLUSTRATING WHILE LOOP */ |
#include { int i=5; clrscr(); while(i<10) { printf("\n National Institute"); i++; } getch(); } |
INPUT TYPE INPUT HERE |
TYPE OUTPUT HERE |
/* EX-19: ILLUSTRATION OF WHILE LOOP UNTIL USER WISHES TO TERMINATE */ |
#include main() { char name[30],ch='y'; clrscr(); while(ch=='y' || ch=='Y') { fflush(stdin); printf("\n Enter the student's name in a Computer Department: "); gets(name); printf("\n\n\t Do you want to continue (y/n): "); scanf("%c",&ch); } } |
(c) for loop:
The for loop is useful while executing a statement to a number of times. The keyword for is followed by the initialization,
condition and iteration are comes into a single statement.
syn : for(initialization; condition; iteration)
{
statement(s);
}
/* EX-20: PGM TO DISPLAY FIRST 5 NUMBERS MULTIPLIES OF 3 ON A SINGLE LINE */ |
#include main() { int i; clrscr(); printf("\n"); for(i=1;i<=5;i++) printf("\t %i", 3*i); getch(); } |
Output : 3 6 9 12 15
Comma operator: Comma operator (,) is used to combined two related expressions into one, making programs more compact.
/* EX-21: ILLUSTRATING COMMA OPERATOR IN FOR LOOP */ |
main() { int i,sum; clrscr(); for(sum=0,i=0; i<8; i++,sum+=i) printf("\n Sum = %d", sum); getch(); } |
OUTPUT : Sum = 0 Sum = 1 Sum = 3 Sum = 6 Sum = 10 Sum = 15 Sum = 21 Sum = 28 |