The program will take two integers from the user, say n1 and n2. It will then ca
ID: 3648664 • Letter: T
Question
The program will take two integers from the user, say n1 and n2. It will then call the method sum(n1, n2) to calculate the sum of all numbers between n1 and n2, inclusive. The answer returned by the sum( ) method will then be displayed on the screen. For example, if the user enters 5 and 9, the program will print the value of 5+6+7+8+9. On the other hand, if the user enters 5 and -2, the program will print the value of 5+4+3+2+1+0+(-1)+(-2). Note: Do not assume the user will always enter the smaller number first.Explanation / Answer
please rate - thanks
import java.util.*;
class main{
public static void main(String args[])
{int n1,n2;
Scanner in=new Scanner(System.in);
System.out.print("Enter the starting number: ");
n1=in.nextInt();
System.out.print("Enter the ending number: ");
n2=in.nextInt();
System.out.println("The sum of the numbers from "+n1+" to "+n2+" is "+sum(n1,n2));
}
public static int sum(int n1, int n2)
{int i,sum=0,start,stop;
start=n2;
stop=n1;
if(n1<n2)
{start=n1;
stop=n2;
}
for(i=start;i<=stop;i++)
sum+=i;
return sum;
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.