Skip to content
Advertisement

Recursion using main() function [closed]

I am writing a program to calculate factorial using recursion of main() function.

/* Print factorial */
#include <stdio.h>
#include <stdlib.h>

static char **p;

int main(int argc, char **argv)
{
        int n, rv;
        if (argc < 2) {
                printf("Usage: a.out <value>n");
                exit(-1);
        }
        n = atoi(argv[1]);
        if (!n) {
                rv = 0;
        } else {
                if (n == 1) {
                        rv = 1;
                } else {
                        n = n - 1;
                        **p = n;
                        main(2, p);
                }
        }
        printf("%dn", rv);
        return 0;
}

The program compiles using gcc but on execution, I am getting a Segmentation Fault at **p = n. Can somebody help me to modify the above program to get the correct result. Also, what is the logic to capture correct rv value between successive recursive calls in main()?

Advertisement

Answer

Since you don’t seem to care about standard and stuffs, here is an implementation of the recursive main function for printing factorial, that compiles on gcc (I only test on Windows). Since it doesn’t follow standard, there is no guarantee that it will compiles on other compiler/platform.

Writing such code for fun is OK, but never let the bad behavior follows into serious coding project or workplace.

/* Print factorial */
#include <stdio.h>
#include <stdlib.h>

char buf[16];

int main(int argc, char **argv)
{
        int n, rv;

        if (argc < 2) {
                printf("Usage: a.out <value>n");
                exit(-1);
        }

        n = atoi(argv[1]);
        if (!n) {
                rv = 1;
        } else {
                if (n == 1) {
                    rv = 1;
                } else {
                    char *pt = buf;
                    char **pt2 = &pt - 1;

                    sprintf(buf, "%d", n - 1);
                    rv = main(2, pt2) * n;
                }
        }
        printf("%dn", rv);

        return rv;
}
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement