Factorial with recursion

1

I have to do a program that calculates the factorial of a number using recursion inside the main.

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

int main (int argc, char *argv[]){
    float numero;
    int valorA = atoi(argv[1]);
    char var1[10];
    itoa(valorA-1, var1, 10);
    if (valorA <= 1)
        return(1);
    else{
        numero = valorA * main(argc, var1);
        return numero;
    }




    printf("Fatorial de %d = %.2f", atoi(argv[1]), numero);
}

When I pass the number as an argument at the command prompt an error occurs, saying that the program has stopped working. What is the problem with my code?

    
asked by anonymous 18.11.2016 / 22:28

2 answers

1

I used a different strategy to get the number, but as your example does not have the factorial itself, maybe this form will be easier for you, using scanf:

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

int genFatorial(int n) {
    if(n) {
        return n * genFatorial(n - 1);
    } else {
        return 1;
    }
}

int main() {
    int num;
    scanf("%d", &num);

    int fatorial = genFatorial(num);
    printf("%d\n", fatorial);

    return 0;
}

This is a very simple solution to this problem, I suggest you use an auxiliary function instead of calling the main function again.

I hope I have helped!

    
19.11.2016 / 00:07
0

Introducing another solution to the problem:

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

int fat (int n)
{
  int res = 1;

  while (n > 1) {
    res = res * n;
    n--;
  }

return res;
}

int main () 
{
  unsigned int n;

  printf("Entre com o valor de n: ");
  scanf("%d", &n);
  printf("Fatorial de %d = %d\n", n, fat(n) );

  system("pause");
  return 0;
}
    
19.11.2016 / 00:25