Doubts in a C exercise

Asked

Viewed 37 times

-1

I’m doing an exercise that asks:

Write an algorithm that receives a 10-element A array and get an arrangement F whose components are the factorial components of the respective components of V.

My code went like this, where did I go wrong? He’s not reading the factorial:

#include<stdio.h>

int main(){
    int vetorA[10],vetorfat[10];
    int i, fatorial;

    printf("Digite os valores do vetor A: \n");

    for(i=0; i<10; i++){
        scanf("%d",&vetorA[i]);
    }

    printf("O vetor fatorial dos respectivos componentes ficara: \n");

    for(i=0; i<10; i++){
        for(fatorial = 1; vetorA[i] > 1; vetorA[i] = vetorA[i] -1){
    
            fatorial = fatorial*vetorA[i];
            vetorfat[i] = vetorfat[fatorial];
    
            printf("%d ", vetorfat[fatorial]);
    
       }
   }

   return 0;
}

1 answer

1

There are two problems: they are the access to the vector index vetorfat and the printf that will display more numbers than you want to be inside the second loop of repetition, responsible for only calculating factor numbers.

The problem of not being able to see the calculated numbers is that you try to access the index with the variable value fatorial:

vetorfat[i] = vetorfat[fatorial];

The vector vetorfat does not have as many items as you initially stated. That is, the moment a calculated factorial number becomes greater than 9 (nine), there is no way to access an index greater than the value "predetermined items - 1"; the program cannot access the requested memory region and results in the end of its execution.

Once this is fixed, you will notice that the numbers output will display many more items than there are in the array vetorA initial. This is because the printf is within the loop of repetition that should be responsible for only calculating the factorial of the current number:

    for(fatorial = 1; vetorA[i] > 1; vetorA[i] = vetorA[i] -1){

        // ...

        printf("%d ", vetorfat[fatorial]); 

   }

It is not necessary to have a vector vetorfat further, since it is only wanting to display the values of the initial vector. The internal loop where it calculates the factorial value would have only the calculation and the printf would be out of it, displaying only the variable value fatorial:

for (fatorial = 1; vetorA[i] > 1; vetorA[i] = vetorA[i] - 1) {
    fatorial = fatorial * vetorA[i];
}

printf("%d ", fatorial);

Using the above code, the output for values 1 to 10 would be:

O vetor fatorial dos respectivos componentes ficara:                    
1 2 6 24 120 720 5040 40320 362880 3628800 

Browser other questions tagged

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