0

My task is to write a function which calculates sum of elements of array. which I did like so:

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

int sum (int array[], int len){
    int i;
    int sum=0;
    for (i=0; i<len; i++){
    sum = sum + array[i];
    }
    return sum;
}


int main() {
    int array[] = {9, 4, 7, 8, 10, 5, 1, 6, 3, 2};
    int len = 10;
    printf ("Sum: %d\n" , sum(array, len)); 
}

Output: Sum: 55

however, now I need to do the very same thing but differently. The Sum function should take 3 arguments, third one being a Pointer, return no value and still be able to call it in the main function to print out the sum again. Any help would be appreciated.

P.S. Yes, it is part of homework.

Matthieu Brucher
  • 21,634
  • 7
  • 38
  • 62
Leonardo
  • 160
  • 2
  • 3
  • 13

1 Answers1

4

The pointer will point to the integer variable that will receive the sum:

void sum (int array[], int len, int *result)

You call it from main giving a pointer to the result. I give no more; the rest is your homework.

Paul Ogilvie
  • 25,048
  • 4
  • 23
  • 41
  • 1
    I changed `int sum(..` to `void sum(..` as sum no longer returns a value. – Paul Ogilvie Oct 22 '18 at 16:53
  • if you define**int result;** in main, and send the function **sum(array, len, &result)**, then all changes you do to result will be saved on the var result in main. print him out after calling your function and if you de-reference it right in your sum function you should be good. remember ! in your sum function to init[*result = 0;] and the use it like so :[*result+= arr[i];] to update its value. when handling pointers in functions its always a good practice to check they are not NULL prior to de-referenceing them – H.cohen Oct 22 '18 at 17:09
  • @PaulOgilvie I don't know why everyone reacts so badly to assignment/homeworks. Im not asking anyone to do it for me. Your answer/direction was more than enough to finish it as requested. What difference would it make if it was a personal "project" ... People ask much simpler questions and get full answers too. Thanks for the answer, of course! – Leonardo Oct 22 '18 at 17:52
  • Dear @Leonardo, I do not want to react "bad" to homework. I just wanted to give you a hint. In order for you to learn, my idea was that you lookup what was still needed to complete your assignment. Doing it yourself, including the looking up and trying, is the best way to learn. As you say, my hint was enough. – Paul Ogilvie Oct 22 '18 at 18:53
  • @H.cohen, if I write "I give no more; the rest is your homework" it means I do not appreciate someone giving the full answer and so preventing the OP to learn by finding out himself. – Paul Ogilvie Oct 22 '18 at 18:54
  • Dear @PaulOgilvie, didn't mean to over step -just thought to add a few pointers instead of posting a new, full answer of my own, apologies. – H.cohen Oct 23 '18 at 06:16