beginnersbook.com

  • Home
  • All Tutorials
    • Learn Servlet
    • Learn JSP
    • Learn JSTL
    • Learn C
    • Learn C++
    • Learn MongoDB
    • Learn XML
    • Learn Python
    • Learn Perl
    • Learn Kotlin
  • Core Java
  • OOPs
  • Collections
  • Java I/O
  • JSON
  • DBMS

C Program to find sum of array elements using pointers, recursion & functions

By Chaitanya Singh | Filed Under: C Programs

In this tutorial, we will learn following two ways to find out the sum of array elements:
1) Using Recursion
2) Using Pointers

Method 1: Sum of array elements using Recursion: Function calling itself

This program calls the user defined function sum_array_elements() and the function calls itself recursively. Here we have hardcoded the array elements but if you want user to input the values, you can use a for loop and scanf function, same way as I did in the next section (Method 2: Using pointers) of this post.

#include<stdio.h>
int main()
{
   int array[] = {1,2,3,4,5,6,7};
   int sum;
   sum = sum_array_elements(array,6);
   printf("\nSum of array elements is:%d",sum);
   return 0;
}
int sum_array_elements( int arr[], int n ) {
   if (n < 0) {
     //base case:
     return 0;
   } else{
     //Recursion: calling itself
     return arr[n] + sum_array_elements(arr, n-1);
    }
}

Output:

Sum of array elements is:28

Method 2: Sum of array elements using pointers

Here we are setting up the pointer to the base address of array and then we are incrementing pointer and using * operator to get & sum-up the values of all the array elements.

#include<stdio.h>
int main()
{
   int array[5];
   int i,sum=0;
   int *ptr;

   printf("\nEnter array elements (5 integer values):");
   for(i=0;i<5;i++)
      scanf("%d",&array[i]);

   /* array is equal to base address
    * array = &array[0] */
   ptr = array;

   for(i=0;i<5;i++) 
   {
      //*ptr refers to the value at address
      sum = sum + *ptr;
      ptr++;
   }

   printf("\nThe sum is: %d",sum);
}

Output:

Enter array elements (5 integer values): 1 2 3 4 5
The sum is: 15

Enjoyed this post? Try these related posts

  1. Quicksort program in C
  2. C Program to Find the Largest of three numbers using Pointers
  3. C Program to Swap two numbers
  4. C Program to Convert Octal Number to Binary Number
  5. C Program to calculate Area of Equilatral triangle
  6. Selection Sort Program in C

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Programs

  • C Programs
  • Java Programs

Recently Added..

  • JSON Tutorial
  • Java Regular Expressions Tutorial
  • Java Enum Tutorial
  • Java Annotations Tutorial

Copyright © 2012 – 2019 BeginnersBook . Privacy Policy . Sitemap