Search code examples
bluej

I was making a program on BlueJ but i am unable to figure was is wrong in the code


I made a program in BlueJ to display the even numbers from 1 to 100. But the Output is even numbers from 8 to 100. So i request you to please help me to rectify my error. For this i would be thankful to you.

public class EvenNumbers1to100
 {
    public static void main(String args[])
    {
        int a;
        for(a=2;a<=100;a+=2)
        System.out.println(a);
    }
}

Solution

  • try this

    int a = 100;
    
    System.out.println("Even numbers from 1 to " + a);
    
    for (int i = 1; i <= a; i++) {
      if (i % 2 == 0) {
       System.out.print(i + " ");
      }
    }
    

    You gotta go for a loop if you want to print all the numbers out