The document describes writing a for loop to add integers from a lower limit (lo) to an upper limit (hi), inclusive, and store the result in the variable result. The for loop increments from lo to hi, adding each integer to the running total in result.
Assume the int variables i -lo - hi - and result have been declared an.docx
1. Assume the int variables i ,lo , hi , and result have been declared and that lo and hi have been
initialized.
Assume further that result has been initialized to the value 0.
Write a for loop that adds the integers from lo up through hi (inclusive), and stores the result in
result.
Do not declare any additional variables --
use only i,lo,hi.
------------------------
import java.util.Scanner;
public class forloop_add{
public static void main(String args[]) {
int i,lo=1,hi=3,result=0;
Scanner scanner =new Scanner(System.in);
System.out.println("Enter the lower limit:");
lo=scanner.nextInt();
System.out.println("Enter the upper limit:");
hi=scanner.nextInt();
///{
//write your code here
//start
//end
///}
System.out.println("Result:"+result);
}
}
2. Solution
import java.util.Scanner;
public class forloop_add{
public static void main(String args[]) {
int i,lo=1,hi=3,result=0;
Scanner scanner =new Scanner(System.in);
System.out.println("Enter the lower limit:");
lo=scanner.nextInt();
System.out.println("Enter the upper limit:");
hi=scanner.nextInt();
for(;lo<=hi;lo++)
{
result += lo;
}
///{
//write your code here
//start
//end
///}
System.out.println("Result:"+result);
}
}