文档介绍:本章学****内容
计数控制的循环
条件控制的循环
for语句,while语句,do-while语句
continue语句,break语句
嵌套循环
结构化程序设计的基本思想
程序调试与排错
第1页/共62页
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
问题的提出
第2页/共62页
Input n1
Input n2
Input n3
input n4
input n5
output sum
sum ← n1+n2+n3+n4+n5
Assume input example:
2 3 4 5 6
end
使用了6个不同的变量
start
问题的提出
第3页/共62页
如何对循环进行控制呢?
第4页/共62页
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
end
第5页/共62页
counter ← initial value
test counter
step n
step x
false
true
update counter
循环体
(Body of Loop)
第6页/共62页
当型循环——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循环语句
循环起始条件
循环结束条件
循环变量增值
第7页/共62页
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循环语句
第8页/共62页
A
条 件P
直
到
型
循
环
假
真
条件控制的循环
A
当
型
循
环
真
假
假
条 件P
第9页/共62页
当型循环——Condition is tested first
条件或计数控制
——Loop is controlled by condition or a counter
语法
while (condition)
statement;
Or
while (condition)
{
statement;
statement;
}
No semicolon!!
while循环语句
第10页/共62页