Write a program that computes the sum from the integers a to b.The method you will write ispublic int sumFrom(int a, int b)For example, sumFrom(1, 10) returns 55 since the sum from 1 to 10 inclusive is 55.
Question
Write a program that computes the sum from the integers a to b.The method you will write ispublic int sumFrom(int a, int b)For example, sumFrom(1, 10) returns 55 since the sum from 1 to 10 inclusive is 55.
Solution
Here is a simple Java program that computes the sum of integers from a to b:
public class Main {
public static void main(String[] args) {
System.out.println(sumFrom(1, 10));
}
public static int sumFrom(int a, int b) {
int sum = 0;
for (int i = a; i <= b; i++) {
sum += i;
}
return sum;
}
}
In this program, the sumFrom method takes two integers a and b as parameters. It initializes a variable sum to 0, then uses a for loop to iterate over all integers from a to b inclusive. For each integer i, it adds i to sum. Finally, it returns sum.
When you run this program with the arguments 1 and 10, the sumFrom method returns 55, which is the sum of all integers from 1 to 10 inclusive.
Similar Questions
Write a Java program that outputs the sum, product, difference and quotientof two numbers using the class and object concept. That means you need to define a class,say MiniCalculator, which can be instantiated with the two given numbers. The sum,product, difference and quotient values should be computed using the methods of theMiniCalculator object. Use overloaded methods in the class you define to deal separatelywith integer and double type inputs. (e.g., sum(34, 678), sum(34.567, 234. 54) ). Write atest class to instantiate the MiniCalculator and demonstrate its functionality.
You need to create an app that calculates the sum of the numbers 1 to N, where N is taken from input.For example, for the number 5, the output should be 15, because 1+2+3+4+5=15.
Write a program to find the sum of two integers using an inline lambda expression.Input format :The input consists of 2 integers.Output format :The output prints the sum of two integers.Sample test cases :Input 1 :5 6 Output 1 :11Input 2 :-12 7Output 2 :-5Input 3 :-5 -7Output 3 :-12
Complete the function solveMeFirst to compute the sum of two integers.ExampleReturn .Function DescriptionComplete the solveMeFirst function in the editor below.solveMeFirst has the following parameters:int a: the first valueint b: the second valueReturns- int: the sum of and Constrain
Java program to sum values of an array.Write a Java program to sum values of an array. Constraints:N/AExample:Input:1, 2, 3, 4, 5, 6, 7, 8, 9, 10Output:55Explanation:-Public Test Cases:# INPUT EXPECTED OUTPUT1 1, 2, 3, 4, 5, 6, 7, 8, 9, 1055
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.