Computer Applications
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.
Java Iterative Stmts
3 Likes
Answer
The logical error occurs because the factorial variable f is initialized to 0. Since multiplication with 0 always results in 0, the loop will never produce the correct factorial value.
The corrected code is as follows:
int p, n = 5, f = 1;
for(p = n; p > 0; p--)
f *= p;
System.out.println(f);
Answered By
2 Likes
Related Questions
Give the output of the following program segment:
String S = "GRACIOUS".substring(4); System.out.println(S); System.out.println("GLAMOROUS".endsWith(S));Give the output of the following program segment and mention how many times the loop is executed.
int K = 1; do {K += 2; System.out.println(K); } while (K <= 6);int X[][] = {{4, 5}, {7, 2}, {19, 4}, {7, 4}};
Write the index of the maximum element and the index of the minimum element of the array.
The following program segment swaps the first element and the second element of the given array without using the third variable, fill in the blanks with appropriate java statements:
void swap() { int x[] = {4, 8, 19, 24, 15}; (1) ............... ; (2) ............... ; x[0] = x[0] / x[1]; System.out.println(x[0] + " " + x[1]); }