Part 1 程序结构
顺序结构(一条线):
#include <iostream>
using namespace std;
int main()
{
int a;
cin >> a;
cout << a << endl;
return 0;
}
分支结构(选择结构):
定义:根据表达式的结果来确定执行哪一条语句。
比如,这里有一个判断正数的程序。
#include <bits/stdc++.h>
using namespace std;
int main()
{
int num;
cin >> num;
if (num > 0)
{
cout << "yes";
}
else
{
cout << "no";
}
return 0;
}
循环结构:
定义:重复执行一段语句。
Part 2 if语句
格式:
if (表达式)
{
代码(一句或多句,只有一句代码可以不用{})
}
样例代码:
#include <iostream>
using namespace std;
int main()
{
if (3 > 2)
{
cout << "3 比 2 大";
}
return 0;
}
输出结果:
3 比 2 大
注意: if语句只关注表达式最终结果是True还是False,True就运行,False则不运行
{}的作用:将多条简单语句,结合成一条复合语句。
Part 3 if-else语句
格式:
if (表达式1)
{
代码1
}
else
{
代码2
}
样例代码:
#include <iostream>
using namespace std;
int main()
{
if (3 > 2)
{
cout << "yes";
}
else
{
cout << "no";
}
}
输出结果:
yes
在if-else中,不管"表达式1"是否成立,都有输出
当"表达式1"成立时,会运行"代码1";
当"表达式1"不成立时,会运行"代码2"。
Part 4 if-else if-else语句
格式:
if (表达式1)
{
代码1
}
else if(表达式2) // 此处 "else" 和 "if" 中间的 " " 不可省略
{
代码2
}
else
{
代码3
}
样例代码:
#include <iostream>
using namespace std;
int main()
{
if (1 > 2)
{
cout << "1 yes";
}
else if(1 < 2)
{
cout << "2 yes";
}
else
{
cout << "all no";
}
return 0;
}
输出结果:
2 yes
在使用 if-else if-else 语句中,会按照顺序从上到下进行判断,如果有表达式成立,则会运行对应的代码;如果没有条件成立,则会运行else的语句。
Part 5 switch-case语句
switch (表达式)
{
case 常量表达式1:
语句组1;
break; ---> 退出switch
case 常量表达式2:
语句组2;
break;
.......
case 常量表达式n:
语句组n;
break;
default:
语句组n+1;
}
样例代码:
#include <iostream>
using namespace std;
int main()
{
int n = 3;
switch (n)
{
case 1:
cout << "*" << endl;
break;
case 2:
cout << "**" << endl;
break;
case 3:
cout << "***" << endl;
break;
default:
cout << "no" << endl;
break;
}
return 0;
}
输出结果:
***
计算表达式的值,将case后面的常量表达式值逐一与之匹配。当某一个case分支中的常量表达式值与之匹配时则执行该分支后面的语句组,然后顺序执行之后的所有语句,直到遇到break语句或switch语句的"}"为止。
在switch中,所有语句全部共用同一个switch的"{}"。