Optimize factorial calculation using vector

Asked

Viewed 821 times

4

Statement of the question:

Read an array A of vector type with 5 integer numerical elements. Construct a matrix B of the same type, each element of the matrix B being the factorial of the corresponding element of the matrix A. Display matrix elements 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;
}

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 switched the vet[i] = vet[i] - 1 for vet[i]--.

Testing with this input:

5
12
4
7
3

This output is produced:

120
479001600
24
5040
6

See here working on ideone.

  • Thank you very much, I have already marked with certain answer

  • @rafaelmarques Thanks. ;)

Browser other questions tagged

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