Question:

The following program segment calculates and displays the factorial of a number. [Example: Factorial of 5 is \(1 \times 2 \times 3 \times 4 \times 5 = 120\)]
\texttt{int P, n = 5, f = 0;}
\texttt{for (P = n; P>0; P--)}
\texttt{\{}
\texttt{\ \ \ \ f *= P;}
\texttt{\}}
\texttt{System.out.println(f);}

Show Hint

Whenever repeated multiplication is needed, initialize the result variable with \(1\), because multiplying by \(0\) always gives \(0\).
Hide Solution
collegedunia
Verified By Collegedunia

Solution and Explanation

Step 1: Recall how factorial is calculated.
The factorial of a number is obtained by multiplying all positive integers from that number down to \(1\). For example,
\[ 5! = 5 \times 4 \times 3 \times 2 \times 1 = 120 \] Step 2: Identify the mistake in the given program.
In the given code, the variable \texttt{f} is initialized as \texttt{0}. Then the statement \texttt{f *= P} means:
\[ f = f \times P \] Since \(f\) starts with \(0\), every multiplication will remain \(0\). Therefore, the program will not calculate the factorial correctly.
Step 3: Write the correct initialization.
To calculate factorial, the multiplication should start from \(1\), not \(0\). So the correct initialization is:
\texttt{int P, n = 5, f = 1;}
Step 4: Trace the corrected program.
Now the loop works as follows:
\[ f = 1 \times 5 = 5 \] \[ f = 5 \times 4 = 20 \] \[ f = 20 \times 3 = 60 \] \[ f = 60 \times 2 = 120 \] \[ f = 120 \times 1 = 120 \] Step 5: Write the corrected program and answer.
The corrected program is:
\texttt{int P, n = 5, f = 1;}
\texttt{for (P = n; P>0; P--)}
\texttt{\{}
\texttt{\ \ \ \ f *= P;}
\texttt{\}}
\texttt{System.out.println(f);}
So, the output will be:
\[ \boxed{120} \]
Was this answer helpful?
0
0

Questions Asked in ICSE Class X board exam

View More Questions