SlideShare ist ein Scribd-Unternehmen logo
1 von 34
1
Let Us
Looping
Introduction
 One of the fundamental properties of a programming
language is the ability to repetitively execute a sequence of
statements which is called decision making and looping.
“Decision making and looping” is one of the most
important concepts of computer programming.
 Programs should be able to make decisions based on the
condition provided and then repeat a specific chunk of code
or statement again and again.
 These looping capabilities enable programmers to develop
concise programs containing repetitive processes that could
otherwise require an excessive number of statements. It
enable us to repeat a specific section of code or statement
without the use of goto statements .
 In looping a sequence of statements are executed until some
conditions for termination of loop are satisfied.
Loop Segments
 A program loop therefore consists of two segments:
 one known as the body of the loop and the other known as
the control statement. The control statement tests certain
conditions and then directs the repeated execution of the
statements contained in the body of the loop.
Control Statement
Body of the Loop
Looping Types
 Depending on the position of the control statement in the
loop, a loop control structure may be classified either as
1. The entry controlled loop
2. The exit controlled loop.
 Based on the nature of the control variables and the kind
of value assigned to, the loops may be classified into two
general categories
1. The counter controlled loop
2. The sentinel controlled loop
Entry Controlled Loop
 The types of loop where the test condition is stated before
the body of the loop, are known as the entry controlled loop.
So in the case of an 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 loop is an entry
controlled loop. In the given figure, the structure of an entry
controlled loop is shown.
Entry Controlled Loop- Flowchart
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 execution 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.
 In case of exit controlled loop the body of the loop is
executed unconditionally for the first time without testing
the condition.
 For example, the do statement or the do....while loop is an
exit controlled loop. The structure of an exit controlled loop
is given in the given figure.
Exit Controlled Loop- Flowchart
Entry VS Exit Controlled Loop
 Test condition: Test condition appears at the beginning in
entry controlled loop where Test condition appears at the
end in exit controlled loop.
 Control variable: In entry controlled loop control variable
is counter variable but in exit controlled loop Control
variable can be counter & sentinel variable
 Execution: In entry controlled loop each execution occurs
by testing condition but in exit controlled loop each
execution except the first one occurs by testing condition
Counter Controlled Loop
 The type of loops, where the number of the execution is
known in advance are termed by the counter controlled
loop. That means, in this case, the value of the variable
which controls the execution of the loop is previously
known. The control variable is known as counter. The
counter must be initialized, tested and updated properly for
the desired loop operations. The number of times we want
to execute the loop may be a constant or variable.
 A counter controlled loop is also called definite repetition
loop because the number of repetitions is known before the
loop begins executing.
 Example : A while loop is an example of counter controlled
loop.
Counter Controlled Loop
sum = 0;
n = 1;
while (n <= 10)
{
sum = sum + n*n;
n = n+ 1;
}
This is a typical example of counter controlled loop. Here,
the loop will be executed exactly 10 times for
n = 1,2,3,......,10
Sentinel Controlled Loop
 The type of loop where the number of execution of the loop
is unknown, is termed by sentinel controlled loop. In this
case, the value of the control variable differs within a
limitation and the execution can be terminated at any
moment as the value of the variable is not controlled by the
loop. The control variable in this case is termed by sentinel
variable.
 A sentinel controlled loop is sometimes called indefinite
repetition loop because the number of repetitions is not
known before the loop begins executing.
 Example : The following do....while loop is an example of
sentinel controlled loop.
Sentinel Controlled Loop
do
{
printf(“Input a number.n”);
scanf("%d", &num);
}
while(num>0);
In the above example, the loop will be executed till the
entered value of the variable num is not 0 or less then 0. This
is a sentinel controlled loop and here the variable num is a
sentinel variable
Counter VS Sentinel Loop
 Number of execution: In counter controlled loop
execution occurs according to the previously known
number but in sentinel controlled loop unknown number
of execution occurs
 Condition variable: In counter controlled loop condition
variable is known as counter variable but in sentinel
controlled loop condition variable is known as sentinel
variable
 Value and limitation of variable: In counter controlled
loop the value of the variable and the limitation of the
condition for the variable both are strict but in sentinel
controlled loop the limitation for the condition variable is
strict but the value of the variable varies in this case
Steps of Looping a Process
 A looping process, in general, would include the
following four steps. The given steps may come at any
order depending on the type of the loop.
1. Setting and initialization of 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.
Types of Loop
 The C language supports three types of looping
statement:
1. The for statement
2. The do while statement
3. The while do statement
The for Statement
 The for loop is an entry controlled loop. It has the
following structure:
for(initialization; test-condition; increment/decrement)
{
body of the loop;
}
Analyze the for Statement
for The keyword of for loop
Initialization Set the initial value of the loop
control variable
Test-condition Set the condition to control the
loop via loop control variable
Inc/dec Update the value of the loop control
variable
Body of the loop Statements to be executed or
controlled under the for loop
Analyze the for Statement
 Initialization is done first using the assignment statements
such as i=1 or count=0. where i and count are known as loop
control variable.
 The value of the loop control variable is tested using the test
condition . The test condition is a relational expression, such as
i < 10 that determines when the loop will exit. If the condition
is true the body of the loop is executed; otherwise the loop is
terminated and the execution continues with the statement
that immediately follows the loop.
 When the body of the loop is executed, the control is
transferred back to the for statement after evaluating the last
statement such as increment/decrement and the new value
of the control variable is again tested to see whether it satisfies
the loop condition or not
Analyze the for Statement
 When the body of the loop is executed, the control is
transferred back to the for statement after evaluating the
last statement such as increment/decrement and the new
value of the control variable is again tested to see whether it
satisfies the loop condition or not. If the condition is
satisfied again, then the body of the loop is executed again.
This process continues till the value of the control variable
fails to satisfy the test condition.
 One of the important points about the for loop is that all the
three actions initialization, test-condition and
increment/decrement are placed within the for statement
itself, thus making the user comfortable but it is not
mandatory.
Analyze the for Statement
 The for loop in C has several capabilities that are not found in
other loop constructs. For example more than one variable can
be initialized at a time in the for statement separated by a
comma. Example: for (m=1, n=10; m<=n; m++)
 Like the initialization section the increment section can have
more than one part separated by a comma. For example:
for (m=1, n=10; m<=n; m++, n--)
 The test condition can have compound relation and the testing
need not to be limited only to the loop control variable.
Example: for (m=1, n=10; m<10 && n< 20; m++)
 It is also permissible to use expressions in the assignment
statements of initialization and increment/decrement.
Example: for( i=(m+n)/2; i>1; i=i/2 )
Analyze the for Statement
 Another unique and important aspect of for loop is that one or
more sections can be omitted, if necessary. However in such
cases the semicolons separating the sections must remain. Both
initialization and increment/decrement sections can be omitted
within the for statement. The initialization can be done before
the for statement and increment/decrement can be performed
within the body of the loop or even after the body of the loop.
Example:
i=5;
for( ; i<=15; )
{
printf(“ The current value of i=%d”, i);
i=i+1;
}
Analyze the for Statement
 Again the test condition can also be omitted. If the test
condition is not present then the for statement behaves like a
infinite loop. Such loop can be broken using break and goto
statement. Example:
for(; ;)
printf(“Hello World”);
 The C compiler does not give an error message if a semicolon is
placed at the end of the for statement but it is considered as a
null statement. Example:
for(i=0;i<=2;i++) ;
Selecting a Loop
 It is the programmer's choice to use which loop depending
on the type of the problem and how he want to solve it. But
still there are some strategy that are used while choosing a
loop to solve a problem:
 Analyze the problem and see whether it required a pre-test
or post-test loop. If it requires a post-test loop then we can
use only one loop that is do while loop. If it requires a pre-
test loop then we have two choices for loop and while loop.
 Decide whether the loop termination requires counter
based control or sentinel based control. Use for loop if the
counter based control is necessary. Use while loop if the
sentinel based control is required.
Jumping out a Loop
 C permits a jump from one statement to another within a loop
as well as a jump out of a loop. The break and goto statements
can be used to jump out of a loop.
 When a break statement is encountered inside a loop, the loop
is immediately exited and the program continues with the
statement immediately following the loop. When the loops are
nested, the break would only exit from the loop containing it.
That is the break will exit only a single loop.
 While a goto statement can transfer the control to any place in
the program. It is useful to provide branching within a loop.
Another important use of goto is to exit from deeply nested
loops when an error occurs.
The While Statement
 The simplest of all the looping structures is the while
statement. The basic format of the while statement is :
while (test-condition)
{
body of the loop;
}
The While Statement
 The while is an entry controlled loop statement. The test
condition is evaluated and if the condition is true, then the
body of the loop is executed. After execution of the body the
test condition is once again evaluated and if it is true, the body
is executed once again.
 This process of repeated execution of the body continues until
the test condition becomes false and the control is transferred
out of the loop. On exit the program continues with the
statement immediately following the body of the loop.
 The important thing to notice that if the test condition is false
then the controlled statements are not executed not even once
unlike the do while loop.
The Do While Statement
 On some occasions it might be necessary to execute the body of
the loop before the test is performed. Such situations can be
handled by using do while loop. It has the structure:
do
{
body of the loop;
}
while(test condition)
The Do While Statement
 On reaching the do statement,
Comparison of Loops
No. Topics For loop While loop Do...while loop
01 Initialization
of condition
variable
Before or within the
parenthesis of the
loop.
Before the loop. Before the loop or
in the body of the
loop.
02 Test
condition
Before the body of the
loop.
Before the body of
the loop.
After the body of
the loop.
03 Updating the
condition
variable
After the first
execution.
After the first
execution.
After the first
execution.
04 Type Entry controlled loop. Entry controlled
loop.
Exit controlled
loop.
05 Loop
variable
Counter. Counter. Sentinel & counter
Questions?
References
 The C Programming Language (9780131103627): Brian W.
Kernighan, Dennis M. Ritchie
 C Programming: A Modern Approach, 2nd Edition By K. N.
King
 Absolute Beginner’s Guide To C, 2nd Edition By Greg Perry
34
Md. Shakhawat Hossain
Student of Department of Computer Science &
Engineering
University of Rajshahi
E-mail: mshimul86@gmail.com

Weitere ähnliche Inhalte

Was ist angesagt? (20)

Structure of a C program
Structure of a C programStructure of a C program
Structure of a C program
 
Unit ii chapter 2 Decision making and Branching in C
Unit ii chapter 2 Decision making and Branching in CUnit ii chapter 2 Decision making and Branching in C
Unit ii chapter 2 Decision making and Branching in C
 
Presentation on C Switch Case Statements
Presentation on C Switch Case StatementsPresentation on C Switch Case Statements
Presentation on C Switch Case Statements
 
Function C programming
Function C programmingFunction C programming
Function C programming
 
User defined functions in C
User defined functions in CUser defined functions in C
User defined functions in C
 
data types in C programming
data types in C programmingdata types in C programming
data types in C programming
 
While , For , Do-While Loop
While , For , Do-While LoopWhile , For , Do-While Loop
While , For , Do-While Loop
 
Union in C programming
Union in C programmingUnion in C programming
Union in C programming
 
C program
C programC program
C program
 
10. switch case
10. switch case10. switch case
10. switch case
 
Types of loops in c language
Types of loops in c languageTypes of loops in c language
Types of loops in c language
 
C decision making and looping.
C decision making and looping.C decision making and looping.
C decision making and looping.
 
C tokens
C tokensC tokens
C tokens
 
Loops in c
Loops in cLoops in c
Loops in c
 
Java program structure
Java program structureJava program structure
Java program structure
 
C Token’s
C Token’sC Token’s
C Token’s
 
Introduction to c programming
Introduction to c programmingIntroduction to c programming
Introduction to c programming
 
Control structures in c
Control structures in cControl structures in c
Control structures in c
 
Input output statement in C
Input output statement in CInput output statement in C
Input output statement in C
 
Unit II chapter 4 Loops in C
Unit II chapter 4 Loops in CUnit II chapter 4 Loops in C
Unit II chapter 4 Loops in C
 

Andere mochten auch

C language control statements
C language  control statementsC language  control statements
C language control statementssuman Aggarwal
 
Loops in C Programming
Loops in C ProgrammingLoops in C Programming
Loops in C ProgrammingHimanshu Negi
 
Data structure using c bcse 3102 pcs 1002
Data structure using c bcse 3102 pcs 1002Data structure using c bcse 3102 pcs 1002
Data structure using c bcse 3102 pcs 1002SANTOSH RATH
 
Optimus protein
Optimus proteinOptimus protein
Optimus proteinEdDonnelly
 
Loneliness and Longevity
Loneliness and LongevityLoneliness and Longevity
Loneliness and LongevityKatherine Chen
 
Li Cppi Corporate Overview
Li Cppi Corporate OverviewLi Cppi Corporate Overview
Li Cppi Corporate Overviewjwarnerinmiami
 
Chapter 1 -_characterization_of_distributed_systems
Chapter 1 -_characterization_of_distributed_systemsChapter 1 -_characterization_of_distributed_systems
Chapter 1 -_characterization_of_distributed_systemsFrancelyno Murela
 
Staff Walking Survey Results
Staff Walking Survey ResultsStaff Walking Survey Results
Staff Walking Survey ResultsKatherine Chen
 
Portfolio
PortfolioPortfolio
Portfoliowrwolff
 
3 easy changes to start taking vitamins, doing crunches, and eating healthier
3 easy changes to start taking vitamins, doing crunches, and eating healthier3 easy changes to start taking vitamins, doing crunches, and eating healthier
3 easy changes to start taking vitamins, doing crunches, and eating healthierKatherine Chen
 
Walking for entertainment
Walking for entertainmentWalking for entertainment
Walking for entertainmentKatherine Chen
 
Compuware Mobility Presentation Overview
Compuware Mobility Presentation OverviewCompuware Mobility Presentation Overview
Compuware Mobility Presentation OverviewMPLS-Services-Compuware
 
How to start going to the gym: what worked/is working for me!
How to start going to the gym: what worked/is working for me!How to start going to the gym: what worked/is working for me!
How to start going to the gym: what worked/is working for me!Katherine Chen
 
STP engagement and consultation for NHS & Local Authorities
STP engagement and consultation for NHS & Local AuthoritiesSTP engagement and consultation for NHS & Local Authorities
STP engagement and consultation for NHS & Local AuthoritiesRhion Jones
 
Ebook competencias-digitales-blog
Ebook competencias-digitales-blogEbook competencias-digitales-blog
Ebook competencias-digitales-blogDaniel Gracia
 
Data structures using C
Data structures using CData structures using C
Data structures using CPdr Patnaik
 

Andere mochten auch (20)

C language control statements
C language  control statementsC language  control statements
C language control statements
 
Loops in C Programming
Loops in C ProgrammingLoops in C Programming
Loops in C Programming
 
Data structure using c bcse 3102 pcs 1002
Data structure using c bcse 3102 pcs 1002Data structure using c bcse 3102 pcs 1002
Data structure using c bcse 3102 pcs 1002
 
Goal: 50 and healthy!
Goal: 50 and healthy!Goal: 50 and healthy!
Goal: 50 and healthy!
 
Optimus protein
Optimus proteinOptimus protein
Optimus protein
 
Loneliness and Longevity
Loneliness and LongevityLoneliness and Longevity
Loneliness and Longevity
 
Li Cppi Corporate Overview
Li Cppi Corporate OverviewLi Cppi Corporate Overview
Li Cppi Corporate Overview
 
Chapter 1 -_characterization_of_distributed_systems
Chapter 1 -_characterization_of_distributed_systemsChapter 1 -_characterization_of_distributed_systems
Chapter 1 -_characterization_of_distributed_systems
 
Staff Walking Survey Results
Staff Walking Survey ResultsStaff Walking Survey Results
Staff Walking Survey Results
 
Portfolio
PortfolioPortfolio
Portfolio
 
3 easy changes to start taking vitamins, doing crunches, and eating healthier
3 easy changes to start taking vitamins, doing crunches, and eating healthier3 easy changes to start taking vitamins, doing crunches, and eating healthier
3 easy changes to start taking vitamins, doing crunches, and eating healthier
 
Walking for entertainment
Walking for entertainmentWalking for entertainment
Walking for entertainment
 
Goal: 50 and healthy!
Goal: 50 and healthy!Goal: 50 and healthy!
Goal: 50 and healthy!
 
Compuware Mobility Presentation Overview
Compuware Mobility Presentation OverviewCompuware Mobility Presentation Overview
Compuware Mobility Presentation Overview
 
How to start going to the gym: what worked/is working for me!
How to start going to the gym: what worked/is working for me!How to start going to the gym: what worked/is working for me!
How to start going to the gym: what worked/is working for me!
 
Predicting Motivation
Predicting MotivationPredicting Motivation
Predicting Motivation
 
Web engineering cse ru
Web engineering cse ruWeb engineering cse ru
Web engineering cse ru
 
STP engagement and consultation for NHS & Local Authorities
STP engagement and consultation for NHS & Local AuthoritiesSTP engagement and consultation for NHS & Local Authorities
STP engagement and consultation for NHS & Local Authorities
 
Ebook competencias-digitales-blog
Ebook competencias-digitales-blogEbook competencias-digitales-blog
Ebook competencias-digitales-blog
 
Data structures using C
Data structures using CData structures using C
Data structures using C
 

Ähnlich wie Looping Fundamentals Explained

Ähnlich wie Looping Fundamentals Explained (20)

C Programming - Decision making, Looping
C  Programming - Decision making, LoopingC  Programming - Decision making, Looping
C Programming - Decision making, Looping
 
Chapter 9 - Loops in C++
Chapter 9 - Loops in C++Chapter 9 - Loops in C++
Chapter 9 - Loops in C++
 
Control statement in c
Control statement in cControl statement in c
Control statement in c
 
Control structure
Control structureControl structure
Control structure
 
What is loops? What is For loop?
What is loops? What is For loop?What is loops? What is For loop?
What is loops? What is For loop?
 
Java Repetiotion Statements
Java Repetiotion StatementsJava Repetiotion Statements
Java Repetiotion Statements
 
Comp ppt (1)
Comp ppt (1)Comp ppt (1)
Comp ppt (1)
 
Programming Fundamentals lecture 8
Programming Fundamentals lecture 8Programming Fundamentals lecture 8
Programming Fundamentals lecture 8
 
CONTROL STMTS.pptx
CONTROL STMTS.pptxCONTROL STMTS.pptx
CONTROL STMTS.pptx
 
Control statements anil
Control statements anilControl statements anil
Control statements anil
 
whileloop-161225171903.pdf
whileloop-161225171903.pdfwhileloop-161225171903.pdf
whileloop-161225171903.pdf
 
While loop
While loopWhile loop
While loop
 
UNIT 2 PPT.pdf
UNIT 2 PPT.pdfUNIT 2 PPT.pdf
UNIT 2 PPT.pdf
 
Loops In C++
Loops In C++Loops In C++
Loops In C++
 
cpu.pdf
cpu.pdfcpu.pdf
cpu.pdf
 
Mca i pic u-3 handling input output and control statements
Mca i pic u-3 handling input output and control statementsMca i pic u-3 handling input output and control statements
Mca i pic u-3 handling input output and control statements
 
Cse lecture-7-c loop
Cse lecture-7-c loopCse lecture-7-c loop
Cse lecture-7-c loop
 
Diploma ii cfpc u-3 handling input output and control statements
Diploma ii  cfpc u-3 handling input output and control statementsDiploma ii  cfpc u-3 handling input output and control statements
Diploma ii cfpc u-3 handling input output and control statements
 
Control structures in C
Control structures in CControl structures in C
Control structures in C
 
handling input output and control statements
 handling input output and control statements handling input output and control statements
handling input output and control statements
 

Mehr von Hossain Md Shakhawat (20)

Recipe for the effective presentaion
Recipe for the effective presentaionRecipe for the effective presentaion
Recipe for the effective presentaion
 
The Road to Higher study in Japan
The Road to Higher study in JapanThe Road to Higher study in Japan
The Road to Higher study in Japan
 
Application of dfs
Application of dfsApplication of dfs
Application of dfs
 
Breadth first search and depth first search
Breadth first search and  depth first searchBreadth first search and  depth first search
Breadth first search and depth first search
 
Islamic jurisprudence
Islamic jurisprudenceIslamic jurisprudence
Islamic jurisprudence
 
Introduction to Medical Imaging
Introduction to Medical ImagingIntroduction to Medical Imaging
Introduction to Medical Imaging
 
Jpeg compression
Jpeg compressionJpeg compression
Jpeg compression
 
Surah Fatiha
Surah FatihaSurah Fatiha
Surah Fatiha
 
Hashing
HashingHashing
Hashing
 
Digital signature
Digital signatureDigital signature
Digital signature
 
Caesar cipher
Caesar cipherCaesar cipher
Caesar cipher
 
Rsa rivest shamir adleman
Rsa rivest shamir adlemanRsa rivest shamir adleman
Rsa rivest shamir adleman
 
Fundamentals of cryptography
Fundamentals of cryptographyFundamentals of cryptography
Fundamentals of cryptography
 
Introduction to programming with c,
Introduction to programming with c,Introduction to programming with c,
Introduction to programming with c,
 
Introduction to digital image processing
Introduction to digital image processingIntroduction to digital image processing
Introduction to digital image processing
 
History of computing
History of computingHistory of computing
History of computing
 
Introduction to Printers
Introduction to PrintersIntroduction to Printers
Introduction to Printers
 
Input devices_(Mouse and Keyboard)
Input devices_(Mouse and Keyboard)Input devices_(Mouse and Keyboard)
Input devices_(Mouse and Keyboard)
 
Binary search tree(bst)
Binary search tree(bst)Binary search tree(bst)
Binary search tree(bst)
 
Introduction to computer
Introduction to computerIntroduction to computer
Introduction to computer
 

Kürzlich hochgeladen

ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...JhezDiaz1
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfErwinPantujan2
 
Science 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxScience 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxMaryGraceBautista27
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17Celine George
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfJemuel Francisco
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxAshokKarra1
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptxmary850239
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Celine George
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONHumphrey A Beña
 
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYKayeClaireEstoconing
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPCeline George
 
Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)cama23
 
Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Seán Kennedy
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management systemChristalin Nelson
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Jisc
 

Kürzlich hochgeladen (20)

ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
 
Science 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxScience 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptx
 
Raw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptxRaw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptx
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptx
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
 
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptxFINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
 
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptxYOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
 
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERP
 
Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)
 
Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management system
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...
 

Looping Fundamentals Explained

  • 3. Introduction  One of the fundamental properties of a programming language is the ability to repetitively execute a sequence of statements which is called decision making and looping. “Decision making and looping” is one of the most important concepts of computer programming.  Programs should be able to make decisions based on the condition provided and then repeat a specific chunk of code or statement again and again.  These looping capabilities enable programmers to develop concise programs containing repetitive processes that could otherwise require an excessive number of statements. It enable us to repeat a specific section of code or statement without the use of goto statements .  In looping a sequence of statements are executed until some conditions for termination of loop are satisfied.
  • 4. Loop Segments  A program loop therefore consists of two segments:  one known as the body of the loop and the other known as the control statement. The control statement tests certain conditions and then directs the repeated execution of the statements contained in the body of the loop. Control Statement Body of the Loop
  • 5. Looping Types  Depending on the position of the control statement in the loop, a loop control structure may be classified either as 1. The entry controlled loop 2. The exit controlled loop.  Based on the nature of the control variables and the kind of value assigned to, the loops may be classified into two general categories 1. The counter controlled loop 2. The sentinel controlled loop
  • 6. Entry Controlled Loop  The types of loop where the test condition is stated before the body of the loop, are known as the entry controlled loop. So in the case of an 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 loop is an entry controlled loop. In the given figure, the structure of an entry controlled loop is shown.
  • 8. 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 execution 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.  In case of exit controlled loop the body of the loop is executed unconditionally for the first time without testing the condition.  For example, the do statement or the do....while loop is an exit controlled loop. The structure of an exit controlled loop is given in the given figure.
  • 10. Entry VS Exit Controlled Loop  Test condition: Test condition appears at the beginning in entry controlled loop where Test condition appears at the end in exit controlled loop.  Control variable: In entry controlled loop control variable is counter variable but in exit controlled loop Control variable can be counter & sentinel variable  Execution: In entry controlled loop each execution occurs by testing condition but in exit controlled loop each execution except the first one occurs by testing condition
  • 11. Counter Controlled Loop  The type of loops, where the number of the execution is known in advance are termed by the counter controlled loop. That means, in this case, the value of the variable which controls the execution of the loop is previously known. The control variable is known as counter. The counter must be initialized, tested and updated properly for the desired loop operations. The number of times we want to execute the loop may be a constant or variable.  A counter controlled loop is also called definite repetition loop because the number of repetitions is known before the loop begins executing.  Example : A while loop is an example of counter controlled loop.
  • 12. Counter Controlled Loop sum = 0; n = 1; while (n <= 10) { sum = sum + n*n; n = n+ 1; } This is a typical example of counter controlled loop. Here, the loop will be executed exactly 10 times for n = 1,2,3,......,10
  • 13. Sentinel Controlled Loop  The type of loop where the number of execution of the loop is unknown, is termed by sentinel controlled loop. In this case, the value of the control variable differs within a limitation and the execution can be terminated at any moment as the value of the variable is not controlled by the loop. The control variable in this case is termed by sentinel variable.  A sentinel controlled loop is sometimes called indefinite repetition loop because the number of repetitions is not known before the loop begins executing.  Example : The following do....while loop is an example of sentinel controlled loop.
  • 14. Sentinel Controlled Loop do { printf(“Input a number.n”); scanf("%d", &num); } while(num>0); In the above example, the loop will be executed till the entered value of the variable num is not 0 or less then 0. This is a sentinel controlled loop and here the variable num is a sentinel variable
  • 15. Counter VS Sentinel Loop  Number of execution: In counter controlled loop execution occurs according to the previously known number but in sentinel controlled loop unknown number of execution occurs  Condition variable: In counter controlled loop condition variable is known as counter variable but in sentinel controlled loop condition variable is known as sentinel variable  Value and limitation of variable: In counter controlled loop the value of the variable and the limitation of the condition for the variable both are strict but in sentinel controlled loop the limitation for the condition variable is strict but the value of the variable varies in this case
  • 16. Steps of Looping a Process  A looping process, in general, would include the following four steps. The given steps may come at any order depending on the type of the loop. 1. Setting and initialization of 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.
  • 17. Types of Loop  The C language supports three types of looping statement: 1. The for statement 2. The do while statement 3. The while do statement
  • 18. The for Statement  The for loop is an entry controlled loop. It has the following structure: for(initialization; test-condition; increment/decrement) { body of the loop; }
  • 19. Analyze the for Statement for The keyword of for loop Initialization Set the initial value of the loop control variable Test-condition Set the condition to control the loop via loop control variable Inc/dec Update the value of the loop control variable Body of the loop Statements to be executed or controlled under the for loop
  • 20. Analyze the for Statement  Initialization is done first using the assignment statements such as i=1 or count=0. where i and count are known as loop control variable.  The value of the loop control variable is tested using the test condition . The test condition is a relational expression, such as i < 10 that determines when the loop will exit. If the condition is true the body of the loop is executed; otherwise the loop is terminated and the execution continues with the statement that immediately follows the loop.  When the body of the loop is executed, the control is transferred back to the for statement after evaluating the last statement such as increment/decrement and the new value of the control variable is again tested to see whether it satisfies the loop condition or not
  • 21. Analyze the for Statement  When the body of the loop is executed, the control is transferred back to the for statement after evaluating the last statement such as increment/decrement and the new value of the control variable is again tested to see whether it satisfies the loop condition or not. If the condition is satisfied again, then the body of the loop is executed again. This process continues till the value of the control variable fails to satisfy the test condition.  One of the important points about the for loop is that all the three actions initialization, test-condition and increment/decrement are placed within the for statement itself, thus making the user comfortable but it is not mandatory.
  • 22. Analyze the for Statement  The for loop in C has several capabilities that are not found in other loop constructs. For example more than one variable can be initialized at a time in the for statement separated by a comma. Example: for (m=1, n=10; m<=n; m++)  Like the initialization section the increment section can have more than one part separated by a comma. For example: for (m=1, n=10; m<=n; m++, n--)  The test condition can have compound relation and the testing need not to be limited only to the loop control variable. Example: for (m=1, n=10; m<10 && n< 20; m++)  It is also permissible to use expressions in the assignment statements of initialization and increment/decrement. Example: for( i=(m+n)/2; i>1; i=i/2 )
  • 23. Analyze the for Statement  Another unique and important aspect of for loop is that one or more sections can be omitted, if necessary. However in such cases the semicolons separating the sections must remain. Both initialization and increment/decrement sections can be omitted within the for statement. The initialization can be done before the for statement and increment/decrement can be performed within the body of the loop or even after the body of the loop. Example: i=5; for( ; i<=15; ) { printf(“ The current value of i=%d”, i); i=i+1; }
  • 24. Analyze the for Statement  Again the test condition can also be omitted. If the test condition is not present then the for statement behaves like a infinite loop. Such loop can be broken using break and goto statement. Example: for(; ;) printf(“Hello World”);  The C compiler does not give an error message if a semicolon is placed at the end of the for statement but it is considered as a null statement. Example: for(i=0;i<=2;i++) ;
  • 25. Selecting a Loop  It is the programmer's choice to use which loop depending on the type of the problem and how he want to solve it. But still there are some strategy that are used while choosing a loop to solve a problem:  Analyze the problem and see whether it required a pre-test or post-test loop. If it requires a post-test loop then we can use only one loop that is do while loop. If it requires a pre- test loop then we have two choices for loop and while loop.  Decide whether the loop termination requires counter based control or sentinel based control. Use for loop if the counter based control is necessary. Use while loop if the sentinel based control is required.
  • 26. Jumping out a Loop  C permits a jump from one statement to another within a loop as well as a jump out of a loop. The break and goto statements can be used to jump out of a loop.  When a break statement is encountered inside a loop, the loop is immediately exited and the program continues with the statement immediately following the loop. When the loops are nested, the break would only exit from the loop containing it. That is the break will exit only a single loop.  While a goto statement can transfer the control to any place in the program. It is useful to provide branching within a loop. Another important use of goto is to exit from deeply nested loops when an error occurs.
  • 27. The While Statement  The simplest of all the looping structures is the while statement. The basic format of the while statement is : while (test-condition) { body of the loop; }
  • 28. The While Statement  The while is an entry controlled loop statement. The test condition is evaluated and if the condition is true, then the body of the loop is executed. After execution of the body the test condition is once again evaluated and if it is true, the body is executed once again.  This process of repeated execution of the body continues until the test condition becomes false and the control is transferred out of the loop. On exit the program continues with the statement immediately following the body of the loop.  The important thing to notice that if the test condition is false then the controlled statements are not executed not even once unlike the do while loop.
  • 29. The Do While Statement  On some occasions it might be necessary to execute the body of the loop before the test is performed. Such situations can be handled by using do while loop. It has the structure: do { body of the loop; } while(test condition)
  • 30. The Do While Statement  On reaching the do statement,
  • 31. Comparison of Loops No. Topics For loop While loop Do...while loop 01 Initialization of condition variable Before or within the parenthesis of the loop. Before the loop. Before the loop or in the body of the loop. 02 Test condition Before the body of the loop. Before the body of the loop. After the body of the loop. 03 Updating the condition variable After the first execution. After the first execution. After the first execution. 04 Type Entry controlled loop. Entry controlled loop. Exit controlled loop. 05 Loop variable Counter. Counter. Sentinel & counter
  • 33. References  The C Programming Language (9780131103627): Brian W. Kernighan, Dennis M. Ritchie  C Programming: A Modern Approach, 2nd Edition By K. N. King  Absolute Beginner’s Guide To C, 2nd Edition By Greg Perry
  • 34. 34 Md. Shakhawat Hossain Student of Department of Computer Science & Engineering University of Rajshahi E-mail: mshimul86@gmail.com