Optimize factorial calculation using vector

4

Issue statement:

  

Read an array A of the vector type with 5 integer numeric elements.   Construct a matrix B of the same type, each element of matrix B being the factorial of the corresponding element of matrix A.   Display the elements of matrix B.

I was able to do it, but I wanted to know how to improve my algorithm.

#include <stdio.h>
#include <stdlib.h>
int main(int argc, char** argv)
{
   int vet[5], i, fat, fat2, fat3, fat4, fat5;
   for(i = 0; i < 5; i++)
   {
     printf("Digite um numero :\n");
     scanf("%d", &vet[i]);
   }
   for(fat = 1; vet[0] > 1; vet[0] = vet[0] - 1)
   {
     fat *= vet[0];
   }
   for(fat2 = 1; vet[1] > 1; vet[1] = vet[1] - 1)
   {
      fat2 *= vet[1];
   }
   for(fat3 = 1; vet[2] > 1; vet[2] = vet[2] - 1)
   {
     fat3 *= vet[2];
   }
   for(fat4 = 1; vet[3] > 1; vet[3] = vet[3] - 1)
   {
     fat4 *= vet[3];
   }
   for(fat5 = 1; vet[4] > 1; vet[4] = vet[4] - 1)
   {
     fat5 *= vet[4];
   }
     printf("%d\n", fat);
     printf("%d\n", fat2);
     printf("%d\n", fat3);
     printf("%d\n", fat4);
     printf("%d\n", fat5);
  system("pause");
  return 0;
}
    
asked by anonymous 10.12.2017 / 20:43

1 answer

3

This is easily solved by putting a for inside the other:

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

int main(int argc, char** argv) {
    int vet[5], fat[5], i;
    for (i = 0; i < 5; i++) {
        printf("Digite um numero:\n");
        scanf("%d", &vet[i]);
    }
    for (i = 0; i < 5; i++) {
        for (fat[i] = 1; vet[i] > 1; vet[i]--) {
            fat[i] *= vet[i];
        }
        printf("%d\n", fat[i]);
    }
    //system("pause");
    return 0;
}

I also changed vet[i] = vet[i] - 1 to vet[i]-- .

Testing with this entry:

5
12
4
7
3

This output is produced:

120
479001600
24
5040
6

See here working on ideone.

    
10.12.2017 / 20:52