条件控制

作用域 定义变量只在{}内部生效

初始化 if(int pow = x * x; pow < 100)

通常书写

1
2
3
4
5
6
7
if (x < 0) {
cout << "if branch" << endl;
} else if (x == 0) {
cout << "else if branch" << endl;
} else {
cout << "else branch" << endl;
}

书写规范:同样如果只有一行代码可写成一行增加代码的可阅读性

if(condition) only_one_statement

循环控制

1
2
3
for(init; condition;iteration){
loop-statement
}

循环嵌套

示例九九乘法表

1
2
3
4
5
6
for(int a = 1; a <= 9; a++){
for(int b = 1; b <= a; b++){
cout << format("{}*{}={:<2}", a, b, a*b);
}
cout << endl;
}

跳转控制

break 打破循环,直接结束循环

coutinue 继续循环 跳过后续未执行的循环体,跳到迭代语句和循环条件之前

goto 任意跳转至某一个标签

1
2
3
4
5
6
7
label:
if(i < 100){
cin >> x;
sum += x;
i ++;
goto label;
}