0% found this document useful (0 votes)
9 views28 pages

Module 2

Uploaded by

sanatabasum2005
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views28 pages

Module 2

Uploaded by

sanatabasum2005
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

Control Structures in C

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.

All programs use control structures to implement the program logic.


There are three types of Control Structures
1. Sequence
2. Selection/Branching
3. Loops/ Repetition/ Iteration

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.

Prepared by T.Aruna Sri, Dept of CSE Page 1


Control Structures in C

I. Conditional(decision ) control structures


· if
· if –else
· if-elseif – else
· nested if
II. Jumping(branching) control structures
· goto
· break
· return
· continue
III. Loop(iterative) control structures
· for loop
· while loop
· do - while loop
IV. Multi way conditional(case) control structures
· switch- case

Conditional Control Structures:

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.

Syntax: The general form of simple if statement is


if ( test expression )
{
statement-block;
}
statement-x;

The statement-block may be a single statement or a group of statements.

Prepared by T.Aruna Sri, Dept of CSE Page 2


Control Structures in C

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);
}
}

The if – else statement


The If – else statement contains a condition. It is logically evaluated. If it evaluates to TRUE
condition, then statements under if part is executed. If the condition evaluates to FALSE state
then statements under else part is executed. Else clause is optional. The statement under if or else
part can be single or multiple statements. If multiple statements are used, they must be embraced
with the braces.

The syntax of if – else statement is given here.


if ( test expression )
{
True-block statements;
}
else
{
False-block statements;
}
statement-x
only one of them is executed

Prepared by T.Aruna Sri, Dept of CSE Page 3


Control Structures in C

Example: Write a program to check a given number is odd or even.


# include <stdio.h>
main()
{
int a;
printf(“Enter the number to bechecked”);
scanf (“ %d” , &a);
if ( (a%2) = = 0)
printf(“The given number is even”);
else
printf(“The given number is odd”);
}

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.

Prepared by T.Aruna Sri, Dept of CSE Page 4


Control Structures in C

Example: Program to find largest of 3 numbers.


#include<stdio.h>
main()
{
float a,b,c;
printf("Enter three values\n");
scanf("%f%f%f",&a,&b,&c);
printf("\nLargest value is ");
if(a>b)
{
if(a>c)
printf("%f\n",a);
else
printf("%f\n",c);
}
else
{
if(c>b)
printf("%f\n",c);
else
printf("%f\n",b);
}
}

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.

Prepared by T.Aruna Sri, Dept of CSE Page 5


Control Structures in C

Example:
An electric power distribution company charges its domestic consumers as follows:

Consumption Units Rates of Charge


0-200 Rs. 0.5 per unit
201-400 Rs. 100 plus Rs. 0.65 per unit excess of 200
401-600 Rs. 230 plus Rs.0.80 per unit excess of 400
601 and above Rs.390 plus Rs. 1.00 per unit excess of 600

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 );
}

Prepared by T.Aruna Sri, Dept of CSE Page 6


Control Structures in C

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.

Rules of Switch Statement


 The switch variable must be an integer or character type.
 Case labels must be constants of constant expressions.
 Case labels must be unique. No two labels can have the same value.
 Case labels must end with a colon.
 The break statement transfers the program control out of the switch block.
 The break statement is optional. When the break is not written in any ‘case’ then the
statements following the next case are also executed until the ‘break’ is not found.

Prepared by T.Aruna Sri, Dept of CSE Page 7


Control Structures in C

 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.

Program to perform arithmetic operators using switch case.


#include<stdio.h>
main( )
{
char op;
int a=10,b=5;
printf(“enter your operator +,-,*,/,%”);

Prepared by T.Aruna Sri, Dept of CSE Page 8


Control Structures in C

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;
}
}

Difference between If statement and Switch Statement


SNO If statement Switch statement
1 It checks whether the condition Is true or It is multi-way decision statement
false
2 It contains the condition which will It contains the variable whose value is to
evaluates to true or false be checked

3 It supports all types of conditions It supports checking only integer and


character values

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.

Prepared by T.Aruna Sri,Dept of CSE Page 9


Control Structures in C

Pretest and Post-test Loops


We need to test for the end of a loop, but where should we check it—before or after each
iteration? We can have either a pre- or a post-test terminating condition.
In a pretest loop , the condition is checked at the beginning of each iteration.
In a post-test loop, the condition is checked at the end of each iteration

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.”

Prepared by T.Aruna Sri,Dept of CSE Page 10


Control Structures in C
Updating a Loop
 A loop update is what happens inside a loop’s block that eventually causes the loop to
satisfy the condition, thus ending the loop.
 Updating happens during each loop iteration.
 Without a loop update, the loop would be an infinite 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

Event Controlled Loops

• In an event-controlled loop, an event is something that happens in the loop’s execution


block that changes the loop’s control expression from true to false.

• The program can update the loop explicitly or implicitly.

Prepared by T.Aruna Sri,Dept of CSE Page 11


Control Structures in C

• We cannot predict the maximum number of iterations during the run of a program.

6-7 Event-controlled Loop Concept

Counter-Controlled Loop

• In a counter-controlled loop, we can control the number of loop iterations.

• 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.

• To update, we can increment or decrement the counter.

Counter-controlled Loop Concept

Prepared by T.Aruna Sri,Dept of CSE Page 12


Control Structures in C

Differences between the entry and exit controlled loops are as


follows

No. Topics Entry controlled loops Exit controlled loops


01 Test condition Test condition appears at the Test condition appears at the end.
beginning.
02 Control Control variable is counter variable. Control variable is counter &
variable sentinel variable.
03 Execution Each execution occurs by testing Each execution except the first one
condition. occurs by testing condition.
04 Examples ======
do
{
printf(“Input a number.\n”);
scanf("%d", &num);
}
while(num>0);
======
========

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;
}

Prepared by T.Aruna Sri,Dept of CSE Page 13


Control Structures in C

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.

Write a program to understand the use of while loop.


/* program Using a while loop*/
#include <stdio.h>
main()
{
int a;
printf("Enter a character:\n(enter x to exit)\n");
while (a != `x')
{
a = getc(stdin);
putchar(a);
printf("\n");
}
printf("\nOut of the while loop. Bye!\n");
}
OUTPUT
Enter a character:
(enter x to exit)
i
H
x
x
Out of the while loop. Bye!

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

Prepared by T.Aruna Sri,Dept of CSE Page 14


Control Structures in C
expression returns 1i.e returns True value. However when the user enters the character x, which
makes the relational expression return 0, the looping stops.

The Infinite while Loop


You can also make a while loop infinite by putting 1 in the expression field, like this:
while (1) {
statement1;
statement2;
.
.
.
}
Because the expression always returns 1, the statements inside the statement block will be
executed over and over— that is, the while loop will continue forever. Of course, you can set
certain conditions inside the while loop to break the infinite loop as soon as the conditions are
met.
The C language provides some statements, such as if and break statements, that you can use to
set conditions and break the infinite while loop if needed.

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.

The syntax of the do is


do
statement
while (expression);

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.

Prepared by T.Aruna Sri,Dept of CSE Page 15


Control Structures in C
Consider the example to understand the working of do-while loop.

Write a program to illustrate the working of do-while loop


/*working of Do-While loop*/
#include<stdio.h>
int main(void)
{
int pass-word= 15;
int code;
int i=3;
do
{
printf("Type the password to enter.\n");
scanf("%d", &code);
if (code==15)
printf("Right code. You can Enter\n");
else
("Wrong code. No Entry\n");
i=i-1:
}
while(i!=0)
}

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.

Limitation of Do-while Loop


In Do-while, the loop the is executed as least once before checking the validity condition. In Do-
while structure entry to the loop is automatic (even with invalid input).Choice is given only for
the continuation of the loop. Such problems are deemed to be lack of control. Example for such
problem is given below.

Write a program to illustrate the limitation of Do-While loop.


/* program to reverse a number entered by the user */

#include <stdio.h>
main()
{
int value, r_digit;
printf("Enter the number to be reversed:\n");
scanf("%d", &value);

Prepared by T.Aruna Sri,Dept of CSE Page 16


Control Structures in C
do
{
r_digit = value % 10;
printf("%d", r_digit);
value = value / 10;
}
while( value != 0 );
printf("\n");
}

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.

/* rewritten code to remove construct */


#include <stdio.h>
main( )
{
int value, r_digit;
value = 0;
while( value <= 0 )
{
printf("Enter the number to be reversed.\n");
scanf("%d", &value);
if( value <= 0 )
printf("The number must be positive\n");
}
while( value != 0 )
{
r_digit = value % 10;
printf("%d", r_digit);
value = value / 10;
}
printf("\n");
}

Prepared by T.Aruna Sri,Dept of CSE Page 17


Control Structures in C
Sample Program Output
Enter the number to be reversed.
-43
The number must be positive
Enter the number to be reversed.
423
324

The for loop


A for loop is a block of code that iterates a list of commands as long as the loop control condition
is true. The syntax of for loop is for(initialization;Test condition;loop expression)
statement sequence

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.

Simple programs using for loop is given below


1. Write a program to print a word hello five times using for loop.
/* A program to print hello five times */
#include<stdio.h>
int main()
{
int i;

Prepared by T.Aruna Sri,Dept of CSE Page 18


Control Structures in C
for(i=0; i<5; i++)
printf("Hello \n");
}
Output:
Hello
Hello
Hello
Hello
Hello

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);
}

The for Loop Variations


For loop is a powerful programming tool. Many variations can be done in the for loop. They are
listed below.
1) for(i=1;i<4; i=i+1)
Here in the initialization part instead of i=i+1, the statements i++ or i+=1 can also be used.
2) for(i=1;i<4; )
{
Printf(“ hello for loop”);
i=i+1;
}

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;
}

Prepared by T.Aruna Sri,Dept of CSE Page 19


Control Structures in C
Here in the for loop statement initialization and increment is not given.
But both the semicolons are mandatory.

The Infinite Loop


In the for loop if conditional expression is absent, the condition is assumed to be true. This turns
out to be infinite loop. This is as shown
below.
for(; ; )
If break statement is used inside the loop , infinite loop is terminated.

The Comma Operator in The for Loop


The comma (,) operator is basically used in conjunction with for loop statement. This permits
two expressions to be used in initialization and count section of the for loop. Only one test
expression is allowed in the for loop.

The syntax of this is given below.


for (expression1a, expression1b; expression2; expression3a, expression3b)
Here expression 1a and expression 1b and expression 3a expression 3b
are separated comma operator.

For example consider the below for statement


for(i=0,j=2;j<=0;j--,i++)
Here i and j are the two different variables used and they are separated by comma operator.
Operation of this is given in the below example:
#include <stdio.h>
main()
{
int i, j;
for (i=0, j=1; i<8; i++, j++)
printf("%d - %d = %d\n", j, i, j - i);
}
OUTPUT:
1-0=1
2-1=1
3-2=1
4-3=1
5-4=1
6-5=1
7-6=1
8-7=1

Declaring Variables Inside The for Loop


In the initialization section of the for loop, Variable can be initialized also. The scope of it
limited to the block of code controlled by that statement.

Consider the example given below.


#include<stdio.h>
main()

Prepared by T.Aruna Sri,Dept of CSE Page 20


Control Structures in C

{
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.

The Nested for Loop


The concept of using a loop within a loop is called nested loop. If a for loop contains another for
loop statement, such loop is called nested for loop.. A nested for loop can contain any number of
for loop statements within itself. Usually only two loops are used. In this the first loop is called
outer loop and the second is called inner loop. These types of loops are used to create matrix. In
this the outer loop is used for counting rows and the internal loop is used for counting columns.

The syntax and example program is given below.

SYNTAX:-
for (initializing ; test condition ; increment / decrement)
{
statement;
for (initializing ; test condition ; increment / decrement)
{
body of inner loop;
}
statement;
}

Example: Write a program to generate a matrix of order4*4 contain symbol*(asterisk).


/*program to generate a matrix oforder4*4 containing symbol*(asterisk)*/
#include<stdio.h>
void main ( )
{

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”);
}
}

OUTPUT OF THIS PROGRAM IS


****
****
****
****

Comparison among the loops :


The comparison among the three types of loops for loop, while loop and do....while loop is given
below.

No. Topics For loop While loop Do...while loop


01 Initialization of In the parenthesis of the Before the loop. Before the loop or in
condition loop. the body of the loop.
variable
02 Test condition Before the body of the Before the body of After the body of the
loop. the loop. loop.
03 Updating the After the first execution. After the first After the first
condition execution. execution.
variable
04 Type Entry controlled loop. Entry controlled Exit controlled loop.
loop.

05 Loop variable Counter. Counter. Sentinel & counter


06 Structure for(n = 1; n <= 10; n++) n = 1; n = 1;
{ while(n <=10) do
======== { {
======== ========== ========
} ========== ========
n=n+1; n = n + 1;
} }
while(n<=10);

Prepared by T.Aruna Sri,Dept of CSE Page 22


Control Structures in C
Differences between the counter and sentinel controlled loops are as follows.
No. Topics Counter controlled loop Sentinel controlled loop
01 Number of Previously known number of Unknown number of execution
execution execution occurs. occurs.
02 Condition Condition variable is known as Condition variable is known as
variable counter variable. sentinel variable.
03 Value and The value of the variable and the The limitation for the condition
limitation of limitation of the condition for the variable is strict but the value of
variable variable both are strict. the variable varies in this case.
04 Examples ======
do
{
printf(“Input a number.\n”);
scanf("%d", &num);
}
while(num>0);
======
========

Jumping Control Structures:


goto :
The goto statement is used to alter the normal sequence of program execution by transferring
control to some other part of the program unconditionally. In its general form, the goto statement
is written as
goto label;
where the label is an identifier that is used to label the target statement to which the
control is transferred. Control may be transferred to anywhere within the current function. The
target statement must be labeled, and a colon must follow the label. Thus the target statement
will appear as
label:statement;

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.

Prepared by T.Aruna Sri,Dept of CSE Page 23


Control Structures in C

Reasons to avoid goto statement


Though, using goto statement give power to jump to any part of program, using goto statement
makes the logic of the program complex and tangled. In modern programming, goto statement is
considered a harmful construct and a bad programming practice.
The goto statement can be replaced in most of C program with the use of break and continue
statements. In fact, any program in C programming can be perfectly written without the use of
goto statement. All programmer should try to avoid goto statement as possible as they can.
#include<stdio.h>
main( )
{
int n=1,x,sum=0;
while(n<=10)
{
scanf(“%d” ,&x);
if(x<0) goto
error;
sum+=x;
++n;
}

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;

Prepared by T.Aruna Sri,Dept of CSE Page 24


Control Structures in C

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;
}

Can break Statement be Used Inside if Construct


The break does not work with if. It only works only with in loops and switches. After observing the
sample programs where break is used in conjunction with if structure inside the for loop and
while loop, the common wrong assumption is that the break statement can be used inside if construct.
Thinking that a break refers to an if construct when it really refers to the enclosing
while or for loop has created some high quality bugs.

This is illustrated in the example below.


#include <stdio.h>
int main()
{
int i;
printf(“Enter your choice from 1-3, where apple-1,Orange-2, grapes- 3, Enter 4 to exit “);
scanf(“%d”,&i);
if(i==1)
Printf(“Your choice of fruit is Apple “);

Prepared by T.Aruna Sri,Dept of CSE Page 25


Control Structures in C

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++)

Prepared by T.Aruna Sri,Dept of CSE Page 26


Control Structures in C
{
if ((i==3) || (i==5))
continue;
sum += i;
}
printf("The sum of 1, 2, 4, 6, and 7 is: %d\n", sum);
}
OUTPUT
The sum of 1, 2, 4, 6, and 7 is: 20

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.

Prepared by T.Aruna Sri,Dept of CSE Page 27


Control Structures in C

Difference between break and Continue


Break Continue
Break Statement is used to transfer control of Continue Statement is used to skip some
statements of the loop and moves to the next
the program outside loop or switch case iteration in the loop
statement either conditionally or
unconditionally
It is used in loop as well as switch case It is used only within the loop
statement
Ex: Ex:
main() main()
{ {
int i; int i;
for(i=0;i<=10;i++) for(i=0;i<=10;i++)
{ {
if(i%5==0) if(i%5==0)
break; continue;
else else
printf("%d",i); printf("%d",i);
} }
Output: Output:
1234 123456789

Prepared by T.Aruna Sri,Dept of CSE Page 28

You might also like