int x[3] = { 1,2,3 }; int x[3] = { 1,2 };//未初始化的元素,默认0 int x[] = { 1,2,3 };//省略下标,依据元素个数自动变更下标 int x[2][2] = { 11,12,21,22 };//二维数组,效果同下 int x[2][2] = { {11,12},{21,22} };
数组的遍历
#include<iostream> using namespace std; int main() { int x[3]; for (int i = 0; i < 3; i++) { cin >> x[i];//从键盘输入3个数 } for (int i = 0; i < 3; i++)//遍历数组 { cout << x[i] << " ";//元素间以空格分隔 } cout << endl;//换行 return 0; }
排序算法,从小到大
#include<iostream> using namespace std; int main() { int x[5] = {3,2,1,4,5}; for (int i = 0; i < 4; i++) { for (int j = i + 1; j < 5; j++) { int temp; if (x[i] > x[j]){ temp = x[i]; x[i] = x[j]; x[j] = temp; } } for (int i = 0; i < 5; i++)//遍历数组 { cout << x[i] << " ";//元素间以空格分隔 } cout << endl;//换行 return 0; }