Sum of array using pointer arithmetic

Given an array, write a program to find the sum of array using pointers arithmetic.

In this program we make use of * operator . The * (asterisk) operator denotes the value of variable. The * operator at the time of declaration denotes that this is a pointer, otherwise it denotes the value of the memory location pointed by the pointer .
sum() function is used to find the sum of the array through pointers.

Examples :

Input : array = 2, 4, -6, 5, 8, -1
Output : sum = 12

Input :  array = 1, 4, -6, 8, -10, -12
Output : sum = -15

filter_none

edit
close

play_arrow

link
brightness_4
code

// CPP program to find sum of array using pointers
#include <iostream>
using namespace std;
  
// Function to find the sum of the array
void sum(int* array, int length)
{
    int i, sum_of_array = 0;
    for (i = 0; i < length; i++)
        sum_of_array = sum_of_array + *(array + i);
    cout << "sum of array is = " << sum_of_array;
}
// Driver function
int main()
{
    // Array to hold the values
    int array[] = { 2, 4, -6, 5, 8, -1 };
    sum(array, 6);
    return 0;
}
chevron_right

Output :

sum of array is = 12

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.


Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :
C
Practice Tags :