Question

The assignment was to create a program that computes the Ackermann equation using recursion, which I successfully did. Part of the assignment says:

"The function should print the number of recursive function calls which are multiple of k. Set k = 100 for values of n; m <= 3, and k = 1; 000; 000 for all other values. Your program should also print the total number of function calls made."

The ackermann function is supposed to print out the number of function calls and recursive functions calls, but I can't figure out how to do it. Any help would be great. Thanks!

This is what I have so far:

#include <stdio.h>

//function to compute the end result ackermann equation
int ackermann (int n, int m)
{
    int result = 0;

    if (n == 0)
    {
        result = m + 1;

    } else if (m == 0)
    {
        result = ackermann(n - 1, 1);

    } else
    {
        result = ackermann(n - 1, ackermann(n, m - 1));
    }

    return result;
}

//main function
int main(int argc, const char * argv[])
{
    char ans = 'y';
    int m, n, result;

    printf("\n\n------Ackermann Function------");

    while (ans == 'Y' || ans == 'y') {
        printf("\nPlease enter n: ");
        scanf("%d", &n);

        printf("\nPlease enter m: ");
        scanf("%d", &m);

        result = ackermann(n, m);

        printf("\nResult: %d", result);

        printf("\n\nDo you want to go again? ");
        scanf(" %c", &ans);
    }

    return 0;
}
Was it helpful?

Solution

static int count = 0;

int func() 
{
  count ++
  // do your work
  // recursive call
}

Make static variable which will keep the total number of calls made to functions.

And in this case you don't have to make count as global making it local static into function is enough because static variable retains it's value as static has file scope.

OTHER TIPS

Use a global variable, incrementing its value on each call:

int calls_count = 0;

...

int ackermann (int n, int m)
{
    ++calls_count;
...
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top