Home >Backend Development >C++ >How to calculate the sum of array elements in C using pointers?

How to calculate the sum of array elements in C using pointers?

王林
王林forward
2023-09-10 20:45:031423browse

A pointer is a variable that stores the address of other variables.

Consider the following statement-

int qty = 179;

How to calculate the sum of array elements in C using pointers?

Declaring a pointer h2>

The syntax for declaring a pointer is as follows-

int *p;

Here,' p' is a pointer variable that holds the address of other variables.

Initialization of pointers

The address operator (&) is used to initialize pointer variables.

For example,

int qty = 175;
int *p;
p= &qty;

Pointer array

It is a collection of addresses (or) a collection of pointers.

Declaration

The following is the declaration of an array of pointers -

datatype *pointername [size];

For example,

int *p[5];

It represents an array of pointers that can hold five integer element addresses.

Initialization

'&' is used for initialization

For example,

int a[3] = {10,20,30};
int *p[3], i;
for (i=0; i<3; i++) (or) for (i=0; i<3,i++)
p[i] = &a[i];
p[i] = a+i;

Accessing

Indirection operator (*) is used for accessing.

For example,

for (i=0, i<3; i++)
printf ("%d", *p[i]);

Program

The following is a C program that uses pointers to calculate the sum of array elements-

Live demonstration

//sum of array elements using pointers
#include <stdio.h>
#include <malloc.h>
void main(){
   int i, n, sum = 0;
   int *ptr;
   printf("Enter size of array : </p><p>");
   scanf("%d", &n);
   ptr = (int *) malloc(n * sizeof(int));
   printf("Enter elements in the List </p><p>");
   for (i = 0; i < n; i++){
      scanf("%d", ptr + i);
   }
   //calculate sum of elements
   for (i = 0; i < n; i++){
      sum = sum + *(ptr + i);
   }
   printf("Sum of all elements in an array is = %d</p><p>", sum);
   return 0;
}

Output

When the above program is executed, the following results are produced-

Enter size of array:
5
Enter elements in the List
12
13
14
15
16
Sum of all elements in an array is = 70

The above is the detailed content of How to calculate the sum of array elements in C using pointers?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete