Sum of array using pointer arithmetic in C++

C++Server Side ProgrammingProgramming

This is a C++ program to find out sum of array elements using pointer.

Algorithm

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

Example Code

 Live Demo

#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;
}

Output

Enter the Numbers: 1 2 3 4 5 6 7
Sum of Elements of Array: 28
raja
Published on 29-Mar-2019 10:17:35
Advertisements