在循环入口处定义循环三要素,循环条件为真时执行循环体,先判断再循环。ios
C++中 for 循环的语法为:bash
for (init; condition; increment) {
statement(s);
}
复制代码
for 循环的执行顺序大体以下:spa
注意: init 、condition 和 increment 之间必定要以 ; 分号隔开,就算三个语句都为空也必定要有 ; 分号,不然会报错! code
for 循环的执行过程以下:cdn
打印 1997 年 7月的日历,1997.7.1 为星期二。blog
#include <iostream>
using namespace std;
int main() {
//打印1997年7月的月历
const int MONTH = 31;
const int WEEK = 7;
int day_of_week = 2; // 1997年7月1日为星期二
cout << "1997年7月的月历以下:" << endl;
cout << "一\t二\t三\t四\t五\t六\t日" << endl;
// 填充 1号以前的星期
for (int i = 0; i < day_of_week - 1; i++) {
cout << '\t';
}
for (int day = 1; day <= MONTH; day++) {
cout << day << '\t';
if (((day_of_week + day - 1) % WEEK) == 0)
cout << endl;
}
cout << endl;
system("pause");
return 0;
}
复制代码
输出结果以下:rem
1997年7月的月历以下:
一 二 三 四 五 六 日
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
请按任意键继续. . .
复制代码