c教学第二章.ppt
文本预览下载声明
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * 4 * 5 * * * * * * * * * * * * * * * * * * * * * * * * * * * do-while 语句 一般形式 do 语句 while (表达式) 可以是复合语句,其中必须含有改变条件表达式值的语句。 执行顺序 先执行循环体语句,后判断条件。表达式为 true 时,继续执行循环体 与while 语句的比较: While 语句执行顺序 先判断表达式的值,为true 时,再执行语句 算法的基本控制结构 对比下列程序: 程序1: #includeiostream using namespace std; int main() { int i,sum(0); cini; while(i=10) { sum+=i; i++; } coutsum=sum endl; } 算法的基本控制结构 程序2: #includeiostream using namespace std; int main() { int i, sum(0); cini; do{ sum+=i; i++; }while(i=10); coutsum=sum endl; } * * for 语句 语法形式 for (表达式1;表达式2;表达式3) 语句 循环前先求解 为true时执行循环体 每次执行完循环体后求解 算法的基本控制结构 * 例2-8 输入一个整数,求出它的所有因子。 算法的基本控制结构 #include iostream using namespace std; int main() { int n, k; cout Enter a positive integer: ; cin n; cout Number n Factors ; for (k=1; k = n; k++) if (n % k == 0) cout k ; cout endl; } * 运行结果1: Enter a positive integer: 36 Number 36 Factors 1 2 3 4 6 9 12 18 36 运行结果2: Enter a positive integer: 7 Number 7 Factors 1 7 * * 例2-9 编写程序输出以下图案 * *** ***** ******* ***** *** * 算法的基本控制结构 #includeiostream using namespace std; int main() { int i,j,n=4; for(i=1;i=n;i++) //输出前4行图案 { for(j=1;j=30;j++) cout ; //在图案左侧空30列 for(j=1; j=8-2*i ;j++) cout ; for(j=1; j=2*i-1 ;j++) cout*; coutendl; } * for(i=1;i=n-1;i++) //输出后3行图案 { for(j=1;j=30;j++) cout ; //在图案左侧空30列 for(j=1; j=7-2*i ;j++) cout*; coutendl; } } * * 循环结构与选择结构相互嵌套 #includeiostream using namespace std; int main() { int n; for(n=100; n=200; n++) { if (n%3!=0) coutn; } } 算法的基本控制结构 * 例2-10 读入一系列整数,统计出正整数个数i和负整数个数j,读入0则结束。 分析: 需要读入一系列整数,但是整数个数不定,要在每次读
显示全部