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?

王林
Release: 2023-09-10 20:45:03
forward
1573 people have browsed it

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

Consider the following statement-

int qty = 179;
Copy after login

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

Declaring a pointer

The syntax for declaring a pointer is as follows-

int *p;
Copy after login

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;
Copy after login

Pointer array

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

Declaration

The following is the declaration of an array of pointers -< /p>

datatype *pointername [size];
Copy after login

For example,

int *p[5];
Copy after login

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;
Copy after login

Accessing

Indirection operator (*) is used for accessing.

For example,

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

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;
}
Copy after login

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
Copy after login

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!

Related labels:
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template