What will the following code print out?

01: public class MainClass {
02:   public static void main(String[] arg) {
03:     int limit = 10;
04:     int sum = 0;
05: 
06:     int i = 1;
07:     for (; i <= limit;) {
08:       sum += i++;
09:     }
10:     System.out.println(sum);
11:   }
12: }
Explanation
This loop can be rewritten as
for (int i=1; i <= 10;) {
       sum += i;
       i++;
}
which is in turn equal to
for (int i=1; i <= 10; i++) {
       sum += i;
}
And the sum is calculated: 1+2+3+4+5+6+7+8+9+10 = 55

The short formula for such a row is n*(n+1)/2 = 10*11/2 = 110/2 = 55

2018 Nov 30, 5:41:50 PM

Java
Java Quiz
Start Quiz

or Read more about Java Quiz

Follow CodeGalaxy

Mobile Beta

Get it on Google Play
Send Feedback