SlideShare a Scribd company logo
SC, Chen
Ch6 Loops
Self Study Note of K. N. King(2008) ‘C Programming A Modern Approach, 2nd Edition’
Ch6 Loops
6.1 The while Statement
6.2 The do Statement
6.3 The for Statement
6.4 Exiting from a Loop
6.5 The NULL Statement
• A loop is a statement whose job is to repeatedly execute some other
statement (the loop body).
• Every loop has a controlling expression in C
• An iteration is one time the loop body is executed
6.1 The while Statement
• The while statement is the simplest and most fundamental of the
loops in C
• The parentheses are required
• The braces is allowed, but not required
• The controlling expression is evaluated first
1. If its value is nonzero(true), the loop body is executed and the expression is
tested again
2. Until the controlling expression has the value zero(false)
while ( expression ) statementControlling Expression
Loop Body
Compound
Statement
Ch 5.2
i = 10;
while (i > 0) {
printf(“T minus %d and countingn”, i);
i--;
}
i = 10;
while (i > 0) {
printf(“T minus %d and countingn”, i--);
}
When a loop controlled by the
expression i>0 terminates, i must
be less than or equal to 0.
The body of a while
loop may not be
executed at all
6.1 The while Statement: Infinite Loops
• A while statement won’t terminate if the controlling expression
always has a nonzero value, which called infinite loop
• C programmers sometimes deliberately create an infinite loop by
using a nonzero constant as the controlling expression
Will execute forever
Until its body contains a statement that transfers control out of the loop
(break, goto, return) or calls a function that causes the program to terminate
while (1) …
6.1 The while Statement: Printing a Table of
Squares
6.1 The while Statement: Summing a Series of
Numbers
6.2 The do Statement
• The do statement is essentially a while statement whose controlling
expression is tested after each execution of the loop body
• The loop body is executed first
Then the controlling expression is evaluated
1. If its value is nonzero(true), the loop body is executed again and then the expression is
evaluated once more
2. Until the controlling expression has the value zero(false) after the loop body has been
executed
• It’s a good idea to use braces in all do statements
A do statement without braces can easily be mistaken for a while statement
do statement while ( expression ) ;
i = 10;
do {
printf(“T minus %d and countingn”, i);
i--;
} while (i > 0);
The body of a do loop
is always executed at
least once
When a loop controlled by the
expression i>0 terminates, i must
be less than or equal to 0.
i = 10;
do
printf(“T minus %d and countingn”, i--);
while (i > 0);
6.2 The do Statement: Calculating the Number
of Digits in an Integer
while( n > 0 ){
n /= 10;
digits ++;
}
Won’t execute if n is 0
6.3 The for Statement
• The for statement is ideal for loops that have a counting variable
Except in a few rare cases, a for loop can always be replaced by an equivalent
while loop
for ( expr1 ; expr2 ; expr3 ) statement
expr1;
while ( expr2 ) {
statement
expr3;
}
expr1:
An initialization step, which is
performed only once before the
loop begins to execute
expr2:
Controls loop termination
expr3:
An operation to be performed at
the end of each loop iteration
for (i = 10; i > 0; i --) {
printf(“T minus %d and countingn”, i);
}
i = 10;
while (i > 0) {
printf(“T minus %d and countingn”, i);
i--;
}
When will for cannot be converted to while?
• When the body of a for loop contains a continue statement
n = 0;
sum = 0;
while (n < 10) {
scanf(“%d”, &i);
if (i == 0)
continue;
sum += i;
n++;
}
sum = 0;
for (n= 0; n < 10; n++) {
scanf(“%d”, &i);
if (i == 0)
continue;
sum += i;
}
When i is equal to 0:
1. The while loop doesn’t increment n
2. The for loop does increment n
expr1;
while ( expr2 ) {
statement
expr3;
}
for ( expr1 ; expr2 ; expr3 ) statement
6.3 The for Statement: for Statement Idioms
• The for statement is ideal for loops that have a counting variable
1. Counting Up
Use < or <= as controlling expression
2. Counting Down
Use > or >= as controlling expression
• “Off-by-one”
for (i = 0; i < n; i++) … for (i = 1; i <= n; i++) …
for (i = n - 1; i >= 0; i--) … for (i = n; i > 0; i--) …
6.3 The for Statement: Omitting Expressions in a
for Statement
• C allows to omit any or all of the expressions
 The two semicolons must always be present, even when some of the expressions are omitted
• If the first expression is omitted
 No initialization is performed before the loop is executed
• If the second expression is omitted
 It defaults to a true value, so the for statement doesn't terminate: infinite loop
• If the third expression is omitted
 The loop body is responsible for ensuring that the value of the second expression eventually becomes false
• When the first and third statements are both omitted
 The resulting loop is nothing more than a while statement
i = 10;
for (; i > 0; i --) {
printf(“T minus %d and countingn”, i);
}
for (i = 10; i > 0; ) {
printf(“T minus %d and countingn”, i--);
}
for (; i > 0; ) {
printf(“T minus %d and countingn”, i--);
}
while (i > 0) {
printf(“T minus %d and countingn”, i--);
}
for (; i > 0; i --) …
Infinite Loops
• C programmers have traditionally preferred for(; ;) than while(1)
Efficiency
− Older compiler would often force programs to test the 1 condition each time through the
while loop
− There should be no difference in performance with modern compilers
6.3 The for Statement: for Statements in C99
• In C99, the first expression in a for statement can be replaced by a
declaration
A variable declared by a for statement is only visible inside the loop
− If a declaration of i already exists, this statement creates a new version of i that will be
used solely within the loop
Pros
1. Convenient
2. Make programs easier to understand
A for statement may declare more than one variable
− Provide all variables have the same type
for (int i = 0; i < n; i ++) …
for (int i = 0, j = 0; i < n; i ++) …
6.3 The for Statement: The Comma Operator
• Using a comma expression to write more than one expressions in the for
statement
1. expr1 is evaluated and its value discarded
2. expr2 is evaluated
Its value is the value of the entire expression
• Can chain together a series of comma expressions
Left associative
• Needed when there is a single expression, but we’d like to have two or
more expressions
Certain macro definitions can benefit from the comma operator
The for statement is the only other place where the comma operator is to be found
expr1, expr2
Macro definitions
Ch 14.3
i = 1, j = 2, k = i + j
((i = 1), (j = 2)), (k = (i + j))
6.3 The for Statement: Printing a Table of
Squares (Revisited) (1/2)
6.3 The for Statement: Printing a Table of
Squares (Revisited) (2/2)
Allows the program to compute consecutive
squares without performing any multiplications
6.4 Exiting from a Loop
• Loops have an exit point
1. Before the loop body
 while
 for
2. After the loop body
 do
3. In the middle of the loop body
 break
• continue
Skip part of a loop iteration without jumping out of the loop
• goto
Allow a program to jump from one statement to another
6.4 Exiting from a Loop: The break Statement
• break
Transfer control out of a switch statement
Also can be used to jump out of a while, do,
or for loop
• The break statement is particularly
useful for writing loops in which the exit
point is in the middle of the body rather
than at the beginning or end
• A break statement transfers control out
of the innermost enclosing while, do ,
for, or switch statement
while(…) {
switch (…) {
…
break;
…
}
}
for(;;) {
printf(“Enter a number (enter 0 to stop): ”);
scanf(“%d”, &n);
if (n == 0)
break;
printf(“%d cubed is %dn”, n, n * n * n);
}
6.4 Exiting from a Loop: The continue Statement
• break transfers control just past the end of a loop
Control leaves the loop
Can be used in switch statements and loops
• continue transfers control to a point just before the end of the loop
body
Control remains inside the loop
Limited to loops
n = 0;
sum = 0;
while (n < 10) {
scanf(“%d”, &i);
if (i == 0)
continue;
sum += i;
n++;
/* continue jumps to here */
}
n = 0;
sum = 0;
while (n < 10) {
scanf(“%d”, &i);
if (i != 0) {
sum += i;
n++;
}
}
continue Statement
• Should newer use the continue statement?
continue statements are rare
continue can be helpful when there are a number of validity tests (or they are
complex)
for (; ;) {
read data
if (data fails first test)
continue;
if (data fails second test)
continue;
.
if (data fails last test)
continue;
process data
}
6.4 Exiting from a Loop: The goto Statement (1/2)
• break and continue statements are both restricted
The target of a break is a point just beyond the end of the enclosing loop
The target of a continue is a point just before the end of the loop
• The goto statement can jump to any statement in a function
Can’t be used to bypass the declaration of a variable-length array in C99
The label must be in the same function as the goto statement itself
• A label is just an identifier placed at the beginning of a statement
A statement may have more than one label
Identifier : statement
goto identifier;
Variable-
length arrays
Ch 8.3
6.4 Exiting from a Loop: The goto Statement (2/2)
• The goto statement is rarely needed in everyday C programming
The break, continue, and return statements are essentially restricted goto
statements
The exit function are sufficient to handle most situations that might require a goto
in other languages
• The goto statement is useful for exiting from nested loops
exit function
Ch 9.5
for (d = 2; d < n; d++) {
if (n % d == 0 )
goto done;
}
done:
if (d < n)
printf (“%d is divisible by %dn”, n, d);
else
printf(“%d is primen”);
while(…) {
switch (…) {
…
goto loop_done;
…
}
}
loop_done: …
Spaghetti Code
• Unstructured and difficult to maintain source code, broadly construed
Code that overuses GOTO statements rather than structured programming
constructs, resulting in convoluted and unmaintainable programs
Such code has a complex and tangled control structure
• Describe older programs having fragmented and scattered files
6.4 Exiting from a Loop: Balancing a Checkbook
6.5 The NULL Statement
• A statement can be NULL
Loop body can be NULL, too
• More concise but usually no more efficient
A loop with an empty body is handy for reading character data
for (d = 2; d < n; d++) {
if (n % d == 0 )
break;
}
for (d = 2; d < n && d != 0; d++)
/* empty loop body */ ;
Reading
characters
Ch 7.3
for (d = 2; d < n && d != 0; d++) ;
if (d < n)
printf(“%d is divisible by %dn”, n, d);
Accidentally putting a semicolon after the parentheses in an if,
while, or for statements creates a null statement
• Ending the if, while, or for prematurely
1. In an if statement
• Create an if statement that apparently performs the
same action regardless of the value of its controlling
expression
2. In an while statement
• May create an infinite loop
• The statement that should be the loop body is executed
only once, after the loop has terminated
3. In an for statement
• Cause the statement that should be the loop body to be
executed only once
NULL statement
• The usage of NULL statement is very rare
Put a label at the end of a compound statement
{
…
goto end_of_statement;
…
end_of_statement: ;
}
A label cannot stand alone, must always
be followed by a statement.
Putting a null statement after the label
solves the problem
Make An Empty Loop Body Stand Out
1. Put the null statement on a line by itself
2. Use a dummy continue statement
3. Use an empty compound statement
for (d = 2; d < n && d != 0; d++)
/* empty loop body */ ;
for (d = 2; d < n && d != 0; d++)
continue;
for (d = 2; d < n && d != 0; d++)
{ }

More Related Content

What's hot

C language Unit 2 Slides, UPTU C language
C language Unit 2 Slides, UPTU C languageC language Unit 2 Slides, UPTU C language
C language Unit 2 Slides, UPTU C language
Rakesh Roshan
 
C language
C languageC language
C language
Mohamed Bedair
 
Unit ii chapter 1 operator and expressions in c
Unit ii chapter 1 operator and expressions in cUnit ii chapter 1 operator and expressions in c
Unit ii chapter 1 operator and expressions in c
Sowmya Jyothi
 
C language UPTU Unit3 Slides
C language UPTU Unit3 SlidesC language UPTU Unit3 Slides
C language UPTU Unit3 Slides
Rakesh Roshan
 
Overview of C Mrs Sowmya Jyothi
Overview of C Mrs Sowmya JyothiOverview of C Mrs Sowmya Jyothi
Overview of C Mrs Sowmya Jyothi
Sowmya Jyothi
 
Decision statements in c language
Decision statements in c languageDecision statements in c language
Decision statements in c language
tanmaymodi4
 
Claguage 110226222227-phpapp02
Claguage 110226222227-phpapp02Claguage 110226222227-phpapp02
Claguage 110226222227-phpapp02
CIMAP
 
C programming session3
C programming  session3C programming  session3
C programming session3
Keroles karam khalil
 
04 control structures 1
04 control structures 104 control structures 1
04 control structures 1Jomel Penalba
 
Unit 5. Control Statement
Unit 5. Control StatementUnit 5. Control Statement
Unit 5. Control Statement
Ashim Lamichhane
 
[ITP - Lecture 12] Functions in C/C++
[ITP - Lecture 12] Functions in C/C++[ITP - Lecture 12] Functions in C/C++
[ITP - Lecture 12] Functions in C/C++
Muhammad Hammad Waseem
 
Operators and expressions in c language
Operators and expressions in c languageOperators and expressions in c language
Operators and expressions in c language
tanmaymodi4
 
[ITP - Lecture 07] Comments in C/C++
[ITP - Lecture 07] Comments in C/C++[ITP - Lecture 07] Comments in C/C++
[ITP - Lecture 07] Comments in C/C++
Muhammad Hammad Waseem
 
Control structure C++
Control structure C++Control structure C++
Control structure C++
Anil Kumar
 
Storage classes in c language
Storage classes in c languageStorage classes in c language
Storage classes in c language
tanmaymodi4
 
Control structures in C++ Programming Language
Control structures in C++ Programming LanguageControl structures in C++ Programming Language
Control structures in C++ Programming Language
Ahmad Idrees
 
Basic structure of c programming
Basic structure of c programmingBasic structure of c programming
Basic structure of c programming
TejaswiB4
 
Constants Variables Datatypes by Mrs. Sowmya Jyothi
Constants Variables Datatypes by Mrs. Sowmya JyothiConstants Variables Datatypes by Mrs. Sowmya Jyothi
Constants Variables Datatypes by Mrs. Sowmya Jyothi
SowmyaJyothi3
 
What is c
What is cWhat is c
What is c
Nitesh Saitwal
 

What's hot (20)

C language Unit 2 Slides, UPTU C language
C language Unit 2 Slides, UPTU C languageC language Unit 2 Slides, UPTU C language
C language Unit 2 Slides, UPTU C language
 
C language
C languageC language
C language
 
Unit ii chapter 1 operator and expressions in c
Unit ii chapter 1 operator and expressions in cUnit ii chapter 1 operator and expressions in c
Unit ii chapter 1 operator and expressions in c
 
C language UPTU Unit3 Slides
C language UPTU Unit3 SlidesC language UPTU Unit3 Slides
C language UPTU Unit3 Slides
 
Overview of C Mrs Sowmya Jyothi
Overview of C Mrs Sowmya JyothiOverview of C Mrs Sowmya Jyothi
Overview of C Mrs Sowmya Jyothi
 
Decision statements in c language
Decision statements in c languageDecision statements in c language
Decision statements in c language
 
Claguage 110226222227-phpapp02
Claguage 110226222227-phpapp02Claguage 110226222227-phpapp02
Claguage 110226222227-phpapp02
 
C programming session3
C programming  session3C programming  session3
C programming session3
 
04 control structures 1
04 control structures 104 control structures 1
04 control structures 1
 
Unit 5. Control Statement
Unit 5. Control StatementUnit 5. Control Statement
Unit 5. Control Statement
 
[ITP - Lecture 12] Functions in C/C++
[ITP - Lecture 12] Functions in C/C++[ITP - Lecture 12] Functions in C/C++
[ITP - Lecture 12] Functions in C/C++
 
Operators and expressions in c language
Operators and expressions in c languageOperators and expressions in c language
Operators and expressions in c language
 
[ITP - Lecture 07] Comments in C/C++
[ITP - Lecture 07] Comments in C/C++[ITP - Lecture 07] Comments in C/C++
[ITP - Lecture 07] Comments in C/C++
 
Control structure C++
Control structure C++Control structure C++
Control structure C++
 
Storage classes in c language
Storage classes in c languageStorage classes in c language
Storage classes in c language
 
Control structures in C++ Programming Language
Control structures in C++ Programming LanguageControl structures in C++ Programming Language
Control structures in C++ Programming Language
 
Ch03
Ch03Ch03
Ch03
 
Basic structure of c programming
Basic structure of c programmingBasic structure of c programming
Basic structure of c programming
 
Constants Variables Datatypes by Mrs. Sowmya Jyothi
Constants Variables Datatypes by Mrs. Sowmya JyothiConstants Variables Datatypes by Mrs. Sowmya Jyothi
Constants Variables Datatypes by Mrs. Sowmya Jyothi
 
What is c
What is cWhat is c
What is c
 

Similar to Ch6 Loops

Session 3
Session 3Session 3
Loops in c language
Loops in c languageLoops in c language
Loops in c language
Tanmay Modi
 
Loops in c language
Loops in c languageLoops in c language
Loops in c language
tanmaymodi4
 
INPUT AND OUTPUT STATEMENTS IN PROGRAMMING IN C
INPUT AND OUTPUT STATEMENTS IN PROGRAMMING IN CINPUT AND OUTPUT STATEMENTS IN PROGRAMMING IN C
INPUT AND OUTPUT STATEMENTS IN PROGRAMMING IN C
Chandrakant Divate
 
Loops c++
Loops c++Loops c++
Loops c++
Shivani Singh
 
Loops in c
Loops in cLoops in c
Loops in c
shubhampandav3
 
03 conditions loops
03   conditions loops03   conditions loops
03 conditions loops
Manzoor ALam
 
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
Sowmya Jyothi
 
Looping
LoopingLooping
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
Priyom Majumder
 
Condition Stmt n Looping stmt.pptx
Condition Stmt n Looping stmt.pptxCondition Stmt n Looping stmt.pptx
Condition Stmt n Looping stmt.pptx
Likhil181
 
Iterative control structures, looping, types of loops, loop working
Iterative control structures, looping, types of loops, loop workingIterative control structures, looping, types of loops, loop working
Iterative control structures, looping, types of loops, loop working
Neeru Mittal
 
Mesics lecture 7 iteration and repetitive executions
Mesics lecture 7   iteration and repetitive executionsMesics lecture 7   iteration and repetitive executions
Mesics lecture 7 iteration and repetitive executions
eShikshak
 
12 lec 12 loop
12 lec 12 loop 12 lec 12 loop
12 lec 12 loop
kapil078
 
Loops IN COMPUTER SCIENCE STANDARD 11 BY KR
Loops IN COMPUTER SCIENCE STANDARD 11 BY KRLoops IN COMPUTER SCIENCE STANDARD 11 BY KR
Loops IN COMPUTER SCIENCE STANDARD 11 BY KR
Krishna Raj
 
Loop and while Loop
Loop and while LoopLoop and while Loop
Loop and while Loop
JayBhavsar68
 
COM1407: Program Control Structures – Repetition and Loops
COM1407: Program Control Structures – Repetition and Loops COM1407: Program Control Structures – Repetition and Loops
COM1407: Program Control Structures – Repetition and Loops
Hemantha Kulathilake
 
Iteration
IterationIteration
Iteration
Liam Dunphy
 
Programming in Arduino (Part 2)
Programming in Arduino  (Part 2)Programming in Arduino  (Part 2)
Programming in Arduino (Part 2)
Niket Chandrawanshi
 

Similar to Ch6 Loops (20)

Session 3
Session 3Session 3
Session 3
 
Loops in c language
Loops in c languageLoops in c language
Loops in c language
 
Loops in c language
Loops in c languageLoops in c language
Loops in c language
 
INPUT AND OUTPUT STATEMENTS IN PROGRAMMING IN C
INPUT AND OUTPUT STATEMENTS IN PROGRAMMING IN CINPUT AND OUTPUT STATEMENTS IN PROGRAMMING IN C
INPUT AND OUTPUT STATEMENTS IN PROGRAMMING IN C
 
Loops c++
Loops c++Loops c++
Loops c++
 
Loops in c
Loops in cLoops in c
Loops in c
 
03 conditions loops
03   conditions loops03   conditions loops
03 conditions loops
 
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
 
Looping
LoopingLooping
Looping
 
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
 
Condition Stmt n Looping stmt.pptx
Condition Stmt n Looping stmt.pptxCondition Stmt n Looping stmt.pptx
Condition Stmt n Looping stmt.pptx
 
Iterative control structures, looping, types of loops, loop working
Iterative control structures, looping, types of loops, loop workingIterative control structures, looping, types of loops, loop working
Iterative control structures, looping, types of loops, loop working
 
Mesics lecture 7 iteration and repetitive executions
Mesics lecture 7   iteration and repetitive executionsMesics lecture 7   iteration and repetitive executions
Mesics lecture 7 iteration and repetitive executions
 
12 lec 12 loop
12 lec 12 loop 12 lec 12 loop
12 lec 12 loop
 
Ch3 repetition
Ch3 repetitionCh3 repetition
Ch3 repetition
 
Loops IN COMPUTER SCIENCE STANDARD 11 BY KR
Loops IN COMPUTER SCIENCE STANDARD 11 BY KRLoops IN COMPUTER SCIENCE STANDARD 11 BY KR
Loops IN COMPUTER SCIENCE STANDARD 11 BY KR
 
Loop and while Loop
Loop and while LoopLoop and while Loop
Loop and while Loop
 
COM1407: Program Control Structures – Repetition and Loops
COM1407: Program Control Structures – Repetition and Loops COM1407: Program Control Structures – Repetition and Loops
COM1407: Program Control Structures – Repetition and Loops
 
Iteration
IterationIteration
Iteration
 
Programming in Arduino (Part 2)
Programming in Arduino  (Part 2)Programming in Arduino  (Part 2)
Programming in Arduino (Part 2)
 

Recently uploaded

Planning Of Procurement o different goods and services
Planning Of Procurement o different goods and servicesPlanning Of Procurement o different goods and services
Planning Of Procurement o different goods and services
JoytuBarua2
 
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdfAKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
SamSarthak3
 
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&BDesign and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Sreedhar Chowdam
 
power quality voltage fluctuation UNIT - I.pptx
power quality voltage fluctuation UNIT - I.pptxpower quality voltage fluctuation UNIT - I.pptx
power quality voltage fluctuation UNIT - I.pptx
ViniHema
 
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
bakpo1
 
road safety engineering r s e unit 3.pdf
road safety engineering  r s e unit 3.pdfroad safety engineering  r s e unit 3.pdf
road safety engineering r s e unit 3.pdf
VENKATESHvenky89705
 
addressing modes in computer architecture
addressing modes  in computer architectureaddressing modes  in computer architecture
addressing modes in computer architecture
ShahidSultan24
 
COLLEGE BUS MANAGEMENT SYSTEM PROJECT REPORT.pdf
COLLEGE BUS MANAGEMENT SYSTEM PROJECT REPORT.pdfCOLLEGE BUS MANAGEMENT SYSTEM PROJECT REPORT.pdf
COLLEGE BUS MANAGEMENT SYSTEM PROJECT REPORT.pdf
Kamal Acharya
 
MCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdfMCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdf
Osamah Alsalih
 
Final project report on grocery store management system..pdf
Final project report on grocery store management system..pdfFinal project report on grocery store management system..pdf
Final project report on grocery store management system..pdf
Kamal Acharya
 
block diagram and signal flow graph representation
block diagram and signal flow graph representationblock diagram and signal flow graph representation
block diagram and signal flow graph representation
Divya Somashekar
 
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdfHybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
fxintegritypublishin
 
CME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional ElectiveCME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional Elective
karthi keyan
 
The role of big data in decision making.
The role of big data in decision making.The role of big data in decision making.
The role of big data in decision making.
ankuprajapati0525
 
Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024
Massimo Talia
 
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Dr.Costas Sachpazis
 
TECHNICAL TRAINING MANUAL GENERAL FAMILIARIZATION COURSE
TECHNICAL TRAINING MANUAL   GENERAL FAMILIARIZATION COURSETECHNICAL TRAINING MANUAL   GENERAL FAMILIARIZATION COURSE
TECHNICAL TRAINING MANUAL GENERAL FAMILIARIZATION COURSE
DuvanRamosGarzon1
 
Halogenation process of chemical process industries
Halogenation process of chemical process industriesHalogenation process of chemical process industries
Halogenation process of chemical process industries
MuhammadTufail242431
 
Quality defects in TMT Bars, Possible causes and Potential Solutions.
Quality defects in TMT Bars, Possible causes and Potential Solutions.Quality defects in TMT Bars, Possible causes and Potential Solutions.
Quality defects in TMT Bars, Possible causes and Potential Solutions.
PrashantGoswami42
 
Vaccine management system project report documentation..pdf
Vaccine management system project report documentation..pdfVaccine management system project report documentation..pdf
Vaccine management system project report documentation..pdf
Kamal Acharya
 

Recently uploaded (20)

Planning Of Procurement o different goods and services
Planning Of Procurement o different goods and servicesPlanning Of Procurement o different goods and services
Planning Of Procurement o different goods and services
 
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdfAKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
 
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&BDesign and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
 
power quality voltage fluctuation UNIT - I.pptx
power quality voltage fluctuation UNIT - I.pptxpower quality voltage fluctuation UNIT - I.pptx
power quality voltage fluctuation UNIT - I.pptx
 
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
 
road safety engineering r s e unit 3.pdf
road safety engineering  r s e unit 3.pdfroad safety engineering  r s e unit 3.pdf
road safety engineering r s e unit 3.pdf
 
addressing modes in computer architecture
addressing modes  in computer architectureaddressing modes  in computer architecture
addressing modes in computer architecture
 
COLLEGE BUS MANAGEMENT SYSTEM PROJECT REPORT.pdf
COLLEGE BUS MANAGEMENT SYSTEM PROJECT REPORT.pdfCOLLEGE BUS MANAGEMENT SYSTEM PROJECT REPORT.pdf
COLLEGE BUS MANAGEMENT SYSTEM PROJECT REPORT.pdf
 
MCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdfMCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdf
 
Final project report on grocery store management system..pdf
Final project report on grocery store management system..pdfFinal project report on grocery store management system..pdf
Final project report on grocery store management system..pdf
 
block diagram and signal flow graph representation
block diagram and signal flow graph representationblock diagram and signal flow graph representation
block diagram and signal flow graph representation
 
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdfHybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
 
CME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional ElectiveCME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional Elective
 
The role of big data in decision making.
The role of big data in decision making.The role of big data in decision making.
The role of big data in decision making.
 
Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024
 
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
 
TECHNICAL TRAINING MANUAL GENERAL FAMILIARIZATION COURSE
TECHNICAL TRAINING MANUAL   GENERAL FAMILIARIZATION COURSETECHNICAL TRAINING MANUAL   GENERAL FAMILIARIZATION COURSE
TECHNICAL TRAINING MANUAL GENERAL FAMILIARIZATION COURSE
 
Halogenation process of chemical process industries
Halogenation process of chemical process industriesHalogenation process of chemical process industries
Halogenation process of chemical process industries
 
Quality defects in TMT Bars, Possible causes and Potential Solutions.
Quality defects in TMT Bars, Possible causes and Potential Solutions.Quality defects in TMT Bars, Possible causes and Potential Solutions.
Quality defects in TMT Bars, Possible causes and Potential Solutions.
 
Vaccine management system project report documentation..pdf
Vaccine management system project report documentation..pdfVaccine management system project report documentation..pdf
Vaccine management system project report documentation..pdf
 

Ch6 Loops

  • 1. SC, Chen Ch6 Loops Self Study Note of K. N. King(2008) ‘C Programming A Modern Approach, 2nd Edition’
  • 2. Ch6 Loops 6.1 The while Statement 6.2 The do Statement 6.3 The for Statement 6.4 Exiting from a Loop 6.5 The NULL Statement • A loop is a statement whose job is to repeatedly execute some other statement (the loop body). • Every loop has a controlling expression in C • An iteration is one time the loop body is executed
  • 3. 6.1 The while Statement • The while statement is the simplest and most fundamental of the loops in C • The parentheses are required • The braces is allowed, but not required • The controlling expression is evaluated first 1. If its value is nonzero(true), the loop body is executed and the expression is tested again 2. Until the controlling expression has the value zero(false) while ( expression ) statementControlling Expression Loop Body Compound Statement Ch 5.2 i = 10; while (i > 0) { printf(“T minus %d and countingn”, i); i--; } i = 10; while (i > 0) { printf(“T minus %d and countingn”, i--); } When a loop controlled by the expression i>0 terminates, i must be less than or equal to 0. The body of a while loop may not be executed at all
  • 4. 6.1 The while Statement: Infinite Loops • A while statement won’t terminate if the controlling expression always has a nonzero value, which called infinite loop • C programmers sometimes deliberately create an infinite loop by using a nonzero constant as the controlling expression Will execute forever Until its body contains a statement that transfers control out of the loop (break, goto, return) or calls a function that causes the program to terminate while (1) …
  • 5. 6.1 The while Statement: Printing a Table of Squares
  • 6. 6.1 The while Statement: Summing a Series of Numbers
  • 7. 6.2 The do Statement • The do statement is essentially a while statement whose controlling expression is tested after each execution of the loop body • The loop body is executed first Then the controlling expression is evaluated 1. If its value is nonzero(true), the loop body is executed again and then the expression is evaluated once more 2. Until the controlling expression has the value zero(false) after the loop body has been executed • It’s a good idea to use braces in all do statements A do statement without braces can easily be mistaken for a while statement do statement while ( expression ) ; i = 10; do { printf(“T minus %d and countingn”, i); i--; } while (i > 0); The body of a do loop is always executed at least once When a loop controlled by the expression i>0 terminates, i must be less than or equal to 0. i = 10; do printf(“T minus %d and countingn”, i--); while (i > 0);
  • 8. 6.2 The do Statement: Calculating the Number of Digits in an Integer while( n > 0 ){ n /= 10; digits ++; } Won’t execute if n is 0
  • 9. 6.3 The for Statement • The for statement is ideal for loops that have a counting variable Except in a few rare cases, a for loop can always be replaced by an equivalent while loop for ( expr1 ; expr2 ; expr3 ) statement expr1; while ( expr2 ) { statement expr3; } expr1: An initialization step, which is performed only once before the loop begins to execute expr2: Controls loop termination expr3: An operation to be performed at the end of each loop iteration for (i = 10; i > 0; i --) { printf(“T minus %d and countingn”, i); } i = 10; while (i > 0) { printf(“T minus %d and countingn”, i); i--; }
  • 10. When will for cannot be converted to while? • When the body of a for loop contains a continue statement n = 0; sum = 0; while (n < 10) { scanf(“%d”, &i); if (i == 0) continue; sum += i; n++; } sum = 0; for (n= 0; n < 10; n++) { scanf(“%d”, &i); if (i == 0) continue; sum += i; } When i is equal to 0: 1. The while loop doesn’t increment n 2. The for loop does increment n expr1; while ( expr2 ) { statement expr3; } for ( expr1 ; expr2 ; expr3 ) statement
  • 11. 6.3 The for Statement: for Statement Idioms • The for statement is ideal for loops that have a counting variable 1. Counting Up Use < or <= as controlling expression 2. Counting Down Use > or >= as controlling expression • “Off-by-one” for (i = 0; i < n; i++) … for (i = 1; i <= n; i++) … for (i = n - 1; i >= 0; i--) … for (i = n; i > 0; i--) …
  • 12. 6.3 The for Statement: Omitting Expressions in a for Statement • C allows to omit any or all of the expressions  The two semicolons must always be present, even when some of the expressions are omitted • If the first expression is omitted  No initialization is performed before the loop is executed • If the second expression is omitted  It defaults to a true value, so the for statement doesn't terminate: infinite loop • If the third expression is omitted  The loop body is responsible for ensuring that the value of the second expression eventually becomes false • When the first and third statements are both omitted  The resulting loop is nothing more than a while statement i = 10; for (; i > 0; i --) { printf(“T minus %d and countingn”, i); } for (i = 10; i > 0; ) { printf(“T minus %d and countingn”, i--); } for (; i > 0; ) { printf(“T minus %d and countingn”, i--); } while (i > 0) { printf(“T minus %d and countingn”, i--); } for (; i > 0; i --) …
  • 13. Infinite Loops • C programmers have traditionally preferred for(; ;) than while(1) Efficiency − Older compiler would often force programs to test the 1 condition each time through the while loop − There should be no difference in performance with modern compilers
  • 14. 6.3 The for Statement: for Statements in C99 • In C99, the first expression in a for statement can be replaced by a declaration A variable declared by a for statement is only visible inside the loop − If a declaration of i already exists, this statement creates a new version of i that will be used solely within the loop Pros 1. Convenient 2. Make programs easier to understand A for statement may declare more than one variable − Provide all variables have the same type for (int i = 0; i < n; i ++) … for (int i = 0, j = 0; i < n; i ++) …
  • 15. 6.3 The for Statement: The Comma Operator • Using a comma expression to write more than one expressions in the for statement 1. expr1 is evaluated and its value discarded 2. expr2 is evaluated Its value is the value of the entire expression • Can chain together a series of comma expressions Left associative • Needed when there is a single expression, but we’d like to have two or more expressions Certain macro definitions can benefit from the comma operator The for statement is the only other place where the comma operator is to be found expr1, expr2 Macro definitions Ch 14.3 i = 1, j = 2, k = i + j ((i = 1), (j = 2)), (k = (i + j))
  • 16. 6.3 The for Statement: Printing a Table of Squares (Revisited) (1/2)
  • 17. 6.3 The for Statement: Printing a Table of Squares (Revisited) (2/2) Allows the program to compute consecutive squares without performing any multiplications
  • 18. 6.4 Exiting from a Loop • Loops have an exit point 1. Before the loop body  while  for 2. After the loop body  do 3. In the middle of the loop body  break • continue Skip part of a loop iteration without jumping out of the loop • goto Allow a program to jump from one statement to another
  • 19. 6.4 Exiting from a Loop: The break Statement • break Transfer control out of a switch statement Also can be used to jump out of a while, do, or for loop • The break statement is particularly useful for writing loops in which the exit point is in the middle of the body rather than at the beginning or end • A break statement transfers control out of the innermost enclosing while, do , for, or switch statement while(…) { switch (…) { … break; … } } for(;;) { printf(“Enter a number (enter 0 to stop): ”); scanf(“%d”, &n); if (n == 0) break; printf(“%d cubed is %dn”, n, n * n * n); }
  • 20. 6.4 Exiting from a Loop: The continue Statement • break transfers control just past the end of a loop Control leaves the loop Can be used in switch statements and loops • continue transfers control to a point just before the end of the loop body Control remains inside the loop Limited to loops n = 0; sum = 0; while (n < 10) { scanf(“%d”, &i); if (i == 0) continue; sum += i; n++; /* continue jumps to here */ } n = 0; sum = 0; while (n < 10) { scanf(“%d”, &i); if (i != 0) { sum += i; n++; } }
  • 21. continue Statement • Should newer use the continue statement? continue statements are rare continue can be helpful when there are a number of validity tests (or they are complex) for (; ;) { read data if (data fails first test) continue; if (data fails second test) continue; . if (data fails last test) continue; process data }
  • 22. 6.4 Exiting from a Loop: The goto Statement (1/2) • break and continue statements are both restricted The target of a break is a point just beyond the end of the enclosing loop The target of a continue is a point just before the end of the loop • The goto statement can jump to any statement in a function Can’t be used to bypass the declaration of a variable-length array in C99 The label must be in the same function as the goto statement itself • A label is just an identifier placed at the beginning of a statement A statement may have more than one label Identifier : statement goto identifier; Variable- length arrays Ch 8.3
  • 23. 6.4 Exiting from a Loop: The goto Statement (2/2) • The goto statement is rarely needed in everyday C programming The break, continue, and return statements are essentially restricted goto statements The exit function are sufficient to handle most situations that might require a goto in other languages • The goto statement is useful for exiting from nested loops exit function Ch 9.5 for (d = 2; d < n; d++) { if (n % d == 0 ) goto done; } done: if (d < n) printf (“%d is divisible by %dn”, n, d); else printf(“%d is primen”); while(…) { switch (…) { … goto loop_done; … } } loop_done: …
  • 24. Spaghetti Code • Unstructured and difficult to maintain source code, broadly construed Code that overuses GOTO statements rather than structured programming constructs, resulting in convoluted and unmaintainable programs Such code has a complex and tangled control structure • Describe older programs having fragmented and scattered files
  • 25. 6.4 Exiting from a Loop: Balancing a Checkbook
  • 26. 6.5 The NULL Statement • A statement can be NULL Loop body can be NULL, too • More concise but usually no more efficient A loop with an empty body is handy for reading character data for (d = 2; d < n; d++) { if (n % d == 0 ) break; } for (d = 2; d < n && d != 0; d++) /* empty loop body */ ; Reading characters Ch 7.3 for (d = 2; d < n && d != 0; d++) ; if (d < n) printf(“%d is divisible by %dn”, n, d); Accidentally putting a semicolon after the parentheses in an if, while, or for statements creates a null statement • Ending the if, while, or for prematurely 1. In an if statement • Create an if statement that apparently performs the same action regardless of the value of its controlling expression 2. In an while statement • May create an infinite loop • The statement that should be the loop body is executed only once, after the loop has terminated 3. In an for statement • Cause the statement that should be the loop body to be executed only once
  • 27. NULL statement • The usage of NULL statement is very rare Put a label at the end of a compound statement { … goto end_of_statement; … end_of_statement: ; } A label cannot stand alone, must always be followed by a statement. Putting a null statement after the label solves the problem
  • 28. Make An Empty Loop Body Stand Out 1. Put the null statement on a line by itself 2. Use a dummy continue statement 3. Use an empty compound statement for (d = 2; d < n && d != 0; d++) /* empty loop body */ ; for (d = 2; d < n && d != 0; d++) continue; for (d = 2; d < n && d != 0; d++) { }

Editor's Notes

  1. 舉例子
  2. 舉例子
  3. 舉例子
  4. 舉例子
  5. 舉例子
  6. 舉例子
  7. 舉例子
  8. 舉例子
  9. 舉例子
  10. 舉例子
  11. 舉例子
  12. 舉例子
  13. 舉例子
  14. 舉例子
  15. 舉例子
  16. 舉例子
  17. 舉例子
  18. 舉例子
  19. 舉例子
  20. 舉例子
  21. 舉例子