SlideShare a Scribd company logo
1 of 48
Repetition (Loops)
• Want to do some
repetitive sequence of
actions:
• print vertical line of *s
*
*
*
*
*
• Corresponding
program:
printf(“*n”);
printf(“*n”);
printf(“*n”);
printf(“*n”);
printf(“*n”);
Outline
II. Program Basics
H. Statements
6. Loops
Pretest: While
Posttest: Do-While
Pretest: For
Parts: termination condition, initialization, body
Pretest vs Posttest
Counter-controlled vs Event-controlled
Infinite Loops
Nested Loops
Repetitions with Loops
Done 5
times?
Yes
printf
No
Types of Loops
• Pretest - a logical condition is checked
before each repetition to determine if the
loop should terminate
– while loop
– for loop
• Posttest - a logical condition is checked
after each repetition for termination
– do-while loop
PreTest vs. PostTest Loops
Pretest Loop
Condition
Action or
Actions
true
false
Posttest Loop
Condition
Action or
Actions
true
false
Terminating Loops
• Counter-controlled loops - a loop controlled
by a counter variable, generally where the
number of times the loop will execute is
known ahead of time
• Event-controlled loops - loops where
termination depends on an event rather than
executing a fixed number of times
Counter-Controlled Loops
• Generally with for loops
• Can generally infer number of repetitions
from code
• Examples:
– read 5 numbers
– print 7 items
– sort n items
Event-Controlled Loops
• Generally with while, do-while loops
• Can’t infer number of repetitions from
program
• Examples:
– read until input ends
– read until a number encountered
– search through data until item found
Parts of Loop
• Initialization - commands to set up loop (set
counter to initial value, etc.)
• Terminating condition - logical condition
that is checked to terminate loop
• Body of loop - commands repeated
– action(s) - statements to repeat
– update(s) - statements to update values
associated with loop (counters, etc.)
Parts of Loop Example
Init: set counter to 0
Termination: counter < 5
Body:
Action: print *
Update: add 1 to
counter
counter = 0;
(counter < 5)
printf("*n");
counter++;
true
false
Importance of Update
What if command
counter++;
left out?
Counter never becomes
>= 5.
Termination Condition
never met.
counter = 0;
(counter < 5)
printf("*n");
true
false
Infinite Loops
• Loop starts but termination condition never
met:
– you forget to increase counter
– user never enters terminating data item
– etc.
• Results
– program may stop (doing nothing repeatedly)
– computer may repeatedly print some data out
Termination Conditions in C
• Loops in C always continue when the
termination condition is true and end when
the condition is false
• Conditions can be rephrased if needed
(positive termination conditions can be
negated)
• Condition only checked at fixed points
(does not have to hold true during body)
Pretest Loop: While
Syntax:
while (condition)
statement;
Corresponds to:
if (!condition) DONE
statement
if (!condition) DONE
statement
...
Condition
Statement
true
false
Example of While
int counter = 0;
while (counter < 5) {
printf(“*n”);
counter++;
}
single statement is
compound
counter < 5
printf("*n");
counter++;
true
false
counter = 0;
Executing More Than One Stmt
• In C, loops repeat one statement
• Generally we always use a compound
statement as that statement:
while (condition) {
/* body */
}
• Useful even when body has one or no
statements
Empty Statements and Loops
• What’s wrong with this?
counter = 0;
while (counter < 5);
{
printf(“*n”);
counter++;
}
• Note the ; after the condition in the while,
its an empty statement (which is the body of
the while), so the while is an infinite loop
Event-Controlled While
• While loops are often used to test for the
occurrence of events that terminate loops
• Example:
– read in a set of numbers until a particular value
is encountered
– along the way count the set of numbers and the
total of the numbers
– print out the average of the numbers
– does not terminate after a fixed point
Calculate Average Loop
number != 999
total += number;
counter++;
GetNextNumber
true
false
total = 0;
counter = 0;
GetFirstNumber
print average
Calculate Average Code
total = 0;
count = 0;
printf(“Please enter first number: “);
scanf(“%d”,&number);
while (number != -999) {
total += number;
count++;
printf(“Please enter next number: “);
scanf(“%d”,&number);
}
printf(“Average is %.3fn”,(float) total
/ count);
Using a Sentinel
• The value -999 is sometimes referred to as a
sentinel value
• The value serves as the “guardian” for the
termination of the loop
• Often a good idea to make the sentinel a
constant:
#define STOPNUMBER -999
while (number != STOPNUMBER) ...
Compound Conditions
• Often the termination condition is compound:
ans = ‘N’;
while (!((ans == ‘Y’) || (ans == ‘y’))) {
printf(“Enter id# and salary: “);
scanf(“%d %f”,&id,&salary);
printf(“You entered id#%1d and salary
$%.2f, Is this correct? (Y/N)
“,id,salary);
scanf(“ %c”,&ans);
}
Making Sure Loop is Entered
• Note in previous loop, we had to set
variable ans to an initial value, ‘N’
• This is because a while loop tests its
condition before entering the loop, and if
the condition is already false, the loop never
executes
• Sometimes it is useful to have a loop that
always executes at least once
Posttest Loop: Do-While
Syntax:
do {
statement(s)
} while (condition);
Corresponds to:
statement
if (!condition) DONE
statement
if (!condition) DONE
...
condition
statement(s)
true
false
Using the Do-While
do {
printf(“Enter id# and salary: “);
scanf(“%d %f”,&id,&salary);
printf(“You entered id#%1d and salary
$%.2f, Is this correct? (Y/N) “
,id,salary);
scanf(“ %c”,&ans);
} while (!((ans == ‘Y’) || (ans == ‘y’)));
• Loop always executes at least once
Programs with Menus
A)dd part to catalog
R)emove part from catalog
F)ind part in catalog
Q)uit
Select option: A
<interaction to add a part>
A)dd part to catalog
R)emove part from catalog
F)ind part in catalog
Q)uit
Select option: <next option>
Menu Loop
do {
showOptions();
printf(“Select
option:“);
scanf(“ %c”,&optn);
execOption(optn);
while (!(
(optn == ‘Q’) ||
(optn == ‘q’)));
NOT quit
selected
true
false
ShowOptions
ReadOption
ExecuteOption
Menu Options
void showOptions() {
printf(“A)dd part to catalogn”);
printf(“R)emove part from
catalogn”);
printf(“F)ind part in catalogn”);
printf(“Q)uitn”);
}
Executing Options
void execOption( char option ) {
switch (option) {
case ‘A’: case ‘a’: addPart(); break;
case ‘R’: case ‘r’: delPart(); break;
case ‘F’: case ‘f’: fndPart(); break;
case ‘Q’: case ‘q’: break;
default: printf(“Unknown option
%cn”,option); break;
}
}
While vs Do-While
• Differences
– where condition tested:
• while (first) - may execute 0 times
• do-while (last) - must execute at least one time
• Similarities
– one statement executed
– initialization before loop
– update during loop
Pretest Loop: For
• Initialization included in loop header
• Update included in loop header
• Header also includes update
• Syntax:
for ( init ; condition ; update )
statement;
• Generally for loops expected to execute
fixed number of times (counter-controlled)
For Loop
• Syntax:
for ( init ;
condition ;
update )
statement;
• Init: assignments to
counter variables
• Update: changes to
counter variables
Condition
Statement
true
false
Init
Update
For Example
• Printing vertical line
of stars:
for (counter = 0;
counter < 5;
counter++)
printf(“*n”);
counter < 5
printf("*n");
true
false
counter = 0;
counter++;
For Example - Sum of 1 to N
printf(“Number to sum to: “);
scanf(“%d”,&N);
total = 0;
for (I = 1; I <= N; I++)
total += I;
/* total is now 1 + 2 + … + N */
For Example - Max of N Scores
printf(“Number of students: “);
scanf(“%d”,&NumStudents);
for (I = 0; I < NumStudents; I++) {
printf(“Enter student score %d: “);
scanf(“%d”,&score);
if (score > max)
max = score;
}
/* max is highest score entered */
The Comma Form
• Possible to evaluate more than one
expression (assignment) in initialization or
update by separating each by commas
• Syntax: expression , expression , …
printf(“Number to sum to: “);
scanf(“%d”,&N);
for (total = 0, I = 1;
I <= N;
total += I, I++);
/* total is now 1 + 2 + … + N */
Directions of Counting
for (I = 10; I >= 1; I--)
printf(“%d…n”,I);
printf(“0 BLASTOFF!n”);
printf(“Enter start, end, inc values: “);
scanf(“%d%d%d”,&lstart,&lend,&linc);
for (I = lstart;
((linc < 0) && (I < lend)) ||
((linc > 0) && (I > lend));
I += linc)
printf(“%dn”,I);
Nesting Loops
• It is often useful to have a loop within a
loop (called nested loops)
• For example:
printf(“Max N! to print: “);
scanf(“%d”,&N); /* 1 */
for (I = 1; I <= N; I++) { /* 2 */
fact = 1; /* 3 */
for (J = 2; J <= I; J++) /* 4 */
fact *= J; /* 5 */
printf(“%d! = %dn”,I,fact); /* 6 */
}
Tracing Nested Loops
Stmt N I J fact output
1 4
2 1
3 1
4 2
6 1! = 1
2 2
3 1
4 2
5 2
4 3
6 2! = 2
2 3
3 1
4 2
5 2
Stmt N I J fact output
4 3
5 6
4 4
6 3! = 6
2 4
3 1
4 2
5 2
4 3
5 6
4 4
5 24
4 5
6 4! = 24
2 5
More Efficient Implementation
printf(“Max N! to print: “);
scanf(“%d”,&N);
fact = 1;
for (I = 1; I <= N; I++) {
fact *= I;
printf(“%d! = %dn”,I,fact);
}
• But why does this work?
Another Nesting Example
• How to print:
******
*****
****
***
**
*
for (I = 6; I >= 1; I--) {
for (J = 1; J <= I; J++)
printf(“*”);
printf(“n”);
}
• Could have 6 be a variable
More Complex Nesting
• How to print:
***********
*********
*******
*****
***
*
for (I = 0; I <= 5; I++) {
for (J = 0; J < I; J++)
printf(“ “);
for (J = 0;
J < (11 - 2 * I);
J++)
printf(“*”);
printf(“n”);
}
• Note 2 (sequential) inner loops
Another Nesting Example
Size: 5
*****
****
***
**
*
Size: 3
***
**
*
Size: 0
do {
printf(“Size: “);
scanf(“%d”,&Size);
if (Size > 0) {
for (I = Size; I >= 1; I--) {
for (J = 1; J <= I; J++)
printf(“*”);
printf(“n”);
}
}
} while (Size > 0);
Nesting and Functions
• With deep nesting its
often a good idea to
have inner loops in
separate functions
do {
printf(“Size: “);
scanf(“%d”,&Size);
drawTri(Size);
} while (Size > 0);
void drawTri (int N)
{
int I;
int J;
if (N > 0) {
for (I = N; I >= 1; I--)
{
for (J = 1; J <= I;
J++)
printf(“*”);
printf(“n”);
}
}
}
break statement
• The break statement can be used to halt a
loop, though it is generally better to use a
flag to signal loop should end
total = 0;
do {
scanf(“%d”,&num);
if (num < 0) break; /* Loop ends */
} while (num != 0);
Flags
• Better to use a flag variable - a variable that
is set to a value when a condition occurs
total = 0;
done = 0; /* done is set to 0 state */
do {
scanf(“%d”,&num);
if (num < 0) done = 1; /* done 1 */
} while ((num != 0) && (!done));
continue statement
• A continue statement says jump to the next
end of the statement list
• Example:
for (I = 0; I < 100; I++) {
if ((I % 2) == 1) continue;
printf(“%d is even”,I);
}
• Again, stylistically, better not to use
Avoiding continue
• Can generally use an if to avoid a continue:
for (I = 0; I < 100; I++) {
if ((I % 2) == 1) continue;
printf(“%d is even”,I);
}
becomes
for (I = 0; I < 100; I++) {
if (!((I % 2) == 1))
printf(“%d is even”,I);
}

More Related Content

Similar to Chapter06.PPT

Loop control structure
Loop control structureLoop control structure
Loop control structureKaran Pandey
 
Verilog Lecture3 hust 2014
Verilog Lecture3 hust 2014Verilog Lecture3 hust 2014
Verilog Lecture3 hust 2014Béo Tú
 
Fundamental of Information Technology - UNIT 8
Fundamental of Information Technology - UNIT 8Fundamental of Information Technology - UNIT 8
Fundamental of Information Technology - UNIT 8Shipra Swati
 
Condition Stmt n Looping stmt.pptx
Condition Stmt n Looping stmt.pptxCondition Stmt n Looping stmt.pptx
Condition Stmt n Looping stmt.pptxLikhil181
 
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 CSowmya Jyothi
 
Loop and while Loop
Loop and while LoopLoop and while Loop
Loop and while LoopJayBhavsar68
 
Loops in C Programming | for Loop | do-while Loop | while Loop | Nested Loop
Loops in C Programming | for Loop | do-while Loop | while Loop | Nested LoopLoops in C Programming | for Loop | do-while Loop | while Loop | Nested Loop
Loops in C Programming | for Loop | do-while Loop | while Loop | Nested LoopPriyom Majumder
 
Slide07 repetitions
Slide07 repetitionsSlide07 repetitions
Slide07 repetitionsaltwirqi
 
Control Structures in C
Control Structures in CControl Structures in C
Control Structures in Csana shaikh
 
computer programming Control Statements.pptx
computer programming Control Statements.pptxcomputer programming Control Statements.pptx
computer programming Control Statements.pptxeaglesniper008
 
Control Statement.ppt
Control Statement.pptControl Statement.ppt
Control Statement.pptsanjay
 
Looping statements in Java
Looping statements in JavaLooping statements in Java
Looping statements in JavaJin Castor
 

Similar to Chapter06.PPT (20)

Looping
LoopingLooping
Looping
 
Loop control structure
Loop control structureLoop control structure
Loop control structure
 
Programming loop
Programming loopProgramming loop
Programming loop
 
SPL 8 | Loop Statements in C
SPL 8 | Loop Statements in CSPL 8 | Loop Statements in C
SPL 8 | Loop Statements in C
 
Verilog Lecture3 hust 2014
Verilog Lecture3 hust 2014Verilog Lecture3 hust 2014
Verilog Lecture3 hust 2014
 
Fundamental of Information Technology - UNIT 8
Fundamental of Information Technology - UNIT 8Fundamental of Information Technology - UNIT 8
Fundamental of Information Technology - UNIT 8
 
Condition Stmt n Looping stmt.pptx
Condition Stmt n Looping stmt.pptxCondition Stmt n Looping stmt.pptx
Condition Stmt n Looping stmt.pptx
 
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
 
Loop and while Loop
Loop and while LoopLoop and while Loop
Loop and while Loop
 
Loops in c
Loops in cLoops in c
Loops in c
 
Lesson 5
Lesson 5Lesson 5
Lesson 5
 
Loops in C Programming | for Loop | do-while Loop | while Loop | Nested Loop
Loops in C Programming | for Loop | do-while Loop | while Loop | Nested LoopLoops in C Programming | for Loop | do-while Loop | while Loop | Nested Loop
Loops in C Programming | for Loop | do-while Loop | while Loop | Nested Loop
 
[ITP - Lecture 11] Loops in C/C++
[ITP - Lecture 11] Loops in C/C++[ITP - Lecture 11] Loops in C/C++
[ITP - Lecture 11] Loops in C/C++
 
Slide07 repetitions
Slide07 repetitionsSlide07 repetitions
Slide07 repetitions
 
Control Structures in C
Control Structures in CControl Structures in C
Control Structures in C
 
computer programming Control Statements.pptx
computer programming Control Statements.pptxcomputer programming Control Statements.pptx
computer programming Control Statements.pptx
 
Control Statement.ppt
Control Statement.pptControl Statement.ppt
Control Statement.ppt
 
Looping statements
Looping statementsLooping statements
Looping statements
 
Looping statements in Java
Looping statements in JavaLooping statements in Java
Looping statements in Java
 
M C6java6
M C6java6M C6java6
M C6java6
 

Recently uploaded

CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfakmcokerachita
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...M56BOOKSTORE PRODUCT/SERVICE
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfSumit Tiwari
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfUmakantAnnand
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docxPoojaSen20
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application ) Sakshi Ghasle
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 

Recently uploaded (20)

Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdf
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.Compdf
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docx
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application )
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 

Chapter06.PPT

  • 1. Repetition (Loops) • Want to do some repetitive sequence of actions: • print vertical line of *s * * * * * • Corresponding program: printf(“*n”); printf(“*n”); printf(“*n”); printf(“*n”); printf(“*n”);
  • 2. Outline II. Program Basics H. Statements 6. Loops Pretest: While Posttest: Do-While Pretest: For Parts: termination condition, initialization, body Pretest vs Posttest Counter-controlled vs Event-controlled Infinite Loops Nested Loops
  • 3. Repetitions with Loops Done 5 times? Yes printf No
  • 4. Types of Loops • Pretest - a logical condition is checked before each repetition to determine if the loop should terminate – while loop – for loop • Posttest - a logical condition is checked after each repetition for termination – do-while loop
  • 5. PreTest vs. PostTest Loops Pretest Loop Condition Action or Actions true false Posttest Loop Condition Action or Actions true false
  • 6. Terminating Loops • Counter-controlled loops - a loop controlled by a counter variable, generally where the number of times the loop will execute is known ahead of time • Event-controlled loops - loops where termination depends on an event rather than executing a fixed number of times
  • 7. Counter-Controlled Loops • Generally with for loops • Can generally infer number of repetitions from code • Examples: – read 5 numbers – print 7 items – sort n items
  • 8. Event-Controlled Loops • Generally with while, do-while loops • Can’t infer number of repetitions from program • Examples: – read until input ends – read until a number encountered – search through data until item found
  • 9. Parts of Loop • Initialization - commands to set up loop (set counter to initial value, etc.) • Terminating condition - logical condition that is checked to terminate loop • Body of loop - commands repeated – action(s) - statements to repeat – update(s) - statements to update values associated with loop (counters, etc.)
  • 10. Parts of Loop Example Init: set counter to 0 Termination: counter < 5 Body: Action: print * Update: add 1 to counter counter = 0; (counter < 5) printf("*n"); counter++; true false
  • 11. Importance of Update What if command counter++; left out? Counter never becomes >= 5. Termination Condition never met. counter = 0; (counter < 5) printf("*n"); true false
  • 12. Infinite Loops • Loop starts but termination condition never met: – you forget to increase counter – user never enters terminating data item – etc. • Results – program may stop (doing nothing repeatedly) – computer may repeatedly print some data out
  • 13. Termination Conditions in C • Loops in C always continue when the termination condition is true and end when the condition is false • Conditions can be rephrased if needed (positive termination conditions can be negated) • Condition only checked at fixed points (does not have to hold true during body)
  • 14. Pretest Loop: While Syntax: while (condition) statement; Corresponds to: if (!condition) DONE statement if (!condition) DONE statement ... Condition Statement true false
  • 15. Example of While int counter = 0; while (counter < 5) { printf(“*n”); counter++; } single statement is compound counter < 5 printf("*n"); counter++; true false counter = 0;
  • 16. Executing More Than One Stmt • In C, loops repeat one statement • Generally we always use a compound statement as that statement: while (condition) { /* body */ } • Useful even when body has one or no statements
  • 17. Empty Statements and Loops • What’s wrong with this? counter = 0; while (counter < 5); { printf(“*n”); counter++; } • Note the ; after the condition in the while, its an empty statement (which is the body of the while), so the while is an infinite loop
  • 18. Event-Controlled While • While loops are often used to test for the occurrence of events that terminate loops • Example: – read in a set of numbers until a particular value is encountered – along the way count the set of numbers and the total of the numbers – print out the average of the numbers – does not terminate after a fixed point
  • 19. Calculate Average Loop number != 999 total += number; counter++; GetNextNumber true false total = 0; counter = 0; GetFirstNumber print average
  • 20. Calculate Average Code total = 0; count = 0; printf(“Please enter first number: “); scanf(“%d”,&number); while (number != -999) { total += number; count++; printf(“Please enter next number: “); scanf(“%d”,&number); } printf(“Average is %.3fn”,(float) total / count);
  • 21. Using a Sentinel • The value -999 is sometimes referred to as a sentinel value • The value serves as the “guardian” for the termination of the loop • Often a good idea to make the sentinel a constant: #define STOPNUMBER -999 while (number != STOPNUMBER) ...
  • 22. Compound Conditions • Often the termination condition is compound: ans = ‘N’; while (!((ans == ‘Y’) || (ans == ‘y’))) { printf(“Enter id# and salary: “); scanf(“%d %f”,&id,&salary); printf(“You entered id#%1d and salary $%.2f, Is this correct? (Y/N) “,id,salary); scanf(“ %c”,&ans); }
  • 23. Making Sure Loop is Entered • Note in previous loop, we had to set variable ans to an initial value, ‘N’ • This is because a while loop tests its condition before entering the loop, and if the condition is already false, the loop never executes • Sometimes it is useful to have a loop that always executes at least once
  • 24. Posttest Loop: Do-While Syntax: do { statement(s) } while (condition); Corresponds to: statement if (!condition) DONE statement if (!condition) DONE ... condition statement(s) true false
  • 25. Using the Do-While do { printf(“Enter id# and salary: “); scanf(“%d %f”,&id,&salary); printf(“You entered id#%1d and salary $%.2f, Is this correct? (Y/N) “ ,id,salary); scanf(“ %c”,&ans); } while (!((ans == ‘Y’) || (ans == ‘y’))); • Loop always executes at least once
  • 26. Programs with Menus A)dd part to catalog R)emove part from catalog F)ind part in catalog Q)uit Select option: A <interaction to add a part> A)dd part to catalog R)emove part from catalog F)ind part in catalog Q)uit Select option: <next option>
  • 27. Menu Loop do { showOptions(); printf(“Select option:“); scanf(“ %c”,&optn); execOption(optn); while (!( (optn == ‘Q’) || (optn == ‘q’))); NOT quit selected true false ShowOptions ReadOption ExecuteOption
  • 28. Menu Options void showOptions() { printf(“A)dd part to catalogn”); printf(“R)emove part from catalogn”); printf(“F)ind part in catalogn”); printf(“Q)uitn”); }
  • 29. Executing Options void execOption( char option ) { switch (option) { case ‘A’: case ‘a’: addPart(); break; case ‘R’: case ‘r’: delPart(); break; case ‘F’: case ‘f’: fndPart(); break; case ‘Q’: case ‘q’: break; default: printf(“Unknown option %cn”,option); break; } }
  • 30. While vs Do-While • Differences – where condition tested: • while (first) - may execute 0 times • do-while (last) - must execute at least one time • Similarities – one statement executed – initialization before loop – update during loop
  • 31. Pretest Loop: For • Initialization included in loop header • Update included in loop header • Header also includes update • Syntax: for ( init ; condition ; update ) statement; • Generally for loops expected to execute fixed number of times (counter-controlled)
  • 32. For Loop • Syntax: for ( init ; condition ; update ) statement; • Init: assignments to counter variables • Update: changes to counter variables Condition Statement true false Init Update
  • 33. For Example • Printing vertical line of stars: for (counter = 0; counter < 5; counter++) printf(“*n”); counter < 5 printf("*n"); true false counter = 0; counter++;
  • 34. For Example - Sum of 1 to N printf(“Number to sum to: “); scanf(“%d”,&N); total = 0; for (I = 1; I <= N; I++) total += I; /* total is now 1 + 2 + … + N */
  • 35. For Example - Max of N Scores printf(“Number of students: “); scanf(“%d”,&NumStudents); for (I = 0; I < NumStudents; I++) { printf(“Enter student score %d: “); scanf(“%d”,&score); if (score > max) max = score; } /* max is highest score entered */
  • 36. The Comma Form • Possible to evaluate more than one expression (assignment) in initialization or update by separating each by commas • Syntax: expression , expression , … printf(“Number to sum to: “); scanf(“%d”,&N); for (total = 0, I = 1; I <= N; total += I, I++); /* total is now 1 + 2 + … + N */
  • 37. Directions of Counting for (I = 10; I >= 1; I--) printf(“%d…n”,I); printf(“0 BLASTOFF!n”); printf(“Enter start, end, inc values: “); scanf(“%d%d%d”,&lstart,&lend,&linc); for (I = lstart; ((linc < 0) && (I < lend)) || ((linc > 0) && (I > lend)); I += linc) printf(“%dn”,I);
  • 38. Nesting Loops • It is often useful to have a loop within a loop (called nested loops) • For example: printf(“Max N! to print: “); scanf(“%d”,&N); /* 1 */ for (I = 1; I <= N; I++) { /* 2 */ fact = 1; /* 3 */ for (J = 2; J <= I; J++) /* 4 */ fact *= J; /* 5 */ printf(“%d! = %dn”,I,fact); /* 6 */ }
  • 39. Tracing Nested Loops Stmt N I J fact output 1 4 2 1 3 1 4 2 6 1! = 1 2 2 3 1 4 2 5 2 4 3 6 2! = 2 2 3 3 1 4 2 5 2 Stmt N I J fact output 4 3 5 6 4 4 6 3! = 6 2 4 3 1 4 2 5 2 4 3 5 6 4 4 5 24 4 5 6 4! = 24 2 5
  • 40. More Efficient Implementation printf(“Max N! to print: “); scanf(“%d”,&N); fact = 1; for (I = 1; I <= N; I++) { fact *= I; printf(“%d! = %dn”,I,fact); } • But why does this work?
  • 41. Another Nesting Example • How to print: ****** ***** **** *** ** * for (I = 6; I >= 1; I--) { for (J = 1; J <= I; J++) printf(“*”); printf(“n”); } • Could have 6 be a variable
  • 42. More Complex Nesting • How to print: *********** ********* ******* ***** *** * for (I = 0; I <= 5; I++) { for (J = 0; J < I; J++) printf(“ “); for (J = 0; J < (11 - 2 * I); J++) printf(“*”); printf(“n”); } • Note 2 (sequential) inner loops
  • 43. Another Nesting Example Size: 5 ***** **** *** ** * Size: 3 *** ** * Size: 0 do { printf(“Size: “); scanf(“%d”,&Size); if (Size > 0) { for (I = Size; I >= 1; I--) { for (J = 1; J <= I; J++) printf(“*”); printf(“n”); } } } while (Size > 0);
  • 44. Nesting and Functions • With deep nesting its often a good idea to have inner loops in separate functions do { printf(“Size: “); scanf(“%d”,&Size); drawTri(Size); } while (Size > 0); void drawTri (int N) { int I; int J; if (N > 0) { for (I = N; I >= 1; I--) { for (J = 1; J <= I; J++) printf(“*”); printf(“n”); } } }
  • 45. break statement • The break statement can be used to halt a loop, though it is generally better to use a flag to signal loop should end total = 0; do { scanf(“%d”,&num); if (num < 0) break; /* Loop ends */ } while (num != 0);
  • 46. Flags • Better to use a flag variable - a variable that is set to a value when a condition occurs total = 0; done = 0; /* done is set to 0 state */ do { scanf(“%d”,&num); if (num < 0) done = 1; /* done 1 */ } while ((num != 0) && (!done));
  • 47. continue statement • A continue statement says jump to the next end of the statement list • Example: for (I = 0; I < 100; I++) { if ((I % 2) == 1) continue; printf(“%d is even”,I); } • Again, stylistically, better not to use
  • 48. Avoiding continue • Can generally use an if to avoid a continue: for (I = 0; I < 100; I++) { if ((I % 2) == 1) continue; printf(“%d is even”,I); } becomes for (I = 0; I < 100; I++) { if (!((I % 2) == 1)) printf(“%d is even”,I); }