Design a class to overload a function Sum( ) as follows:
(i) int Sum(int A, int B) — with two integer arguments (A and B) calculate and return sum of all the even numbers in the range of A and B.
Sample input: A=4 and B=16
Sample output: sum = 4 + 6 + 8 + 10 + 12 + 14 + 16
(ii) double Sum( double N ) — with one double arguments(N) calculate and return the product of the following series:
sum = 1.0 x 1.2 x 1.4 x . . . . . . . . x N
(iii) int Sum(int N) - with one integer argument (N) calculate and return sum of only odd digits of the number N.
Sample input : N=43961
Sample output : sum = 3 + 9 + 1 = 13
Write the main method to create an object and invoke the above methods.
public class RAnsariSumOverload
{
public int Sum(int A, int B) {
int sum = 0;
for (int i = A; i <= B; i++) {
if (i % 2 == 0)
sum += i;
}
return sum;
}
public double Sum(double N) {
double p = 1.0;
for (double i = 1.0; i <= N; i += 0.2)
p *= i;
return p;
}
public int Sum(int N) {
int sum = 0;
while (N != 0) {
int d = N % 10;
if (d % 2 != 0)
sum += d;
N /= 10;
}
return sum;
}
public static void main(String args[]) {
RAnsariSumOverload obj = new RAnsariSumOverload();
int evenSum = obj.Sum(4, 16);
System.out.println("Even sum from 4 to 16 = " + evenSum);
double seriesProduct = obj.Sum(2.0);
System.out.println("Series Product = " + seriesProduct);
int oddDigitSum = obj.Sum(43961);
System.out.println("Odd Digits Sum = " + oddDigitSum);
}
}
First read the algorithm, then study the program code line by line. After that, compare the code with the output and finally go through the explanation. This approach helps learners understand both the logic and the implementation properly.
After understanding this example, try to rewrite the same program without looking at the code. Then change some values or logic and run it again. This helps improve confidence and keeps learners engaged on the page for longer.