Question 6
Java Programming Language (Article) (Program)
10
Question 6
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.
Program:
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); } }
Output:
This Particular section is dedicated to Programs only. If you want learn more about Java Programming Language. Then you can visit below links to get more depth on this subject.