Define a class to overload the method perform as follows: double perform(double r, double h) - to calculate and return the value of Curved surface area of cone, CSA = pi * r * l void perform(int r, int c) - Use NESTED FOR LOOP to generate the following format. For r = 4, c = 5 the output is: 12345 12345 12345 12345 void perform(int m, int n, char ch) - to print the quotient of the division of m and n if ch is Q, else print the remainder of the division of m and n if ch is R
Topic: Method overloading — three versions of perform()
Answer
class Perform { double perform(double r, double h) { double l = Math.sqrt(r * r + h * h); double csa = Math.PI * r * l; return csa; }
void perform(int r, int c) { for(int i = 1; i <= r; i++) { for(int j = 1; j <= c; j++) System.out.print(j); System.out.println(); } }
void perform(int m, int n, char ch) { if(ch == 'Q') System.out.println("Quotient = " + (m / n)); else if(ch == 'R') System.out.println("Remainder = " + (m % n)); else System.out.println("Invalid character"); }
public static void main(String args[]) { Perform ob = new Perform(); System.out.println("CSA of cone = " + ob.perform(3.0, 4.0)); ob.perform(4, 5); ob.perform(17, 5, 'Q'); ob.perform(17, 5, 'R'); } }
Three methods named perform(), distinguished by their parameter lists: (double, double), (int, int) and (int, int, char). Note that the second and third differ only by the extra char — that is enough for valid overloading.
First method: the formula needs the slant height l, which is not given — compute it first with Pythagoras, l = sqrt(r^2 + h^2), and only then apply CSA = pi * r * l. Use Math.PI rather than 3.14 or 22.0/7 for accuracy. Order matters: computing csa before l is the classic logical error.
Second method: r rows and c columns, and every row prints 1 to c, so the inner loop always starts at 1 and the printed value is simply j. Use print() inside and println() after the inner loop to break the line.
Third method: / gives the quotient and % the remainder when both operands are ints. Compare the char with single quotes ('Q'), and include a final else so an unexpected character is handled rather than silently ignored.
r, h double - radius and height of the cone l double - slant height, computed by Pythagoras csa double - curved surface area of the cone r, c int - number of rows and columns of the pattern i, j int - loop variables for the rows and columns m, n int - the dividend and the divisor ch char - 'Q' for quotient, 'R' for remainder ob Perform - object of the class used to invoke the methods