作用:用于跳出选择结构 或者 循环结构
使用时机:
- 出现在switch条件语句中,作用是终止case并跳出switch
- 出现在循环语句中,作用是跳出当前的循环语句
- 出现在嵌套循环中,跳出最近的内层循环语句
2. continue语句
作用:在循环语句中,跳过本次循环中余下尚未执行的语句,继续执行下一次循环
3. goto语句
作用:可以无条件跳转语句
语法:goto 标记
;
解释:如果标记的名称存在,执行到goto语句时,会跳转到标记的位置
int main(){
cout << "1、xxxxx" << endl;
goto FLAG;
cout << "2、xxxxx" << endl;
cout << "3、xxxxx" << endl;
cout << "4、xxxxx" << endl;
FLAG:
cout << "5、xxxxx" << endl;
}
数组就是一个集合,里面存放了相同类型的数据元素
定义时必须有初始长度
特点1:数组中的每个 数据元素都是相同的数据类型
特点2:数组是由 连续的内存 位置组成的
数组名是一个常量,不可以进行赋值操作
1. `int arr[5];`
2. `int arr[5] = {1,2,3,4,5};`
3. `int arr[] = {1,2,3,4,5,6,7,8,9};`
统计整个数组在内存中的长度
sizeof(arr);
cout << 数组中元素个数为 << sizeof(arr)/sizeof(arr[0]) << endl;
可以获取数组在内存中的首地址
cout << "数组首地址为" << arr << endl;
& 为取址符号
cout << "数组中第一个元素地址为" << &arr[0] << endl;
cout << "数组中第一个元素地址为" << (int)&arr[0] << endl;
int main(){
int mid;
int arr[9] = {2,4,0,5,7,1,3,8,9};
for(int i=0;i<9-1;i++){
for(int j=0;j<9-i-1;j++){
if(arr[j]>arr[j+1]){
mid = arr[j];
arr[j] = arr[j+1];
arr[j+1] = mid;
}
}
}
for(int i=0;i<9;i++){
cout << arr[i] << " ";
}
}
定义方式:
int arr[2][3];
int arr[2][3] = {
{1,2,3},
{4,5,6}
};
int arr[2][3] = {1,2,3,4,5,6};
int arr[][3] = {1,2,3,4,5,6};
数组名称的用途:
函数的定义以及使用:
定义的add函数需要放在main函数前面
#include
using namespace std;
int add(int a,int b){
return a+b;
}
int main(){
int x = 2;
int y = 9;
int sum = add(x,y);
cout << sum <<endl;
return 0;
}
值传递的时候,如果==形参发生变化,并不会影响实参==
1. 提前告诉编译器函数的存在
2. 声明可以写多次,但是定义只能有一次
#include
using namespace std;
// 函数声明语句,大括号不写
int max(int a,int b);
int main(){
int res = max(5,6);
cout << "max=" << res ;
return 0;
}
int max(int a,int b){
return (a>b?a:b);
}
创建 .h 后缀名的头文件
创建 .cpp 后缀名的源文件
在头文件中写函数的声明
#include
using namespace std;
// 函数声明
void swap(int a,int b);
在源文件中写函数的定义
#include "swap.h"
void swap(int a,int b){
int temp = a;
a = b;
b = temp;
cout << "a=" << a << endl;
cout << "b=" << b << endl;
}