新闻资讯

质量为本、客户为根、勇于拼搏、务实创新

< 返回新闻资讯列表

c语言数组相加如何用for循环实现,c语言数组里面的数求和

发布时间:2024-05-23 17:40:14

c语言数组相加如何用for循环实现

可使用for循环遍历两个数组,然后将对应位置的元素相加并存储到一个新数组中。以下是一个示例代码:

#include <stdio.h>

int main() {
    int arr1[] = {1, 2, 3, 4, 5};
    int arr2[] = {6, 7, 8, 9, 10};
    int result[5];

    for (int i = 0; i < 5; i++) {
        result[i] = arr1[i] + arr2[i];
    }

    printf("Sum of arrays:
");
    for (int i = 0; i < 5; i++) {
        printf("%d + %d = %d
", arr1[i], arr2[i], result[i]);
    }

    return 0;
}

在这个示例中,我们定义了两个数组arr1和arr2,然后使用for循环遍历数组并将对应位置的元素相加存储到result数组中。最后使用另外一个for循环打印出相加的结果。固然,这只是一个简单的示例,实际利用中可能会根据具体需求进行更复杂的操作。