Factorial with recursion

Asked

Viewed 698 times

2

I have to make a program that calculates the factorial of a number using recursiveness within 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 argument at the command prompt an error occurs, saying that the program has stopped working. What’s wrong with my code?

  • Taking advantage, take a look at [tour] just to know the model of the site, and in [Ask] have some tips on how to better elaborate the next questions you ask, to increase the chance of solution. Here you go some tips to format the code if you need to.

  • Why recursion needs to be done with main?

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 is easier for Oce, using the 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 again the main function too.

I hope I’ve helped!

  • 1

    I would suggest using the unsigned int only.

  • Yes, it would be a cool optimization :P Good idea, I used int by 'simplicity' same

0

Presenting 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;
}
  • In the problem it specifies that it needs the method to be recursive.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.