Java Program Prectiece question

 Return the Sum of Two Numbers

Create a method that takes two integers as arguments and returns their sum.

Examples

SumOfTwoNumbers(3, 2) ➞ 5

SumOfTwoNumbers(-3, -6) ➞ -9

SumOfTwoNumbers(7, 3) ➞ 10



methoid 1-

public class SumCalculator {
public static void main(String[] args) {
int num1 =
7;
int num2 = 3;
int sum = calculateSum(num1, num2);
System.out.println("The sum of " + num1 + " and " + num2 + " is: " + sum);
}

public static int calculateSum(int a, int b) {
return a + b;
}
}

Method 2-
public class SumCalculator {
public static void main(String[] args) {
int num1 =
3;
int num2 = 7;
int sum = calculateSum(num1, num2);
System.out.println("The sum of " + num1 + " and " + num2 + " is: " + sum);
}

public static int calculateSum(int a, int b) {
int sum = 0;
for (int i = a; i <= b; i++) {
sum += i;
}
return sum;
}
}





In this example, we define the calculateSum method that takes two integers (a and b) as input parameters. Instead of directly adding a and b, we use a loop to iterate through the range from a to b (inclusive) and accumulate the sum of all the numbers in between. The final sum is then returned. This approach is useful if you want to calculate the sum of a range of consecutive numbers rather than just adding two specific numbers together














Comments

Popular posts from this blog

Learn DevOps and Cloud Computing -- FREE Certificates -- , build your knowledge