Page 218 - Cs_withBlue_J_C11_Flipbook
P. 218
8 avg= sum/2.0;
9 System.out.println("Sum "+ sum + " and Average "+ avg);
10 sum = n1+n2;
11 avg= sum/2.0;
12 System.out.println("Sum "+ sum + " and Average "+ avg);
13 }
14 }
The output of the preceding program is as follows:
Sum 40 and Average 20.0
Sum 55 and Average 27.5
In the above program, the sum and average marks of two students are to be calculated, separately for each of them. For
this, the marks of the first student are input and their sum and average are found. Similarly, again the code is written
to find the sum and average of marks of the second student. While coding this program, we clearly understand that
we are writing similar statements twice. So, it would be wise if we have a technique that can remove this redundancy.
Faced with such an issue, the developers found a solution and designed a ‘method’, a technique using which the
redundant statements (i.e., the statements to be repeated) can be avoided and statements need to be written only
once and be executed the required number of times, just by calling the method.
So, they used the code in the following way.
class sum_average
{
void calculate(int m, int n)
{
int sum = m + n;
double average = sum/2.0;
System.out.println(sum+ " " +average);
}
void main()
{
calculate(10,30);
calculate(20,35);
}
}
Note: Methods are the block of statements in a program which performs a specific task and can be
reused as and whenever required. They are also called Functions.
In the above code, the calculate() method is called twice with different values. However, the code is written once in the
method. This reduces the size of the program as well as the probability of committing mistakes is reduced.
9.2 NEED FOR USING A METHOD
Methods contain specific tasks which are invoked only when they are required. They are very useful as:
• They reduce the size of the coding.
• They reduce the burden of debugging the programming code, as finding and correcting the errors become easier for
the developers.
• They also occupy less space in memory and the execution becomes faster.
216216 Touchpad Computer Science-XI

