Factorial from 0 to 20 using For

Asked

Viewed 444 times

1

I need to do the following exercise: "Using the for loop, calculate and print the factorial of all numbers between 0 and 20. Use Double type. Ex: 0! =1 1! =1 2! = 2 ... 20! = 2432902008176640000" But I can’t identify the mistake I’m making. Someone has an idea?

#include <stdio.h>

int main(){
    int cc, cf, acc;
    double fat;

    for(cc=0; cc<=20; cc++){
        if(cc==0) fat=1;
        else{
            for(cf=0;cf<cc;cf++){

                fat = fat * cf;
                acc = acc + fat;
            }
        }
        printf("%d! = %.1lf\n",cc+1 , fat);
    }
}

3 answers

3


(1) You are adding "int" to "double":

acc = acc + fat;

The problem is that high factorial values fit in double, but do not fit in int. By the way, you’re not even using the variable "acc" for anything...

(2) You are not initiating the variable "acc":

  int cc, cf, acc;

That is, even ignoring that acc should be double, and that you are not using acc for anything, your acc accounts result in undefined value, because acc has not been initialized.

(3) Your logic is inefficient and confusing:

for (cc = 0; cc <= 20; cc++)
{
  if (cc == 0) // <------- INEFICIENTE, está repetindo a mesma comparação
    fat = 1;   // <------- 21 vezes, sendo que só 1 vez ela vai ser verdadeira
  else
  {
    for (cf = 0; cf < cc; cf++) // <---- CONFUSO: por que este segundo loop ???
    {
      fat = fat * cf;
      acc = acc + fat;
    }
  }

(4) Your program is not documented. You didn’t even post a comment explaining its logic.

Below, a simplified version of the program.

#include <stdio.h>

int main()
{
  int cc;
  double fat = 1;

  // caso especial: 0! = 1
  printf("* 0! = 1\n");

  // caso geral: n! = 1 * 2 * .. * n
  for (cc = 1; cc <= 20; cc++)
  {
    fat *= cc;
    printf("* %d! = %.0lf\n", cc , fat);
  } // for

  return 0;
}

Testing:

$ 380272.exe                      
* 0! = 1                          
* 1! = 1                          
* 2! = 2                          
* 3! = 6                          
* 4! = 24                         
* 5! = 120                        
* 6! = 720                        
* 7! = 5040                       
* 8! = 40320                      
* 9! = 362880                     
* 10! = 3628800                   
* 11! = 39916800                  
* 12! = 479001600                 
* 13! = 6227020800                
* 14! = 87178291200               
* 15! = 1307674368000             
* 16! = 20922789888000            
* 17! = 355687428096000           
* 18! = 6402373705728000          
* 19! = 121645100408832000        
* 20! = 2432902008176640000       
$                                 

2

Hello, all right?

You can do it in C as follows:

#include <stdio.h>

int main()
{
   double fat;
   int n;
   printf("Insira um valor para o qual deseja calcular seu fatorial: ");
   scanf("%d", &n);

   for(fat = 1; n > 1; n = n - 1)
     fat = fat * n;

   printf("\nFatorial calculado: %lf", fat);
   return 0;
}

2

I would make some structural and logical changes to your code:

#include <stdio.h>

int main() {
  int cc, cf, acc;
  long fat; // <1>

  for (cc = 0; cc <= 20; cc++) {
    fat = 1; // <2>
    if (cc == 0) fat = 1;
    else {
      for (cf = 1; cf <= cc; cf++) { // <3>
        fat *= cf; // <4>
      }
    }
    printf("%d! = %ld\n", cc, fat); // <5>
  }
}

<1> First I would change the type of the variable to long, which is far superior to that of a simple int, and taking into account that there is no multiplication of integer numbers resulting in decimal places, I see no problem in displaying as integer.

╔════════╦══════════════╦══════════════════════╦════════════╗
║ Type   ║ Storage size ║ Value range          ║ Precision  ║
╠════════╬══════════════╬══════════════════════╬════════════╣
║ float  ║ 4 byte       ║ 1.2E-38 to 3.4E+38   ║ 6 decimal  ║
║ double ║ 8 byte       ║ 2.3E-308 to 1.7E+308 ║ 15 decimal ║
╚════════╩══════════════╩══════════════════════╩════════════╝

<2> Each iteration of the second is required to reset the variable.

<3> The second for is necessary to start from 1 to not exist the first multiplication by 0 that Zera the final result, in fact this is where is the logical problem of your code.

<4> Summarize the mathematical operation.

<5> The printf I would display using %ld which in other words can be read as long double.


The final result can be seen on any compiler C online:

0! = 1
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720
7! = 5040
8! = 40320
9! = 362880
10! = 3628800
11! = 39916800
12! = 479001600
13! = 6227020800
14! = 87178291200
15! = 1307674368000
16! = 20922789888000
17! = 355687428096000
18! = 6402373705728000
19! = 121645100408832000
20! = 2432902008176640000

Browser other questions tagged

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