C program to find sum of the array elements using pointers is a simple and easy program to calculate the sum of the element stored in an array using a pointer.

What is a pointer in c?
The pointer is a variable that stores the address of another variable.
The syntax for pointers in c
<Datatype> *pointername;

Example:-
int *ptr;

Accessing the value of a variable:-
& Address of the operator gives the address of the variable.
* gives the value at that address stored in the pointer variable.
How to find sum of the array elements using pointers
we first take input numbers in the array. Then we copy the base address of the array to the pointer variable. Then we read the number in an array from base address and calculate a sum. print the sum of elements in an array.

Algorithm to find sum of elements in array using pointer

  1. Declare variable
  2. Take input numbers
  3. Copy base address of array to a pointer variable
  4. Traverse array
    Calculate Sum
    If Array ends
    Stop
  5. Print sum of elements in array

Program to find sum of the array elements using pointers

#include<stdio.h>
main()
{
int i,n,sum=0,*ptr;
printf("Enter number \n");
scanf("%d",&n);
int var[n-1];
printf("Enter values in array\n");
for(i=0;i<n;i++)
{
scanf("%d",&var[i]);
}
ptr=&var[0];//you can also use ptr=var;
for(i=0;i<n;i++)
{
sum+=*ptr;
ptr++;
}

printf("Sum=%d\n",sum);
}

Output :
Find sum of the array elements using pointers

Write A Comment