kristintirin kristintirin - 1 month ago 5
Java Question

Java program that display sequence of 5 even numbers starting from the input number

I need a java program that will print a sequence of 5 even numbers starting from the input number.

The output should be :

2 4 6 8 10


But when I input 4 the output was : 4 6 8 but it should be: 4 6 8 10 12
how to set a sequence of 5 even numbers starting from the input.
enter image description here

So far this is my code:

int sum = 0;
System.out.println("Enter number:");

int num = Integer.parseInt(br.readLine());
if (num % 2 == 0) {
for (int x = num; x <= 6; x++) // HERE
{
System.out.print(num + " ");
sum = sum + num;
num = num + 2;
}
System.out.println("");
System.out.println("Sum is " + sum);
}


It would help me a lot. thanks in advance!

Answer

You just need to loop 5 times, so consider

    int num= Integer.parseInt(br.readLine());
    if (num%2 == 0)
    {
        for (int x=0; x < 5;x++) 
        {    
          System.out.print(num + " ");
          num=num+2;
        }
    }

Based upon your comment (loop for 10 for odd) so could do

    int num= Integer.parseInt(br.readLine());
    int loopTo = 10;
    if (num%2 == 0)
    {
       loopTo = 5;
    }

     for (int x=0; x < loopTo;x++) 
     {    
          System.out.print(num + " ");
          num=num+2;
     }
Comments