This blog is under construction

Sunday, 21 July 2013

C program to find the sum of n numbers using pointers

Write a C program to find the sum of N numbers using pointers.


  #include <stdio.h>
  #include <stdlib.h>

  /* finds the sum of given n elements */
  void findSum(int *data, int n, int *res)  {
        int i;
        for (i = 0; i < n; i++) {
                *res = *res + *(data + i);
        }
        return;
  }

  int main() {
        int i, n, res = 0, *data;

        /* get the number of inputs from the user */
        printf("Enter the number of inputs:");
        scanf("%d", &n);

        /* dynamically allocate memory for n elements */
        data = (int *) malloc(sizeof(int) * n);

        /* input n elements from the user */
        for (i = 0; i < n; i++) {
                printf("Data[%d] : ", i);
                scanf("%d", &data[i]);
        }

        /* calculates the sum of n elements */
        findSum(data, n, &res);

        /* print the result */
        printf("Sum of given %d numbers is %d\n", n, res);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter the number of inputs:5
  Data[0] : 10
  Data[1] : 20
  Data[2] : 30
  Data[3] : 40
  Data[4] : 50
  Sum of given 5 numbers is 150


No comments:

Post a Comment