八、程序流程
1、循环
循环鼻祖:goto
计算机科学发展的早期,程序糟糕、粗糙而简短。循环由标签、语句和跳转组成。 在C++中,标签是后面跟冒号(:)的名称。标签放在合法C++语句的左边,跳转是通过在关键字goto后面加上标签的名称来实现的。
//此程序用于演示使用关键字goto实现循环 #include
a、作为一条原则,程序员应当避免使用goto语句。
2、使用while循环
只要条件为真,while循环将使程序重复执行一段代码。
//此程序用于演示使用while循环 #include
using namespace std;
cout<<\< cout<<\< goto loop; using namespace std; int counter=0; int counter=0; while(counter<5) { } cout<<\< 如果不小心在循环后面加上分号,如: int counter; while(counter<5); counter++; 在这个例子中,counter永远不会被执行。 while语句语法: while(condition) statement; condition可以是任何C++表达式,statement可以是任何合法的C++语句或语句块。如果condition为真,将执行statement,然后再次测试condition。这一过程将不断重复下去,直到condition为假为止。此时while循环将终止,接着执行statement后面的第一句语句。 continue和break: 有时候需要在执行while循环体中所有语句之前返回到while循环的开头。continue语句用于跳转到循环的开头。 而有时候需要在满足循环退出条件之前跳出循环。break语句立即跳出while循环,继续执行右大括号后的语句。 //此程序用于演示break的用法 #include int n; counter++; cout<<\< } for(n=100;n>=1;n--) if(n%7==0) { } return 0; std::cout<<\以内能被7整除的最大数为:\< //此程序用于演示continue的用法 #include break语句语法: while(condition1) { if(condition2) break; //statement } continue语句语法: while(condition1) { if(condition2) int n; std::cout<<\之间能被13整除的数有:\; for(n=100;n<=200;n++) { if(n!=0) } std::cout<<\; return 0; continue; std::cout< continue; //statement } while(true)循环: while循环测试的条件可以是任何合法的C++表达式。只要条件为真,while循环将继续执行可以将true作为测试条件来创建永不结束的循环。 //此程序用于演示while true循环 #include 3、实现do...while循环 while循环体可能永远都不会执行。while语句在执行循环体之前检查条件,如果条件为假,将跳过整个while循环体。 //跳过while循环体 #include while(counter>0) { int counter; std::cout<<\; std::cin>>counter; int counter=0; while(true) { } std::cout<<\< counter++; if(counter>10) break; } std::cout<<\; counter--; std::cout<<\< How many Hellos?:2 Hello! Hello! Counter is Output:0 输出: How many Hellos?:0 Counter is Output:0 如果希望至少打印Hello一次,可在while循环之前加上下面的if语句: if(counter<1) Counter=1; 但这种做法被程序员称为“拙作(kludge)”,是一种既难看又不雅的解决方案。 4、使用do...while do...while循环在测试条件前执行循环体,从而确保循环体至少被执行一次。 //do...while循环 #include using namespace std; int counter; cout<<\; cin>>counter; do { cout<<\; counter--; return 0; 百度搜索“77cn”或“免费范文网”即可找到本站免费阅读全部范文。收藏本站方便下次阅读,免费范文网,提供经典小说综合文库Visual C++ 2010- 程序流程在线全文阅读。
相关推荐: