C++基础--数组

1. 一维概念

#include<iostream>
using namespace std;

int main(){
//1.数据类型 数组名[数组长度]
	int score[3];
	score[0]=100;
	score[1]=50;
	score[2]=50;
	cout << score[0] << endl;

//2. 数据类型 数组名[数组长度]={值1,值2,值3,....}
	int arr[5]={1,2,3,4,5};
	for(int i=0;i<5;i++){
		cout << arr[i] <<endl;
	}

//3.数据类型 数组名[]={值1,值2,值3,....}
	int a[]={0,0,3,4,5};
	for(int j=0;j<5;j++){
		cout << a[j] <<endl;
	}

	system("pause");
	return 0;

}

2. 一维数组

#include<iostream>
using namespace std;

int main(){
	int arr[10]={1,2,3,4,5,6,7,8,9,10};
//通过sizeof()查看数组长度
	cout <<"整个数组占用的长度:"<<sizeof(arr)<<endl;
	cout <<"arr[0]占用的长度:"<<sizeof(arr[0])<<endl;
//通过&取地址运算符查看数组地址
	cout << "数组的首地址为:" <<int(arr) <<endl;
	cout << "第一个元素的首地址为:" <<(int)&arr[0]<<endl;
	cout << "第二个元素的地址为:" <<(int)&arr[1]<<endl;
//数组名是常量,不可以进行赋值操作 arr=10是错误的

	system("pause");
	return 0;

}

3. 二维概念

#include<iostream>
using namespace std;

int main(){
//1.数据类型 数组名[行数][列数]
	int a[2][2];
	a[0][0] = 1;
	a[0][1] = 2;
	a[1][0] = 2;
	a[1][1] = 1;
	
   	for(int i=0;i<2;i++){
		for(int j=0;j<2;j++){
			cout<<a[i][j] <<" ";
		}
		cout <<  endl;
	}
//2.数据类型 数组名[行数][列数]={{数据1,数据2},{数据3,数据4},....}
	int arr[2][3]=
	{
		{1,2,3},
		{2,1,3}
	};
  	for(int i=0;i<2;i++){
		for(int j=0;j<3;j++){
			cout<<arr[i][j] <<" ";
		}
		cout <<endl;
	}
//3.数据类型 数组名[行数][列数]={数据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;
	}
//4.数据类型 数组名[][列数]={数据1,数据2,数据3,数据4,....}
	int arr2[][3]={1,2,5,6,4,8};

	system("pause");
	return 0;
}

4. 二维数组

#include<iostream>
using namespace std;

int main(){
	int a[2][3]={
		{1,2,3},
		{4,5,6}
	};
	
	cout << "二维数组占用的内存空间为:" <<endl;
	cout << sizeof(a) << endl;
	cout << "二维数组一行占用的内存空间为:" <<endl;
	cout << sizeof(a[0]) << endl;
	cout << "二维数组每一个元素占用的内存空间为:"<<endl;
	cout << sizeof(a[0][0]) << endl;

	cout << "二维数组的首地址为:" <<endl ;
	cout << (int)&a[0][0] <<endl;
	cout << "二维数组的第二行首地址为:" <<endl ;
	cout << (int)&a[1][0] <<endl;

	system("pause");
	return 0;
}

5. 冒泡排序

#include<iostream>
using namespace std;

int main(){


int a[9]={4,5,6,8,9,3,1,7,0};
int end=sizeof(a)/sizeof(a[0]) -1;
int temp=0;
for(int i=0;i<=end;i++){
	for(int j=0;j<=end-i;j++){
		if(a[j]>a[j+1]){
			temp=a[j];
			a[j]=a[j+1];
			a[j+1]=temp;
		}
	}
}
for(int m=0;m<=end;m++){
	cout <<a[m]<<endl;	
}

system("pause");
return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值