Module 2
Module 2
UNIT – II
Control Structures: if and switch statements, loops- while, do-while and for statements, break,
continue, goto and labels.
Control Structures in c
Control Structures -"Statements used to control the flow of execution in a program".
Means a statement through which we control the behavior of ourprogram like what kind of
function it will perform, when it will terminate or continue under certain circumstances or
conditions.
These instructions enable us to group individual instructions into a single logical unit with one
entry point and one exit point. To make it more clearer, suppose we have lot of statements in our
program by using control structure we control their working like either all statements will
evaluate at once on the basis of certain condition or will evaluate one by one or will not be
evaluated.
Normally statements in C program are executed sequentially i.e in the order in which they are
written. This is called Sequential execution. We can transfer the control point to a desired
location is possible with control structures. C allows many kinds of control statements.
If:
if is also called as conditional statement in if statements get executed only when the condition is
true, it can terminate when the condition becomes false.
Example:
#include<stdio.h>
main()
{
int a,b,c,d;
float ratio;
printf("Enter four integer values\n");
scanf("%d %d %d%d",&a,&b,&c,&d);
if(c-d!=0) /*Execute statement block */
{
ratio=(float)(a+b)/(float)(c-d);
printf("Ratio=%f\n",ratio);
}
}
Nested -ifs
Inside one if statement, if or if-else can be used. Such statements are called nested if’s the
structure is given below.
if( a )
{
if ( b )
{
Statement1;
---
Statement n;
}
if ( c )
{
Statement1;
---
Statement n;
}
else
{
Statement1;
---
Statement n;
}
}
else
{
Statement1;
---
Statement n;
}
The final else is associated with if (a) and not associated with if c,because it is not in the same
block.
if –else if-else:
In this statement statements in loops gets executed when the corresponding conditions are true.
Statements in final else block gets executed when all other conditions are false. We can use any
no. of else-if blocks between if and else.
Example:
An electric power distribution company charges its domestic consumers as follows:
Reads the customer number and power consumed and prints the amount to be paid by the
customer
#include<stdio.h>
main()
{
int units, custnum;
float charges;
printf("Enter customer no. and units consumed\n");
scanf("%d%d",&custnum,&units);
if(units<=200)
charges=0.5*units;
else if(units<=400)
charges=100+0.65*(units-200);
else if(units<=600)
charges=230+0.8*(units-400);
else
charges=390+(units-600);
printf("\n\nCustomer no:%d Charge=%.2f\n", custnum, charges );
}
Switch Statement
C has a multiple branch selection statements called switch. It tests the value of an expression
against a list of integer or character constants.
When a match is found the statements associated with that constants are executed. The general
format of switch is
switch (expression)
{
case constant1;
Statement sequence
break;
case constant2;
Statement sequence
break;
case constant3;
Statement sequence
break;
...
default
Statement sequence
}
Switch, case and default are key words and statement sequence can be single statement or a
compound statement. If it is compound statement it must be enclosed in braces.
The expression which is in switch, must evaluate to integer type.
The expression is switch can have int constant or char constant or expression that evaluates
to one of their constants. If character date type is used, its equivalent integer value is
considered. Floating point expressions are not allowed in switch statement.
In case expression such as case constant1, case constant2, case constant3, . etc the word
constant 1 is called case labels or case prefixes.
The case label can either be integer or character constant. Each case label must be distinct.
When a switch statement is executed, the expression is evaluated and control is directly
transferred to the group of statements where case-label value matches with the value of
expression statements under that case label is executed the break statement ensures
immediate exit from the switch statement. If none of the cases are satisfied, the default
statement is executed.
The default statement is optional. If none of the case are satisfied and default case is also not
present, then no action takes place.
The default case is optional. If present, it will be executed when the match with any
‘case’ is not found.
There can be at most one default label.
The default may be placed anywhere but generally written at the end.
When placed at end it is not compulsory to write the ‘break’ for it.
We can nest the switch statements.
Write a program to check whether the enter the character is a vowel, a last alphabet or consonant
/* program to check whether the enter the character is a vowel, a last alphabet or consonant */
# include <stdio.h>
main( )
{
char ch;
printf(“\n Enter a lower case alphabeet (a-z);”);
scanf (“ %d” , & ch);
if ( ch<’a’ || ch>’z’)
printf(“\n Character is not lower case alphabet”);
else
switch (ch)
{
case ‘a’ :
case ‘e’ :
case ‘i’ :
case ‘o’ :
Case ‘u’ :
printf(“\n Entered Character is vowel”);
break;
case ‘z’ :
printf(“\n Entered Character is last alphabet”);
break;
default;
printf(“\n Entered Character is consonant”);
}
}
Output: Enter a lower case alphabet ( a – z ): p entered character is consonant.
Explanation: each case need not have its own statements. A set of case can have common
statements to be executed. This is as shown in the above program. The default can either end
with break or not. This depends upon program structure.
scanf(“%c”,&op);
switch(op)
{
case ‘+’: printf(“sum=%d”,a+b);
break;
case ‘-’: printf(“difference=%d”,a-b);
break;
case ‘*’: printf(“mul=%d”,a*b);
break;
case ‘/’: printf(“div=%d”,a/b);
break;
case ‘%’: printf(“rim=%d”,a%b);
break;
default: printf(“your option is wrong”;
break;
}
}
4 Syntax: Syntax:
if(condition) switch(variable)
{ {
//statements case value1:
} break;
else case value2:
{ break;
//statements default
}
LOOPS:
The real power of computers is in their ability to repeat an operation or a series of operations many
times. This repetition, called looping, is one of the basic structured programming concepts.
Each loop must have an expression that determines if the loop is done. If it is not done, the loop
repeats one more time; if it is done, the loop terminates.
Pretest loop:
• With each iteration, the program tests the condition first before executing the loop’s
block.
• If the condition tests to true, the loop continues and executes the block; if the condition
tests to false, the loop terminates.
• With a pretest loop, there is a chance the loop may never execute in the run of a program!
Posttest loop:
• With each iteration, the program executes the loop’s block first and tests against a
condition.
• If the condition tests to true, the loop continues and executes another iteration; if the
condition tests to false, the loop terminates.
• With a post-test loop, the loop will always execute at least once!
Loop Initialization
Programs typically require some type of preparation before executing loops.
Loop initialization, which happens before a loop’s first iteration, is a way to prepare the
loop. It may be explicit or implicit.
In explicit initialization, we write code to set the values of key variables used by the loop.
Implicit initialization relies on a “preexisting situation to control the loop.”
All the possible expressions that can be used in a loop limit test can be summarized into two
general categories: event-controlled loops and counter-controlled loops.
Loop Comparisions
• We cannot predict the maximum number of iterations during the run of a program.
Counter-Controlled Loop
• In such a loop, we use a counter, which we must initialize, update and test.
• The number the loop assigns to the counter doesn’t need to be a constant value.
C has three loop statements: the while, the for, and the do…while. The first two are
pretest loops, and the the third is a post-test loop. We can use all of them for event-
controlled and counter-controlled loops.
While Loop
The simplest of the three loops is the while loop. The while-loop has a condition and the
statements .
The syntax is given below.
while (condition)
{
statements;
}
The condition expression (something like (a > b) etc...) is evaluated first.If the expression
evaluates to True state i.e returns a nonzero value(normally 1) the looping continues; that is, the
statements inside the statement block are executed. After the execution, the expression is
evaluated again. The statements are then executed one more time if the expression still returns
nonzero value. The process is repeated over and over until the expression returns 0(False state).
The statement block, surround by the braces { and }.If there is only one statement in the
statement block, the braces can be discarded.
Consider an example of using the while statement.
ANALYSIS
The char variable a is initialized before the the while Statement. In the while condition the
relational expression c !=`x' is tested. If the expression returns 1, which means the relation still
holds,the statements under the while are executed. The looping continues as long as the
Do-while Loop
The while and for loops test the termination condition at the beginning of the loop. By contrast,
the do-while loop, tests at the bottom after making each pass through the loop body; the body is
always executed at least once.
First the statement is executed under the do clause, then expression in the while is evaluated. If it
is true, statement is executed and again the while is evaluated and this looping process continues.
When the expression becomes false, the loop terminates. The do-while is much less used than
while and for. If the statement contains a set of statements, they must be enclosed in the braces.
Output:
13
Wrong code. No Entry
15
Right code. You can Enter
Analysis:
Here do part is executed to know the password. If it is right, entry is given otherwise not. Loop
will repeat only for three set of inputs. For the fourth set variable i value does not satisfy the
while condition. Hence loop is quit.
#include <stdio.h>
main()
{
int value, r_digit;
printf("Enter the number to be reversed:\n");
scanf("%d", &value);
Output:
Enter the number to be reversed: 132
231
Enter the number to be reversed: 0
0
Analysis:
The above program reverses a number that is entered by the user. It does this by using the
modulus % operator to extract the right most digit into the variable r_digit. The original number
is then divided by 10, and the operation repeated whilst the number is not equal to 0.If user
enters the number other than zero, program works. If user enters 0(zero), then also the do part is
executed, violating the condition at while. This means it's possible to enter a do { } while loop
with invalid data. Hence it is better to avoid the usage of Do-while statement. Its easy to avoid
the use of Do-while construct by replacing it with other constructs. The above program can be
written without Do-while construct. This is shown below.
Syntax explanation:
(1) Initialization:
This is some kind of expression which initializes the control variable or (index varaible) This
statement is carried out only once before the start of the loop. e.g. i = 0;
(2) Condition:
The condition is evaluated at the beginning of every loop and the loop is
only carried out while this expression is true. e.g. i < 20;
(3) Loop expression
This is some kind of expression for altering the value of the control variable. This expression is
evaluated at the end of each iteration. In C it can be absolutely anything. e.g. i++ or i *= 20 or i
/= 2.3 ...
(4) Statement sequence
Statement sequence can consist only one statement or a group of statements. If it contains a
group of statements, they must be embraced in braces({}).If it contains only one statement ,
braces need not be enclosed.
Write a program to print upper case and lower case alphabets using using char data type in for
loop.
/* a program to print upper case and lower case alphabets using using char data type in for loop */
#include <stdio.h> /* library header */
main()
{
char ch;
for (ch = 'A' ; ch <= 'z' ; ch++)
printf("%c\n" , ch);
}
Here in the for loop statement increment is not given, but given in the body of the statement.
Semicolon after the condition is mandatory.
3) int i=2;
for(;i<4; i=i+1)
Printf(“ helo for loop”);
Here in the for loop statement initialization is not given, but given before the statement.
Semicolon before the condition is mandatory.
4) int i=2;
for(;i<4;)
{
Printf(“ helo for loop”);
i=i+1;
}
{
int j;
for(int i=0; i<5;i++)
{
j=i*i;
printf(“The value of j is%d”,j);
}
i=i+9; /*ERROR. i is not known here */
}
In the above example the integer variable i is declared inside the for loop in the initialization part
of it.. This i is limited only to that declared loop. Outside the loop is unknown. If declared
compiler shows error message.
SYNTAX:-
for (initializing ; test condition ; increment / decrement)
{
statement;
for (initializing ; test condition ; increment / decrement)
{
body of inner loop;
}
statement;
}
int i, j;
clrscr ( );
for (j=1; j<=4; j++) /*outer for loop*/
{
for (i=1; i<=5; i++) /*inner for loop*/
{
printf (“*”)
}
Prepared by T.Aruna Sri,Dept of CSE Page 21
Control Structures in C
printf (“\n”);
}
}
Each labeled statement within the function must have a unique label, i.e., no two statement can
have the same label.
In this syntax, label is an ident ifier. When, the control of program reaches to goto
statement, the control of the program will jump t o the label: and executes the code below
it.
error:
printf(“\n the number is non negative”);
}
Return:
The return statement causes the current function to terminate. It can return a value to the calling
function. A return statement can not appear in a function whose return type is void. If the value
returned has a type different from that of the function's return type, then the value is converted. Using
the return statement without an expression creates an undefined result. Reaching the } at the end of
the function is the same as returning without an expression.
Syntax:
return expression;
Example:
Maximum of two numbers
#include<stdio.h>
main( )
{
int a=12,b=8;
if(a>b)
return a;
else
return b;
}
Break Statement :
break statement is a jump statement. Break statement when encountered within a loop
immediately terminates the loop by passing condition check and execution transfer to the first
statement after the loop. In case of switch it terminates the flow of control from one case to
another.
Example of break :
#include <stdio.h>
main ()
{
for (int i = 0; i<100; i++)
{
printf ("\n%d", i);
if (i == 10); // This code prints value only upto 10.
break;
}
if(i==2)
Printf(“Your choice of fruit is Orange“);
if(i==3)
Printf(“Your choice of fruit is Grapes“);
if (i == 4)
break;
}
}
Continue Statement:
Instead of breaking a loop, a need to stay in the loop but skip over some statements within the loop
may occur. To do this, the continue statement is used. The continue statement takes the control to the
beginning of the loop bypassing the statements inside the loop which have not yet been executed.The
continue statement can only be used within the body of a while, do, or for statement. For better
control over the program, like a break statement, continue is generally used in conjunction with if
structure within loops. When continue is used the next iteration of a do, for, or while statement is
determined as follows:
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. Then the compiler
reevaluates the conditional expression and, depending on the result, either terminates or iterates the
statement body
One good use of continue is to restart a statement sequence when an error occurs. Using the continue
statement, as well as the break statement, may makes program hard to debug. Hence it is seldom used.
The format of using continue in while loop and some examples of continue statement is given below.
while (<expression>)
{
...
if (<condition>)
continue;
...
...
// control jumps here on the continue
}
3) Write a program to find the sum Using the continue statement in for loop.
/* Using the continue statement */
#include <stdio.h>
main()
{
int i, sum;
sum = 0;
for (i=1; i<8; i++)
ANALYSIS:
Program is to calculate the sum of the integer values of 1, 2, 4, 6, and 7. because the integers are
almost consecutive, a for loop is built in lines 9_13. The statement sum += i; sums all integers
from 1 to 7 except for 3 and 5,.3nad 5 are skipped in the for loop by using continue statement. This
is done by evaluating the expression (i==3) || (i==5) in the if statement. If the expression
returns 1 (that is, the value of i is equal to either 3 or 5), the continue statement is executed,
which causes the sum operation to be skipped, and another iteration to be started at the beginning
of the for loop. In this way, the sum of the integer values of 1,2, 4, 6, and 7is obtained, but 3 and
5are skipped, automatically by using continue statement in for loop. After the for loop, the value
of sum, 20, is displayed on the screen by the printf() function .
Write a program to find the odd numbers using continue statement in while loop.
/* a program to find the odd numbers using continue statement*/
#include <stdio.h>
main ()
{
int x;
x = 0;
while (x < 10)
{
++x;
if (x % 2 == 0)
{
continue;
}
printf ("%i is an odd number.\n", x);
}
Output
1 is an odd number.
3 is an odd number.
5 is an odd number.
7 is an odd number.
9 is an odd number.