Home / Questions / (vii)John was asked to write a Java code to calculate the surface area of a cone. The following code was written by him: Formula: Surface area of a cone is A = πrℓ, where ℓ = √(r² + h²) 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; } } Task: (a) Specify the type of error in the above program.(b) Correct the program and write the error-free version.
Explanatory Question

(vii)

John was asked to write a Java code to calculate the surface area of a cone. The following code was written by him:

Formula:

Surface area of a cone is A = πrℓ, where ℓ = √(r² + h²)


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;  
    }  
}  

Task:

(a) Specify the type of error in the above program.
(b) Correct the program and write the error-free version.

👁 0 Views
📘 Detailed Answer
🕒 Easy to Read
Read the answer carefully and go through the related questions on the right side to improve your understanding of this topic.

Answer with Explanation

Solution:

(a) Type of Error:

The error in the program is the incorrect order of operations. The variable l is used before it is initialized, which leads to an undefined variable error or logical error.


variable l might not have been initialized
        a = 22.0/7 * r * l;
                         ^
1 error

(b) Corrected Program:

Below is the corrected version of the program:


class Area  
{  
    double area(double r, double h)  
    {  
        double l, a;  
        l = Math.sqrt(r * r + h * h); // Compute l first  
        a = (22.0 / 7) * r * l; // Use l after initialization  
        return a;  
    }  

    public static void main(String args[])  
    {  
        Area obj = new Area();  
        double result = obj.area(5, 12); // Example values (r = 5, h = 12)  
        System.out.println("Surface Area of Cone: " + result);  
    }  
}  

Explanation of Fixes:

  1. Fixed the order of operations:

    • l = Math.sqrt(r * r + h * h); is now calculated before using it in a = (22.0 / 7) * r * l;.

  2. Added a main method:

    • This allows the program to run and test the output.

Expected Output for r = 5, h = 12:


Surface Area of Cone: 94.28571428571429