程序控制结构2022-11-02

while循环

-循环条件
-循环体

while( ) {
....
}

无限循环
加入“哨兵”的功能可以结束循环

#include <iostream>
using namespace std;
int main()
{
int n,sum = 0;
cout << "The program gets some integers, and output their sum.\n";
cout << "To stop, please input 0.\n";
while(ture){
cout << "Please input an integer:";
cin >> n;
if(n==0)
  break;
sum+=n;
}
}

for循环

-操作符号++、--等,前缀递增递减和后缀的递增递减等操作运算;

注意

操作数必须为变量,而不能为其他表达式;
不在复杂表达式中使用

for(初始化表达式;条件表达式;步进表达式)循环体

求1~n的平方和

#include <iostream>
using namespace std;
int main()
{
int n,i,sum;
cout << "The program gets a positive integer,\n";
cout << "and prints the squared sum from 1 to the number.\n";
cout << "The number:";
cin >> n;
sum = 0;
for(i = 1 ; i<=n;++i)
  sum +=i*i;
cout << "The sum is" << sum <<"."<<endl;
return 0;
}

循环嵌套

#include <iostream>
#include <iomani>
using namespace std;
int main()
{
int i,j;
cout << " Nine-by-nine Multiplication Table\n";
cout << "------------------------------------------\n";
cout <<"  ";
for(i = 1 ; i<= 9; ++i)
  cout << setw(4) << i;
cou << "\n";
cout << "------------------------------------------\n";
for(i = 1; i<=9 ; ++i)
{
cout << setw(2) << i;
for(j = 1 ; j<= 9; ++j)
{
if(j < i)
cout <<"  ";
else
cout << setw(4) << i*j;
}
cout << endl;
}
cout <<"--------------------------------------\n";
return 0;
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容