Unit II chapter 4 Loops in C

924 views 31 slides Dec 07, 2021
Slide 1
Slide 1 of 31
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29
Slide 30
30
Slide 31
31

About This Presentation

LOOPS IN C
MRS. SOWMYA JYOTHI
PROGRAMMING IN C BY BALAGURUSWAMY


Slide Content

CHAPTER 4
DECISION MAKING and LOOPING
REFERENCE: PROGRAMMING IN C BY BALAGURUSWAMY
MRS. SOWMYA JYOTHI, SDMCBM, MANGALORE

•Aloopisaparticularareaofaprogramwheresome
executablestatementsarewrittenwhichgets
executedbytestingoneormoreconditions.
•So,inlooping,asequenceofstatementsisexecuted
untilsomeconditionsforterminationaresatisfied.
•Aprogramloopthereforeconsistsoftwosegments;
thebodyoftheloopandthecontrolstatement.

Steps of looping process :
A looping process, in general, would include the
following four steps.
1.Setting and initializationof a condition variable.
2.Execution of the statements of the loop.
3.Test for a specified value of the condition variable
for execution of the loop.
4.Incrementing or updating the condition variable.

•Dependingonthepositionofthecontrol
statementintheloop,acontrolstructure
canbeclassifiedintotwotypes;
1.entrycontrolledand
2.exitcontrolled.

•Entrycontrolledloop:Thetypesofloopwherethe
testconditionisstatedbeforethebodyoftheloop,
areknownastheentrycontrolledloop.
Entry controlled loop, the condition is tested before
the execution of the loop. If the test condition is true,
then the loop gets the execution, otherwise not.
For example, the for loopis an entry controlled loop.

Exit controlled loop :
•The types of loop where the test condition is stated
at the end of the body of the loop, are know as the
exit controlled loops.
•So, in the case of the exit controlled loops, the body of the loop
gets executed without testing the given condition for the first
time.
•Then the condition is tested.
•If it comes true, then the loop gets another execution and
continues till the result of the test condition is not false.
•For example, the do statementor the do....while loopis an exit
controlled loop.

Sentinelcontrolledloop:
•Thetypeofloopwherethenumberofexecutionof
theloopisunknown,istermedbysentinel
controlledloop.
•Inthiscase,thevalueofthecontrolvariablediffers
withinalimitationandtheexecutioncanbe
terminatedatanymomentasthevalueofthevariable
isnotcontrolledbytheloop.
•Thecontrolvariableinthiscaseistermedbysentinel
variable.
•Thewhileloopisanexampleofsentinelcontrolled
loop.

The While Statement:
•The simplest of all looping structure in C is the while statement.
•The general format of the while statement is:
while (test condition)
{
body of the loop
}
Thegiventestconditionisevaluatedandiftheconditionistruethenthebodyof
theloopisexecuted.Aftertheexecutionofthebody,thetestconditionisonceagain
evaluatedandifitistrue,thebodyisexecutedonceagain.Thisprocessofrepeated
executionofthebodycontinuesuntilthetestconditionfinallybecomesfalseandthe
controlistransferredoutoftheloop.Onexit,theprogramcontinueswiththe
statementsimmediatelyafterthebodyoftheloop.Thebodyoftheloopmayhave
oneormorestatements.Thebracesareneededonlyifthebodycontainedtwoare
morestatements

Example program for generating ‘N’ numbers using while loop:
# include < stdio.h>
void main()
{
intn, i=1;
printf(“Enter the upper limit number”);
scanf(“%d”, &n);
while(i< = n)
{
printf(“\t%d”,i);
i++;
}
}

For Loop:
The for loop provides a more concise loop control structure.
The general form of the for loop is:
for (initialization; test condition; increment)
{
body of the loop
}

•Whenthecontrolentersforloopthevariablesusedinforloopis
initializedwiththestartingvalue.
•Thevaluewhichwasinitializedisthencheckedwiththegiventest
condition.
•Thetestconditionisarelationalexpression
•Thebodyoftheloopisenteredonlyifthetestconditionissatisfied
andafterthecompletionoftheexecutionoftheloopthecontrolis
transferredbacktotheincrementpartoftheloop.
•Thecontrolvariableisincrementedusinganassignmentstatement.
•Ifthevalueofthecontrolvariablesatisfiesthenthebodyoftheloop
isagainexecuted.Theprocessgoesontillthecontrolvariablefails
tosatisfythecondition.

Additional features of the for loop:
•We can include multiple expressions in any of the fields of for loop
provided that we separate such expressions by commas.
•For example in the for statement that begins
for( i= 0; j = 0; i< 10, j=j-10)
•Sets up two index variables iand j the former initialized to zero and
the latter to 100 before the loop begins.
•Each time after the body of the loop is executed, the value of iwill be
incremented by 1 while the value of j is decremented by 10.

For loop example program:
/* example that finds the sum of the first 15 positive natural numbers*/
#include < stdio.h>
void main()
{
inti;
intsum=0,sum_of_squares=0;
for(i=0;i< = 30; i+=2)
{
sum+=i;
sum_of_squares+=i*i;
}
printf(“Sum of first 15 positive even numbers=%d\n”,sum);
printf(“Sum of their squares=%d\n”,sum_of_squares);

/*Program to find whether the number is odd or even*/
#include<stdio.h>
main()
{
inti, n=5;
for(i=1;i<n;i=i+1)
{
switch(i%2)
{
case0:printf("thenumber%diseven\n",i);
break;
case1:printf("thenumber%disodd\n",i);
break;
}
}
}

The Do while statement:
•Thedowhileloopisakindofloopsimilartothewhileloopincontrast
towhileloop,thedowhilelooptestsatthebottomoftheloopafter
executingthebodyoftheloop.Sincethebodyoftheloopisexecuted
firstandthentheloopconditionischecked.Wecanbeassuredthat
thebodyoftheloopisexecutedatleastonce.

The syntax of the do while loop is:
do
{
statement;
}
while(expression);
If the condition expression is true then the body is executed again and this
process continues till the conditional expression becomes false. When the
expression becomes false. When the expression becomes false the loop
terminates.

do
{
printf(“Enter the number:”);
scanf(“%d”, &num);
}
while(num>0);

Example :The following do....whileloop is an example of sentinel
controlled loop.
do
{
printf(“Input a number.\n”);
scanf("%d", &num);
}
while(num>0);
= = = = = =
Intheaboveexample,theloopwillbeexecutedtilltheenteredvalue
ofthevariablenumisnot0orlessthen0.
Thisisasentinelcontrolledloopandherethevariablenumisa
sentinelvariable.

The Break Statement:
•Sometimeswhileexecutingaloopitbecomesdesirabletoskipapart
ofthelooporquittheloopassoonascertainconditionoccurs.
•Forexampleconsidersearchingaparticularnumberinasetof100
numbersassoonasthesearchnumberisfounditisdesirableto
terminatetheloop.
•Clanguagepermitsajumpfromonestatementtoanotherwithina
loopaswellastojumpoutoftheloop.Thebreakstatementallows
ustoaccomplishthistask.
•Abreakstatementprovidesanearlyexitfromfor,while,doand
switchconstructs.Abreakcausestheinnermostenclosingloopor
switchtobeexitedimmediately.

/* A program to find the sum*/
#include < stdio.h>
void main()
{
inti;
float sum=0;
printf(“Input the numbers, -1 to end\n”);
while(1)
{
scanf(“%d”,&i);
if(i==-1)
{
break;
}
sum=sum+i;
}
printf(“\nTotal:%d”,sum);}

Continuestatement:
•Duringloopoperationsitmaybenecessarytoskipapartof
thebodyoftheloopundercertainconditions.
•LikethebreakstatementCsupportssimilarstatementcalled
continuestatement.
•Thecontinuestatementcausesthelooptobecontinued
withthenextiterationafterskippinganystatementin
between.
•Thecontinuewiththenextiterationtheformatofthe
continuestatementissimply:
continue;

#include < stdio.h>
void main()
{
inti=1, num, sum=0;
for (i= 0; i< 5; i++)
{
printf(“Enter the integer”);
scanf(“%d”, &num);
if(num< 0)
{
printf(“You have entered a negative number”);
continue;
}
sum+=num;
}

No. Topics For loop While loop Do...while loop
01Initializationof
condition
variable
Intheparenthesisof
theloop.
Beforetheloop. Beforetheloopor
inthebodyofthe
loop.
02TestconditionBeforethebodyofthe
loop.
Beforethebodyof
theloop.
Afterthebodyof
theloop.
03Updatingthe
condition
variable
Afterthe first
execution.
Afterthefirst
execution.
Afterthefirst
execution.
04Type Entrycontrolledloop.Entrycontrolled
loop.
Exitcontrolledloop.
05LoopvariableCounter. Counter. Sentinel&counter
Tags