factorization with loops

1

I am writing the book 6º edition of C as a program of the Deitel brothers and I am in doubt in an exercise, the exercise is 4.14 of chapter 4 that is about factorization, it asks a program that the user type a number and that number is factored, for example if the user types the number 5, the program will make 5 * 4 * 3 * 2 * 1 resulting in 120. If someone can give me some hint and no answer I will be very grateful thank you:

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

int main()
{
    int i, num, aux1=0, fat=0, aux=0;

    printf("digite um numero para ser fatorado:\n");
    scanf("%i", &num);
    printf("\nvamos fatorar entao o numero %i:\n\n", num);

    for(i=num;i>=1;i--)
    {
        aux=i;
        fat=aux*i;
        printf("%i! ", fat);
    }
    return 0;
}
    
asked by anonymous 02.07.2014 / 20:12

2 answers

1

Notice what you are doing:

Suppose num = 5;

   for(i=num;i>=1;i--)
    {
        aux=i;
        fat=aux*i;
        printf("\n%d ", fat);
    }

Take the bench test:

i=5         |    i=4            |  ...
aux=5       |   aux=4           |
fat=5*5???  |  fat=4*4          |

What you're looking for is this:

i=5         |    i=4            |  ...
aux=5       |   aux=fat   (5)   |
fat=5       |  fat=aux*i (5*4)  |

Note that there are several unnecessary variables and do not forget: 0! = 1 .

Tip: You do not need the aux variable, much less the aux1 you have not even used.

    
03.07.2014 / 00:59
1

My tips:

  • What is the factorial of 0? This would be a better value for initializing fat, since you would print the correct answer if the loop did not run once.

  • Notice how the final result of fat depends only on the last value of aux , which depends only on the last value of i . I think that's not why you created fat ...

  • I prefer to iterate from 1 to N instead of N to 1. This makes it easier to write an invariant to the value of fat . If you do not want to think about the invariant then it obviously does)

  • Tip C:

    You can declare deposition variables of any { . It does not have to be all at the top of the function:

    {int i; for(i=n; i >= 1; i--){
       int aux = /* ... */
    }}
    

    In addition, if you are not using Visual Studio, you can compile your program using the C99 standard that allows you to declare variables in the middle of the

    int num;
    scanf("%d", &num);
    
    for(int i=n; i >= 1; i--);
    
        
    02.07.2014 / 20:49