Advertisements
Advertisements
Question
Observe the following code. It may contain Syntax, Logical or runtime errors. Execute it in Java and identify the error, if any. Rewrite the code without the error. Also write the aim of the code.
import java.util.*;
public class cl Factorial
{
void fn Factorial(int num)
{
for(int k = 1; k <= num; k++)
f = f*k;
}
public void main()
{
int number = 0;
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number:");
number = sc.nextInt();
int cpy = number, dg = 0, facdg = 0;
while(cpy > 0)
{
dg = cpy % 10;
facdg = factorial(dg);
System.out.println("Factorial of "+dg+"="+facdg);
}
}
}Code Writing
Advertisements
Solution
import java.util.*;
public class Factorial
{
int fnFactorial(int num)
{
int f = 1;
for(int k = 1; k <= num; k++)
{
f = f * k;
}
return f;
}
public static void main(String[] args)
{
int number = 0;
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number:");
number = sc.nextInt();
int cpy = number, dg = 0, facdg = 0;
Factorial obj = new Factorial();
while(cpy>0)
{
dg = cpy% 0;
facdg = obj.fnFactorial(dg);
System.out.println("Factorial of" + dg + "=" + facdg);
cpy = cpy/10;
}
}
}
shaalaa.com
Is there an error in this question or solution?
Chapter 3: User-Defined Methods - Exercises [Page 93]
