Home > Back-end >  java program for print all numbers between -100 to 100 divisible by 3
java program for print all numbers between -100 to 100 divisible by 3

Time:12-24

I tried this many times, but if anyone can help with this solution I would be grateful.

There is my code, any other versions?

int n=201;
int []array = new int[n];
int j=0;

for (int i = -100;i <= 100; i  )
{
    if (i % 3 != 0)
    {
        array[j] = i;
        j  ;
    }
}
for (int i = 0;i < j;i  )
{
    System.out.println(array[i]);
}

CodePudding user response:

You can use the Stream API to print all numbers between -100 to 100 divisible by 3.

Like this ...

IntStream.rangeClosed(-100, 100)
         .filter((item) -> item % 3 == 0)
         .forEach(System.out::println);

The rangeClosed() method takes both the arguments and generates a Stream containing a sequence of numbers from -100 to 100 both inclusive.

CodePudding user response:

java program for print all numbers between -100 to 100 divisible by 3

You don't need a list or array. Just print the numbers.

But first, you need to adjust the starting value so it is divisible by 3. This can be done using the remainder operator.

int start = -100;
start -= start % 3;  // start - (-1) = -99
int end = 100;

Now just iterate thru the range, incrementing by 3.

for(int i = start; i <= end; i =3) {
   System.out.println(i);
}
  • Related