ICSE Class 10 Computer Applications Question 24 of 30

Solved 2024 Specimen Paper ICSE Class 10 Computer Applications — Question 24

Back to all questions
24
Question

Question 2(iv)

Sam executes the following program segment and the answer displayed is zero irrespective of any non zero values are given. Name the error. How the program can be modified to get the correct answer?

void triangle(double b, double h)
{	
    double a; 
    a = 1/2 * b * h;
    System.out.println("Area=" + a);	
}	
Answer

Logical error.

Modified program:

void triangle(double b, double h)
{	
    double a; 
    a = 1.0/2 * b * h;
    System.out.println("Area=" + a);	
}	
Explanation

The statement is evaluated as follows:

a = 1/2 * b * h;
a = 0 * b * h; (1/2 being integer division gives the result as 0)
a = 0 (Since anything multiplied by 0 will be 0)

To avoid this error, we can replace '1/2' with '1.0/2'. Now the expression will be evaluated as follows:

a = 1.0/2 * b * h;
a = 0.5 * b * h; (The floating-point division will result in result as as 0.5)

This will give the correct result for the given code.