Search code examples
cfactorialcomparison-operators

Comparison operator in for loop (C language)


I'm trying to make basic factorial example program in C -language, but i can't understand why the following program does not function properly with == comparison operator, although it works completely fine with <= operator.

Non-functional version:

#include <stdio.h>

int main()
{

    int i, n, fact=1;

    printf("Enter a number:");
    scanf("%d", &n);

    for(i=1; i==n; i++)
        {
            fact=fact*i;
        }

        printf("Factorial of %d is %d", n, fact);

    return 0;

}

Functional version:

#include <stdio.h>

int main()
{

    int i, n, fact=1;

    printf("Enter a number:");
    scanf("%d", &n);

    for(i=1; i<=n; i++)
        {
            fact=fact*i;
        }

        printf("Factorial of %d is %d", n, fact);

    return 0;

}

Thanks already in advance!


Solution

  • The condition in the for loop is a while condition:

    int i = 1;
    while(i == n)
    {
       //loopbody
       fact=fact*i;
       i++;
    }
    

    So it will only do anything when n==1, plus the loop can only run 0 or 1 times.