使用 C++ 中的指针运算求数组的和


这是一个使用指针查找数组元素之和的 C++ 程序。

算法

Begin
   Initialize the array elements with values from user input.
   Initialize s = 0
   Loop for i = 0 to
      s = s + *(ptr + i)
   Print the sum value in variable s.
End

示例代码

 动态演示

#include<iostream>
using namespace std;
int main() {
   int a[7], i, s = 0;
   int *ptr;
   cout << "Enter the Numbers: ";
   for (i = 0; i < 7; i++) {
      cin >> a[i];
   }
   ptr = a;
   for (i = 0; i < 7; i++) {
      s = s + *(ptr + i);
   }
cout << "\nSum of Elements of Array: " << s;
}

输出

Enter the Numbers: 1 2 3 4 5 6 7
Sum of Elements of Array: 28

更新于: 30-Jul-2019

3K+ 浏览量

开启你的 职业生涯

通过完成该课程获得认证

开始
广告
© . All rights reserved.