处理数组的函数,我们有两种表示方法

①函数原型: int sum_arr(int arr[], int n)

#include <iostream>
const int ArSize = 8;
int sum_arr(int arr[], int n);
using namespace std;

int main()
{
    int arr[ArSize] = {1,2,3,4,5,6,7,8};
    cout << "Total is " << sum_arr(arr, ArSize) << endl;
    cout << "The sum of the first four number is " << sum_arr(arr, 4) << endl;
    cout << "The sum of the last four number is " << sum_arr(arr + 4, 4) << endl;
    return 0;
}

int sum_arr(int arr[], int n)
{
    int total = 0;
    for(int i = 0; i < n; i++)
        total += arr[i];
    return total;
}
在这种表示方法中,int sum_arr(int arr[], int n) 指出了数组名称是arr,数组中元素的个数是n


②函数原型: int sum_arr(const int * begin, const int * end)

#include <iostream>
const int ArSize = 8;
int sum_arr(const int * begin, const int * end);
using namespace std;

int main()
{
    int arr[ArSize] = {1,2,3,4,5,6,7,8};
    cout << "Total is " << sum_arr(arr, arr + ArSize) << endl;
    cout << "The sum of the first four number is " << sum_arr(arr, arr + 4) << endl;
    cout << "The sum of the last four number is " << sum_arr(arr + 4, arr + 8) << endl;
    return 0;
}

int sum_arr(const int * begin, const int * end)
{
    int total = 0;
    const int *p_int = begin;
    for(p_int = begin; p_int < end; p_int++)
        total += *p_int;
    return total;
}
在这种表示方法中,int sum_arr(const int * begin, const int * end)指出了数组的起始位置是begin,结束位置是end

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值