C语言数组运算——第七周数组运算(C language array operation — array operation in week 7)

数组运算

数组的集成初始化

int a[]={2,4,6,8,44,11,23};

数组的大小

sizeof给出整个数组所占据的内容的大小,单位是字节

数组的单元个数:siezeof(a)/sizeof(a[0])

数组的赋值

必须采用遍历

遍历数组做赋值

for(i=0;i<length;i++){
    b[i] = a[i];
}

遍历数组做初始化

for(i=0;i<number;i++){
    count[i] = 0;
}

遍历数组去判断

for(i=0;i<length;i++){
    if(a[i] == key){
        ret = i;
        break;
    }
}

遍历数组看结果是否要输出

for(i=0;i<cnt;i++){
    if(number[i] >average){
        printf("%d",number[i]);
    }
}

遍历数组看每一个计数值的大小

for(i=0;i<number;i++){
        printf("%d:%d\n",i,count[i]);
}

eg

#include <stdio.h>
/*
找出key在数组a中的位置
key:要寻找的数组
a:要寻找的数组
length:数组a的长度
return:如果找到,返回其在a中的位置,如果找不到则返回-1 
*/
int search(int key,int a[],int length);
int main(void){
    int a[]={2,4,6,7,1,3,5,9,11,13,23,14,32,};
    int x;
    int loc;
    printf("请输入一个数字:");
    scanf("%d",&x);
    loc=search(x,a,sizeof(a)/sizeof(a[0]));
    if(loc == -1){
        printf("%d不存在\n",x);
    } else{
        printf("%d在第%d个位置上\n",x,loc);
    }
    return 0;
}
int search(int key,int a[],int length){
    int ret = -1;
    int i;
    for(i=0;i<length;i++){
        if(a[i] == key){
            ret = i;
            break;
        }
    }
    return ret;
}

数组作为函数参数时,必须再用另一个参数来传入数组的大小

————————

Array operation

Integrated initialization of arrays

int a[]={2,4,6,8,44,11,23};

The size of the array

Sizeof gives the size of the contents occupied by the entire array, in bytes

Number of cells in the array: siezof (a) / sizeof (a [0])

Assignment of array

Traversal must be used

Traversing the array for assignment

for(i=0;i<length;i++){
    b[i] = a[i];
}

Traverse the array for initialization

for(i=0;i<number;i++){
    count[i] = 0;
}

Traverse the array to determine

for(i=0;i<length;i++){
    if(a[i] == key){
        ret = i;
        break;
    }
}

Traverse the array to see if the result should be output

for(i=0;i<cnt;i++){
    if(number[i] >average){
        printf("%d",number[i]);
    }
}

Traverse the array to see the size of each count value

for(i=0;i<number;i++){
        printf("%d:%d\n",i,count[i]);
}

eg

#include <stdio.h>
/*
找出key在数组a中的位置
key:要寻找的数组
a:要寻找的数组
length:数组a的长度
return:如果找到,返回其在a中的位置,如果找不到则返回-1 
*/
int search(int key,int a[],int length);
int main(void){
    int a[]={2,4,6,7,1,3,5,9,11,13,23,14,32,};
    int x;
    int loc;
    printf("请输入一个数字:");
    scanf("%d",&x);
    loc=search(x,a,sizeof(a)/sizeof(a[0]));
    if(loc == -1){
        printf("%d不存在\n",x);
    } else{
        printf("%d在第%d个位置上\n",x,loc);
    }
    return 0;
}
int search(int key,int a[],int length){
    int ret = -1;
    int i;
    for(i=0;i<length;i++){
        if(a[i] == key){
            ret = i;
            break;
        }
    }
    return ret;
}

When an array is used as a function parameter, another parameter must be used to pass in the size of the array