Skip to content
Advertisement

Why is the number 30 not displayed at the end of the output? [closed]

enter image description here

package com.company;

public class Main {

    public static void main(String[] args) {
        // write your code here
        int p=0;

        for (int i=1; i<11; i++)
        {
            if (i%2 == 0)
            {
                System.out.println(p);
                p = p + i;
            }
        }
    }
}

Advertisement

Answer

Add a print after the loop. You can also start with 2. And increment by 2 for each iteration (thus eliminating the need for the modulo two test). Something like,

int p = 0;
for (int i = 2; i < 11; i += 2) {
    System.out.println(p);
    p += i;
}
System.out.println(p);

Which outputs

0
2
6
12
20
30
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement