MCQModerate1 mark
1
Choose the correct answers to the questions from the given options. (Do not copy the questions, write only the correct answers.)
Consider the following program segment in which the statements are jumbled. Choose the correct order of statements to calculate and return the factorial of 4. 1. for(k = 1; k <= 4; k++) 2. return fa; 3. long fa = 1, k; 4. fa *= k;
Topic: Jumbled program statements
Previous-year question practice database
Try it
Pick an option and check your answer. The full worked answer is below either way.
Answer
Exam answer
(b) 3, 1, 4, 2.
Explanation
Reason it out in the order a program must run. Variables have to be declared and initialised before use, so statement 3 comes first — and note fa starts at 1, not 0, because it is a product. Then the loop header (1), then the body that multiplies (4), and finally the return (2) once the loop has finished. Any order returning before the loop ends, or using fa before declaring it, cannot compile.
In words
3, 1, 4, 2.
More from User-Defined Methods
In the following method prototype to accept a character, an integer and return YES or NO, fill in the blank to complete the method prototype.
public __________ someMethod(char ch, int n)2026In a calculator which Java feature allows multiple methods named calculate() for the different operations?2026The 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.2026Define a class to overload the method format as follows:
void format() - To print the following pattern using Nested for loops only:
1 2 3 4 5
2 3 4 5
3 4 5
4 5
5
int format(String s) - To calculate and return the sum of ASCII codes of each character of the String.
Example: CAB
Output: 67 + 65 + 66 = 198
void format(int n) - To calculate and display the sum of natural numbers up to n given by the formula n(n + 1) / 2.2026Which of the following pairs of methods will cause a compile-time error due to incorrect method overloading?2025John was asked to write a Java code to calculate the surface area of a cone. The following code was written by him:
Surface area of cone is A = pi * r * l, where l = sqrt(r^2 + h^2)
class area
{
double area(double r, double h)
{
double l, a;
a = 22.0 / 7 * r * l;
l = Math.sqrt(r * r + h * h);
return a;
}
}
Specify the type of the error in the above program, correct and write the program to be error free.2025