How to write a java program that add up the values between two numbers?
- Wednesday Nov 18,2009 12:42 AM
- By diddy
- In Others
How to write a java program that add up the valve between two number?
Say if my lower number is 7 and higher number is 11, then the program should add 7+8+9+10+11=45. But if the lower number is bigger the the higher number, its should show and error message.





3 Comments
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int high,low,sum=0;
Scanner in=new Scanner(System.in);
System.out.println("enter the first number");
low=in.nextInt();
System.out.println("enter the second number");
high=in.nextInt();
if(high>=low){
for(int i=low;i<=high;i++)
sum=sum+i;
System.out.println("the sum is "+sum);
}
else{
System.out.println("Error");
}
}
}
Write a Java class with a "main" function and a "sumInterval" function. The latter will take two parameters, being the two numbers. The "main" function will call "sumInterval" with either two hardcoded values, or retrieve those values from the command line or some sort of datasource.
In the "sumInterval" function, you could report an error message if the first number is greater than the second number, but you could also just swap them so the first number is used as the second number, and vice versa.
In the body of the function, perform a loop with a counter initialized to the first number, along with a "sum" initialized to zero. In each iteration of the loop, add the value of the counter to the sum. The loop should terminate when the counter is greater than the second number. "increment" portion of the loop should increment the counter.
At the end of the function, have it return the value of the "sum" variable.
In the "main" function, get the result from "sumInterval" into a local variable and print out the resulting sum, along with the two numbers at the ends of the interval.
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package examples;
import java.util.Scanner;
/**
*
* @author lakmal
*/
public class Number {
/**
* @param args the command line arguments
*/
void addNumbers(int lower, int higher) {
int sum = 0;
if (higher >= lower) {
for (int i = lower; i <= higher; i++) {
sum += i;
}
System.out.println("Total=" + sum);
} else {
System.out.println(" ‘Higher’ number should be greater than ‘Lower’ number");
this.getNumbers();
}
}
void getNumbers() {
Scanner input = new Scanner(System.in);
System.out.println("Enter Your Lower Number:");
int lower = input.nextInt();
System.out.println("Enter Your Higher Number:");
int higher = input.nextInt();
this.addNumbers(lower, higher);
}
public static void main(String[] args) {
// TODO code application logic here
Number number1 = new Number();
number1.getNumbers();
}
}
Hope this will help !! if any problem related to this please mail me lakmalpadmakumara@gmail.com
Recent Posts
Recent Comments
Leave a reply