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]);
}
There's no need to store the numbers since you want just to print them:
for (int i = -100;i <= 100; i++)
if (i % 3 == 0)
System.out.println(i);
If you want to save such values in some collection, have a look at ArrayList<T>
(instead of array):
ArrayList<Integer> list = new ArrayList<Integer>();
for (int i = -100;i <= 100; i++)
if (i % 3 == 0)
list.add(i);
for (int item : list)
System.out.println(item);
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.
Using the fact that that integer division drops the fraction (100/3 = 33)
and that 33*3 = 99
you can determine the starting and ending number divisible by 3
. Then just increment the counter by 3
.
int start = -(100/3)*3;// first number divisible by three greater than -100.
int end = (100/3)*3; // last number divisible by three less than 100.
for(int i = start; i <= end; i+=3) {
System.out.println(i);
}
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 .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.