文档介绍:第6章循环控制结构
本章学习内容
计数控制的循环
条件控制的循环
for语句,while语句,do-while语句
continue语句,break语句
嵌套循环
程序调试与排错
Example:
如何确定程序的输入和输出呢?
Draw a flowchart for the following problem:
读入5个整数,计算并显示它们的和.
Input : 5 个整数n1, n2, n3, n4, n5
Output: n1, n2, n3, n4, n5的和
Input example: 2 3 4 5 6
Output example: 20
问题的提出
Input n1
Input n2
Input n3
input n4
input n5
output sum
sum ← n1+n2+n3+n4+n5
2
n1
Assume input example:
2 3 4 5 6
3
n2
4
n3
5
n4
6
n5
20
sum
end
使用了6个不同的变量
start
问题的提出
读入1000个整数,计算并显示它们的和.?
如何对循环进行控制呢?
counter ← 1, sum ← 0
counter<6
sum ← sum + n
false
true
counter++
output sum
input n
1
counter
sum
0
1 < 6 true
2
n
0 + 2
2
2
2 < 6 true
3
2 + 3
5
3
3 < 6 true
4
5 + 4
9
4
4 < 6 true
5
9 + 5
14
5
5 < 6 true
6
14 + 6
20
6
6 < 6 false
counter-controlled
计数器每次增1
使用了3个变量
Assume input example:
2 3 4 5 6
start
end
counter ← initialValue
test counter
Step n
Step x
false
true
Update counter
循环体
(Body of Loop)
当型循环——Condition is tested first
计数控制——Loop is controlled by a counter
Syntax
for (initial value ; condition; update counter)
statement;
Or
for (initial value ; condition; update counter)
{
statement;
statement;
}
for循环语句
循环起始条件
循环结束条件
循环变量增值
pound statement
被当作一条语句看待
循环变量控制循环次数,不要在循环体内改变这个变量的值
i ← 0, sum ← 0
i < 5
sum←sum+ n
false
true
i++
output sum
input n
int i, sum, n;
sum = 0;
for (i = 0; i < 5; i++)
{
scanf(“%d”, &n);
sum = sum + n;
}
printf(“%d”, sum);
for循环语句
start
end
A
条件P
直
到
型
循
环
假
真
A
当
型
循
环
真
假
假
条件P