> For the complete documentation index, see [llms.txt](https://42-guide.gitbook.io/42-guide/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://42-guide.gitbook.io/42-guide/piscine-life/c05/ft_iterative_factorial.md).

# ft\_iterative\_factorial

**Objective:**

Create an **iterative function** that calculates the factorial of a given number. The function should return **0** if the input is invalid (i.e., negative numbers).

**Turn-in Directory:**

ex00/

**Files to Turn In:**

ft\_iterative\_factorial.c

**Allowed Functions:**

None

**Prototype:**

```c
int ft_iterative_factorial(int nb);
```

***

#### **Detailed Explanation**

The **ft\_iterative\_factorial** function calculates the factorial of a given number `nb` using iteration. The factorial of a number `n` is defined as the product of all positive integers less than or equal to `n`. For example:

* Factorial of 5: `5! = 5 * 4 * 3 * 2 * 1 = 120`
* Factorial of 0: `0! = 1`

The function returns:

* The factorial of `nb` if `nb` is a non-negative integer.
* **0** if `nb` is negative (invalid input).

***

#### **Code Implementation**

```c
int ft_iterative_factorial(int nb)
{
    int result;

    result = 1;
    if (nb < 0)  // Handle invalid input (negative numbers)
        return (0);
    if (nb <= 1)  // Base case: factorial of 0 or 1 is 1
        return (1);
    while (nb > 0)  // Iterative calculation of factorial
    {
        result *= nb;
        --nb;
    }
    return (result);
}
```

***

#### **Example Usage**

```c
#include <stdio.h>

int ft_iterative_factorial(int nb);

int main(void)
{
    printf("Factorial of 5: %d\n", ft_iterative_factorial(5));  // Output: 120
    printf("Factorial of 0: %d\n", ft_iterative_factorial(0));  // Output: 1
    printf("Factorial of -3: %d\n", ft_iterative_factorial(-3)); // Output: 0
    printf("Factorial of 10: %d\n", ft_iterative_factorial(10)); // Output: 3628800

    return 0;
}
```

***

#### **Edge Cases to Consider**

1. **Negative Numbers**:
   * Input: `-3` → Returns **0** (invalid input).
2. **Zero**:
   * Input: `0` → Returns **1** (by definition, `0! = 1`).
3. **Positive Numbers**:
   * Input: `5` → Returns **120** (`5! = 120`).
4. **Large Numbers**:
   * Input: `10` → Returns **3628800** (`10! = 3628800`).

***

#### **Limitations of ft\_iterative\_factorial**

1. **No Handling of Overflows**:
   * The function does not handle integer overflows. For large values of `nb`, the result may exceed the range of an `int`, leading to undefined behavior.
2. **Iterative Approach**:
   * While the iterative approach avoids recursion depth issues, it may still be inefficient for very large inputs due to the loop.

***

#### **How It Works**

1. **Initialization**:

   * The variable `result` is initialized to **1** to store the factorial value.

   ```c
   result = 1;
   ```
2. **Invalid Input Check**:

   * If `nb` is negative, the function immediately returns **0**.

   ```c
   if (nb < 0)
       return (0);
   ```
3. **Base Case Check**:

   * If `nb` is **0** or **1**, the function returns **1** because the factorial of 0 and 1 is 1.

   ```c
   if (nb <= 1)
       return (1);
   ```
4. **Iterative Calculation**:

   * The `while` loop multiplies `result` by `nb` and decrements `nb` until `nb` becomes **0**.

   ```c
   while (nb > 0)
   {
       result *= nb;
       --nb;
   }
   ```
5. **Return the Result**:

   * Once the loop ends, the function returns the value of `result`, which is the factorial of `nb`.

   ```c
   return (result);
   ```

***

#### **Key Points to Remember**

1. **Iterative Approach**:
   * The function uses a `while` loop to calculate the factorial, avoiding recursion.
2. **Base Cases**:
   * The base cases handle edge cases like `0` and negative numbers.
3. **Efficiency**:
   * The time complexity is **O(n)**, where `n` is the value of `nb`. Each iteration reduces `nb` by 1 until it reaches **0**.

#### **Best Practices**

1. **Input Validation**:
   * Always check for invalid inputs (e.g., negative numbers) to avoid unexpected behavior.
2. **Edge Cases**:
   * Test edge cases like `0`, `1`, and negative numbers to ensure the function behaves as expected.
3. **Overflow Handling**:
   * Consider adding overflow handling for large inputs, though it is not required in this exercise.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://42-guide.gitbook.io/42-guide/piscine-life/c05/ft_iterative_factorial.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
