English

The following program segment calculates and displays the factorial of a number. [Example: Factorial of 5 is 1 x 2 x 3 x 4 x 5 = 120] int p, n = 5, f=0; for (p = n; p>0; p--) f*=p; System - Computer Applications

Advertisements
Advertisements

Question

The following program segment calculates and displays the factorial of a number. [Example: Factorial of 5 is 1 x 2 x 3 x 4 x 5 = 120]

   int p, n = 5, f=0; 
   for (p = n; p>0; p--)
   f*=p;
   System.out.println(f);

Name the type of error if any; correct the statement to get the desired output.

Long Answer
Advertisements

Solution

int p, n = 5, f = 1;
  • The program segment has a logical error.
  • Type of Error: Logical Error.
  • The variable f is initialised to 0. Since any number multiplied by zero is zero, the calculation f *= p will always result in 0. To calculate a factorial, the initial value of the product variable must be 1.
  • To get the desired output, change the initialisation of f from 0 to 1.
 
shaalaa.com
  Is there an error in this question or solution?
2025-2026 (March) Official Board Paper
Share
Notifications

Englishहिंदीमराठी


      Forgot password?
Use app×