数组是程序编程过程中不可避免的一部分,本次是用5种语言来进行数组的简略应用示例。
C语言:
int a[10000], b[100][100]; // 定义数组,数组下标从0开始
for (int i = 0; i < 100; i++) // 输入数组
scanf("%d", &a[i]);
for (int i = 0; i < 100; i++) // 遍历数组
printf("%d\n", a[i]);
int t = 5; // 以下为将元素t插入至数组中
for (int i = 6; i < 10000; i++)
a[i] = a[i - 1];
a[5] = t;
for (int i = 5; i < 9999; i++) // 删除数组第6个元素
a[i] = a[i + 1];
C++:
int a[10000], b[100][100]; // 定义数组,数组下标从0开始
for (int i = 0; i < 100; i++) // 输入数组
cin>>a[i];
for (int i = 0; i < 100; i++) // 遍历数组
cout << a[i] << endl;
int t = 5; // 以下为将元素t插入至数组中
for (int i = 6; i < 10000; i++)
a[i] = a[i - 1];
a[5] = t;
for (int i = 5; i < 9999; i++) // 删除数组第6个元素
a[i] = a[i + 1];
``
C#
namespace ArrayApplication
{
class MyArray
{
static void Main(string[] args)
{
int [] n = new int[10]; /*定义 n 是一个带有 10 个整数的数组 */
int i,j;
/* 初始化数组 n 中的元素 */
for ( i = 0; i < 10; i++ )
{
n[ i ] = i + 100;
}
/* 输出每个数组元素的值 */
for (j = 0; j < 10; j++ )
{
Console.WriteLine("Element[{0}] = {1}", j, n[j]);
}
/* 用foreach输出每个数组元素的值 */
foreach (int j in n )
{
int i = j-100;
Console.WriteLine("Element[{0}] = {1}", i, j);
}
Console.ReadKey();
}
}
}
Python
Python数组用法比较繁琐,有前辈总结十分详细,
走传递门:python用法笔记(数组(list、touple、dict)、字符串) - likai_liche
str='Runoob'
print(str) # 输出字符串
print(str[0:-1]) # 输出第一个到倒数第二个的所有字符
print(str[0]) # 输出字符串第一个字符
print(str[2:5]) # 输出从第三个开始到第五个的字符
print(str[2:]) # 输出从第三个开始的后的所有字符
print(str * 2) # 输出字符串两次
print(str + '你好') # 连接字符串
print('------------------------------')
print('hello\nrunoob') # 使用反斜杠(\)+n转义特殊字符
print(r'hello\nrunoob') # 在字符串前面添加一个 r,表示原始字符串,不会发生转义
#输出结果
#Runoob
#Runoo
#R
#noo
#noob
#RunoobRunoob
#Runoob你好
------------------------------
#hello
#runoob
#hello\nrunoob
Java
/*数组定义的两种方式*/
int[] x = new int[3];
int[] y = { 1, 2, 3 };
/*数组初始化的两种方式*/
int[] arr = { 1, 2, 3, 4, 5 };
int[] arr2 = new int[] { 1, 2, 3, 4, 5 };
/*数组遍历*/
public static void main(String[] args) {
int[] x = { 1, 2, 3 };
for (int y = 0; y < x.length; y++) { //数组中有一个属性可以获取是数组的长度. 数组名.length
System.out.println(x[y]);
// System.out.println("x["+y+"]="+x[y]); 打印效果 x[0]=1;
}
}
/*数组排序*/
import java.util.Arrays;
public class ArrayUtil {
public static void main(String[] args) {
int[] a = new int[]{1, 33, 5, 44, 76};//1,5,33,44,76
System.out.println("排序之前:");
arrayPrint(a);
Arrays.sort(a);
System.out.println("排序之后:");
//改变原数组
arrayPrint(a);
}
public static void arrayPrint(int[] c) {
if (c == null) {
return;
}
for (int j = 0; j < c.length; j++) {
System.out.print(c[j] + " ");
}
System.out.println();
}
}