Knowee
Questions
Features
Study Tools

write an iterative code for factorial in c

Question

write an iterative code for factorial in c

🧐 Not the exact question you are looking for?Go ask a question

Solution

Sure, here is a simple iterative code for calculating factorial in C:

#include <stdio.h>

long long factorial(int n) {
    long long fact = 1;
    for(int i = 1; i <= n; i++) {
        fact *= i;
    }
    return fact;
}

int main() {
    int num;
    printf("Enter a positive integer: ");
    scanf("%d",&num);
    if (num < 0)
        printf("Error! Factorial of a negative number doesn't exist.");
    else {
        printf("Factorial of %d = %lld", num, factorial(num));
    }
    return 0;
}

This program first takes an integer input from the user. Then it checks if the number is negative, if it is, it prints an error message. If it's not, it calculates the factorial using a for loop in the factorial function and then prints the result.

This problem has been solved

Similar Questions

Write a C program, using functions where the function calculates the factorial of a given integer, and the main() program does I/O and calling of factorial function.

c++ program on factorial of a number in short

Write a program to calculate the factorial of N.

Write a program that takes a positive integer as input and calculates its factorial using a for loop. The factorial of a number is the product of all positive integers up to that number.

Write a C++ program to find the factorial of a given integer using recursion.sample input and outputEnter a positive integer: 5 Factorial of 5 is: 120

1/3

Upgrade your grade with Knowee

Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.