阵列程序代码怎么写

时间:2025-01-28 08:47:29 单机游戏

编写阵列程序代码需要根据所使用的编程语言和阵列的类型(一维、二维、三维等)来进行。以下是几种常见编程语言中创建和操作阵列的示例代码:

C语言

一维阵列

```c

include

int main() {

int array = {1, 2, 3, 4, 5};

for (int i = 0; i < 5; i++) {

printf("%d ", array[i]);

}

printf("\n");

return 0;

}

```

二维阵列

```c

include

int main() {

int array = {

{1, 2, 3},

{4, 5, 6},

{7, 8, 9}

};

for (int i = 0; i < 3; i++) {

for (int j = 0; j < 3; j++) {

printf("%d ", array[i][j]);

}

printf("\n");

}

return 0;

}

```

结构体阵列

```c

include

struct Student {

char name;

char sex;

int age;

char addr;

};

int main() {

struct Student students;

for (int i = 0; i < 40; i++) {

printf("Enter name: ");

scanf("%s", students[i].name);

printf("Enter sex: ");

scanf("%s", students[i].sex);

printf("Enter age: ");

scanf("%d", &students[i].age);

printf("Enter address: ");

scanf("%s", students[i].addr);

}

return 0;

}

```

C++

一维阵列

```cpp

include

using namespace std;

int main() {

int array = {1, 2, 3, 4, 5};

for (int i = 0; i < 5; i++) {

cout << array[i] << " ";

}

cout << endl;

return 0;

}

```

二维阵列

```cpp

include

using namespace std;

int main() {

int array = {

{1, 2, 3},

{4, 5, 6},

{7, 8, 9}

};

for (int i = 0; i < 3; i++) {

for (int j = 0; j < 3; j++) {

cout << array[i][j] << " ";

}

cout << endl;

}

return 0;

}

```

结构体阵列

```cpp

include

include

using namespace std;

struct Student {

string name;

string sex;

int age;

string addr;

};

int main() {

Student students;

for (int i = 0; i < 40; i++) {

cout << "Enter name: ";

cin >> students[i].name;

cout << "Enter sex: ";

cin >> students[i].sex;

cout << "Enter age: ";

cin >> students[i].age;

cout << "Enter address: ";

cin >> students[i].addr;

}

return 0;

}

```

Python

一维阵列

```python

array = [1, 2, 3, 4, 5]

for i in array:

print(i, end=" ")

print()

```

二维阵列