Factorial from 0 to 20 using For

I need to do the following exercise: "Using the For loop, calculate and print on screen the factorial of all numbers between 0 and 20. Use the Double type. Ex: 0! =1 1! =1 2! = 2 ... 20! = 2432902008176640000" But I can't identify the mistake I'm making. Anyone have 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);
    }
}
Author: Icaro Martins, 2019-04-30

3 answers

(1) you are adding " int "with " double":

acc = acc + fat;

The problem is that high factorial values fit in double, but don't fit in int. Incidentally, you're not even using the "acc" variable for anything...

(2) you are not initializing 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 accounts with acc 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 put a single comment explaining your 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;
}

Heads:

$ 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       
$                                 
 3
Author: zentrunix, 2019-04-30 11:12:28

Hello, All right?

You can do 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
Author: MaatheusGois, 2019-04-30 04:09:28

I would make some structural and logic 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>
  }
}

First that I would change the type of the variable to long, which is much higher than that of a simple int, and taking into account that there is no multiplication of integers with result with 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 ║
╚════════╩══════════════╩══════════════════════╩════════════╝

Each iteration of the second for it is necessary to zero the variable.

The second for it is necessary to start from 1 to no there is the first multiplication by 0 that zeros out the final result, actually here is the logical problem of your code.

Would summarize the mathematical operation.

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


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

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
Author: MarceloBoni, 2019-04-30 04:36:30