1

I have a function that calculates geometric mean (nth root of product of terms, where n is number of terms), and the only thing I'm having trouble with is figuring out how to keep track of how many terms there were. The only thing I could come up with was a global variable, but I know I shouldn't do that. How can I do it without the global variable?

float count;
float geometricMean(float n) {
    char again; 
    float j;
    printf("Input a number:  ");
    scanf("%f", &j);
    printf("Another number? (y/n)  ");
    scanf(" %c", &again);
    if (again == 'y') {
        j *= geometricMean(n+1);
        if (n==1)
            return pow(j, (1/count));
        else {
            return j;
        }
    }
    else {
        count = n;
        return j;
    }
}
cclloyd
  • 8,171
  • 16
  • 57
  • 104
  • this is for Java but can be achived in C with pointers and structs: http://stackoverflow.com/questions/13075456/returning-multiple-values-from-a-recursive-function – Rotem Varon Oct 22 '14 at 16:46
  • possible duplicate of [Pass by reference through multiple functions](http://stackoverflow.com/questions/717614/pass-by-reference-through-multiple-functions) – 2501 Oct 22 '14 at 17:25

1 Answers1

4

Use a static variable. Static variables don't change between function calls. At the start of your function, write something like:

float geometricMean(float n) {
    static int count = 0;
    count ++;
    // Rest of the code;
}

Each time you call your function, count will increase by 1 (it won't go back to 0).

Go here: What does "static" mean? if you want to know more about static variables.

EDIT: Please don't go out using static variables just like if it was a global, just with a smaller scope. It will lead to undesired results! If you're planning to change the value of a static variable in each iteration of your function, like I did here, please make you sure you make crystal clear what those alterations are and use them right after defining your static if possible.

Community
  • 1
  • 1
SlySherZ
  • 1,631
  • 1
  • 16
  • 25
  • 1
    It seems to me that a static is almost as bad as a global. The only benefit is that it doesn't pollute the global namespace. I would prefer the deleted answer which recommended passing in a pointer to a counter. – Dark Falcon Oct 22 '14 at 17:06