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;
}