一、跳转语句
1.break语句
作用:用于跳出选择结构或者循环结构
break使用时机:
- 出现在switch条件语句中,作用是终止case并跳出switch
- 出现在循环语句中,作用是跳出当前的循环语句
- 出现在嵌套循环中,作用是跳出最近的内层循环语句
2.continue语句
作用:在循环语句中,跳过本次循环中余下未执行的语句,继续执行下一次循环
注意:continue并没有使整个循环终止,而break会跳出循环
3.goto语句
作用:可以无条件跳转语句
语法:goto 标记;
解释:如果标记的名称存在,执行到goto语句时,会跳转到标记的位置
#include<iostream>
using namespace std;
int main() {
cout << "1.xxxxx" << endl;
cout << "2.xxxxx" << endl;
goto FLAG;
cout << "3.xxxxx" << endl;
cout << "4.xxxxx" << endl;
FLAG:
cout << "5.xxxxx" << endl;
system("pause");
return 0;
}
二、数组
1.一维数组
特点:
- 数组中的每个数据元素都是相同的数据类型
- 数组是由连续的内存空间组成的
三种定义方式:
- 数据类型 数组名[ 数组长度 ];
- 数据类型 数组名[ 数组长度 ] = { 值1,值2 ... };
- 数据类型 数组名[ ] = { 值1,值2 ... };
#include<iostream>
using namespace std;
int main() {
//1.数据类型 数组名[ 数组长度 ];
/*int arr[3];
arr[0] = 10;
arr[1] = 20;
arr[2] = 30;
cout << arr[0] << endl;
cout << arr[1] << endl;
cout << arr[2] << endl;*/
//2.数据类型 数组名[ 数组长度 ] = { 值1,值2 ... };
/*int arr2[5] = { 10,20,30,40,50 };
for (int i = 0; i < 5; i++)
{
cout << arr2[i] << endl;
}*/
//3.数据类型 数组名[ ] = { 值1,值2 ... };
int arr3[] = { 50,40,30,20,10,5 };
for (int i = 0; i < 6; i++)
{
cout << arr3[i] << endl;
}
system("pause");
return 0;
}
2.二维数组
四种定义方式:
- 数据类型 数组名[ 行数 ][ 列数 ];
- 数据类型 数组名[ 行数 ][ 列数 ] = {{数据1,数据2},{数据3,数据4}};
- 数据类型 数组名[ 行数 ][ 列数 ] = {数据1,数据2,数据3,数据4};
- 数据类型 数组名[ ][ 列数 ] = {数据1,数据2,数据3,数据4};
建议使用第二种方式,因为第二种方式更直观,可以提高代码的可读性
#include<iostream>
using namespace std;
int main() {
//二维数组
//1.数据类型 数组名[ 行数 ][ 列数 ];
/*int arr[2][3];
arr[0][0] = 1;
arr[0][1] = 2;
arr[0][2] = 3;
arr[1][0] = 4;
arr[1][1] = 5;
arr[1][2] = 6;
//外层循环打印行数,内层循环打印列数
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 3; j++)
{
cout << arr[i][j] << " ";
}
cout << endl;
}*/
//2.数据类型 数组名[ 行数 ][ 列数 ] = {{数据1,数据2},{数据3,数据4}};
/*int arr1[2][3] = { {1,2,3},{4,5,6} };
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 3; j++)
{
cout << arr1[i][j] << " ";
}
cout << endl;
}*/
//3.数据类型 数组名[ 行数 ][ 列数 ] = {数据1,数据2,数据3,数据4};
/*int arr2[2][3] = { 1,2,3,4,5,6 };
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 3; j++)
{
cout << arr2[i][j] << " ";
}
cout << endl;
}*/
//4.数据类型 数组名[ ][ 列数 ] = {数据1,数据2,数据3,数据4};
int arr3[][3] = { 1,2,3,4,5,6 };
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 3; j++)
{
cout << arr3[i][j] << " ";
}
cout << endl;
}
system("pause");
return 0;
}
三、函数
函数定义的5个步骤:
- 返回值类型
- 函数名
- 参数列表
- 函数体语句
- return表达式
返回值类型 函数名(参数列表)
{
函数体语句
return表达式
}
函数声明
作用:告诉编译器函数名称及如何调用函数,函数的实际主体可以单独定义
注意:函数的声明可以多次,但是函数的定义只能有一次
返回值类型 函数名(参数列表);
函数分文件编写
作用:让代码结构更加清晰
函数分文件编写的步骤:
- 创建后缀名为.h的头文件
- 创建后缀名为.cpp的源文件
- 在头文件中写函数的声明
- 在源文件中写函数的定义
//swap.h文件
#include<iostream>
using namespace std;
//实现两个数字交换的函数声明
void swap(int a, int b);
//swap.cpp文件
#include "swap.h"
//函数的定义
void swap(int a, int b)
{
int temp = a;
a = b;
b = temp;
cout << "a = " << a << endl;
cout << "b = " << b << endl;
}
#include<iostream>
using namespace std;
#include "swap.h"
int main()
{
int a = 10;
int b = 20;
swap(a, b);
system("pause");
return 0;
}