Search code examples
cfactorial

Why is this showing up as 82 when executed? For Loop - Factorial


The first code comes out as 82 for the 1! factorial... any reason why? It really doesn't make any sense to me, considering that the do loop works perfectly fine. If you run the program, you will see a table giving all the answers to the factorials. The do loop is okay what I have to do, but I can't use it.

Any idea why the for loop isn't working properly?

#include <stdio.h>                                     /* Necessary header */
#define LAST_NUMBER 25                                 /* Macro preset to avoid magic numbers */

int main(void)                                         /* Start executive method */
{
    int Nbr;
    signed long total = Nbr;

    printf("Nbr               Nbr!");                  /* Table Headers */
    printf("\n----------------------");

    for (Nbr = 1; Nbr<=LAST_NUMBER;)              /* Loop statement begins */
    {
        total *= Nbr;
        printf("\n%2d   %15ld", Nbr, total);
                Nbr++;
                                        /* Prints both columns for table */
    }                       /* Loop ends when predefined number is reached */

    return 0;
}                                                      /* End main method */

/* The following code works fine */

#include <stdio.h>                                     /* Necessary header */
#define LAST_NUMBER 25                                 /* Macro preset to avoid magic numbers */

int main(void)                                         /* Start executive method */
{
    int Nbr = 1;
    signed long total = Nbr;

    printf("Nbr               Nbr!");                  /* Table Headers */
    printf("\n----------------------");

    do                                                 /* Loop statement begins */
    {
        total *= Nbr;
        printf("\n%2d   %15ld", Nbr, total);            /* Prints both columns for table */
        Nbr++;
    }while (Nbr<=LAST_NUMBER);                         /* Loop ends when predefined number is reached */

    return 0;
}                                                      /* End main method */

Solution

  • int Nbr;
    signed long total = Nbr;
    

    You must initialize variables before using them.