What will be the output? int n = 5, factorial = 1; for(int i = n; i > 1; i--) { factorial *= i; } printf("%d", factorial);

Question image

Understand the Problem

The question is asking for the output of a given C program that calculates the factorial of the number 5 using a loop. We need to determine the final value of 'factorial' after the loop executes.

Answer

$120$
Answer for screen readers

The final answer is $120$.

Steps to Solve

  1. Initialize Variables We start with two variables:
  • $n = 5$
  • $factorial = 1$.
  1. Set Up the Loop The for-loop is initiated with for(int i = n; i > 1; i--). This means the loop begins with $i = 5$ and will continue until $i$ is greater than 1.

  2. Calculate Factorial In each iteration of the loop, we multiply factorial by $i$:

  • Iteration 1: $i = 5$, so $factorial = factorial \times 5 = 1 \times 5 = 5$.
  • Iteration 2: $i = 4$, so $factorial = factorial \times 4 = 5 \times 4 = 20$.
  • Iteration 3: $i = 3$, so $factorial = factorial \times 3 = 20 \times 3 = 60$.
  • Iteration 4: $i = 2$, so $factorial = factorial \times 2 = 60 \times 2 = 120$.

At the end of the loop, $factorial$ will hold the value of 120.

  1. Print the Result Finally, we print the value of factorial which now equals $120$.

The final answer is $120$.

More Information

This program calculates the factorial of 5, which is the product of all positive integers up to that number. The factorial of 5 is commonly denoted as $5!$ and is equal to $5 \times 4 \times 3 \times 2 \times 1 = 120$.

Tips

  • Incorrect Loop Logic: Some might mistakenly set the loop to go from $1$ to $n$, which would not correctly calculate the factorial.
  • Starting Factorial Value: Forgetting to initialize factorial to $1$ can lead to incorrect results, as any number multiplied by $0$ is $0$.

AI-generated content may contain errors. Please verify critical information

Thank you for voting!
Use Quizgecko on...
Browser
Browser