This C Program calculates the sum of all elements of an array using pointers as arguments.
The program calls a function to add all the element of an array and passes the array argument as a pointer.
1. Create a static array of some fixed size, along with element declaration.
2. Build a function with a single argument, in which we will pass array argument.
3. Inside this function, all the elements of the array are accessed one-by-one, adding to return the sum.
4. Return sum to the called function and print it.
Here is source code of the C program to calculate sum of all elements of an array using pointers as arguments. The program is successfully compiled and tested using Turbo C compiler in windows environment. The program output is also shown below.
/*
* C program to find the sum of all elements of an array using
* pointers as arguments.
*/
#include <stdio.h>
void main()
{
static int array[5] = { 200, 400, 600, 800, 1000 };
int sum;
int addnum(int *ptr);
sum = addnum(array);
printf("Sum of all array elements = %5d\n", sum);
}
int addnum(int *ptr)
{
int index, total = 0;
for (index = 0; index < 5; index++)
{
total += *(ptr + index);
}
return(total);
}
1. Declare a static array of some fixed size along with array element definition.
2. Take a variable sum, which will store the total sum of all the array elements.
3. Create a function with a single argument, in which we will pass the above created array argument. This function will return the sum.
4. Inside this function, a for loop will run from 0 to array size-1, accessing each element of array by adding the iterator i to the pointer variable (array argument, which was passed to this function).
5. Elements will get add and the total sum will be returned from this function.
6. Variable sum inside main() function, will get this returned value and will be printed.
Sum of all array elements = 3000
Sanfoundry Global Education & Learning Series – 1000 C Programs.
Here’s the list of Best Books in C Programming, Data Structures and Algorithms.
- Practice BCA MCQs
- Apply for Computer Science Internship
- Apply for C Internship
- Check Computer Science Books
- Watch Advanced C Programming Videos