Home > Mobile >  java program to loop and output 2,5,7,10,12
java program to loop and output 2,5,7,10,12

Time:10-23

Loop

how to loop this without using array? I'm clearly confuse in this in java module I don't know the solution ;-; I'm new to java pls helppp mee

CodePudding user response:

Try this.

for (int i = 5; i <= 25; i  = 5)
    System.out.println(i / 2);

Or

for (int i = 1; i <= 5; i  )
    System.out.println(i * 5 / 2);

output:

2
5
7
10
12

Think for yourself why this produces the correct result.

CodePudding user response:

public class Main {
    public static void main(String[] args) {
        int outputNum = 0;
        for(int i = 0; i < 5; i  ){

            if (i % 2 == 0){
                outputNum  = 2;
            }
            else {
                outputNum  = 3;
            }
            System.out.print(outputNum   (i == 4 ? "" : " "));
        }
    }
}

This does exactly what you need.
Explanation:
In the loop if the i variable is even we add 2 to the output number (since you need to add 2 then 3 then 2...) and if i is uneven then we add three. At the end of the for loop we print the number without the newline using System.out.print and we separate them by a space if we aren't printing the last number using a ternary operator (i == 4 ? "" : " ") which returns a space if i is not equal to 4 and an empty string if it is, we do this to avoid having a space on the end of our output, so we get this 2 5 7 10 12 instead of this 2 5 7 10 12

  • Related