Home >Backend Development >C++ >How to calculate the sum of array elements in C using pointers?
A pointer is a variable that stores the address of other variables.
Consider the following statement-
int qty = 179;
The syntax for declaring a pointer is as follows-
int *p;
Here,' p' is a pointer variable that holds the address of other variables.
The address operator (&) is used to initialize pointer variables.
For example,
int qty = 175; int *p; p= &qty;
It is a collection of addresses (or) a collection of pointers.
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.
'&' 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;
Indirection operator (*) is used for accessing.
For example,
for (i=0, i<3; i++) printf ("%d", *p[i]);
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; }
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!