Chapter 05
Chapter 05
Repetition
and Loop
Statements
Instructor:
Kun-Mao Chao
( 台大資工 趙坤
茂)
Repetition in Programs
• In most software, the statements in the program
may need to repeat for many times.
– e.g., calculate the value of n!.
– If n = 10000, it’s not elegant to write the code as
1*2*3*…*10000.
• Loop is a control structure that repeats a group
of steps in a program.
– Loop body stands for the repeated statements.
• There are three C loop control statements:
– while, for, and do-while.
Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 5-2
Flow Diagram of Loop Choice Process
Statement
Statement
Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 5-8
Compound Assignment Operators
(1/2)
• The loop body usually consists of statements of
the form: variable = variable op expression.
– e.g., count_emp = count_emp + 1;
• C provides compound assignment operators
which enable a more concise notation for this
kind of statements.
– “variable op = expression” is the same to
“variable = variable op expression.”
Update Expression
for(j=1;j<=50;j++){
… Inner loop
}
}
• The above loop will run for 100*50 iterations.
Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 5-18
The do-while Statement in C