0
Anybody help, what was the mistake i made in this program
import java.util.Scanner; class SumProg{ public static void main(String[ ] args) { Scanner sp = new Scanner(System.in); int initValue=sp.nextInt(); int finalValue=sp.nextInt(); for(int i=initValue;i<=finalValue;i++) { int sum=0; sum+=i; System.out.println("The sum of the numbers is:"+sum); } } }
2 Answers
+ 4
Hello there, I assume that you intend to print sum of numbers from initValue to finalValue.
The problem is that your sum variable is declared inside the loop, so everytime the loop runs, sum is set to zero.
Also the print statement is supposed to be outside the loop.
So your loop should be like
int sum = 0;
for(int i = initValue; i <= finalValue; i++){
sum += i;
}
System.out.print(sum);
0
thanks mate...got it