So I have to write a program which writes all even numbers between 0 and 50 INTO AN ARRAY and then display them on the screen....

My problem is how i am going to put it into an array I only did part of it but I can't continue doing it...:-

public class Even_Number{
public static void main (String args[]) {
int L[]=new int[50];
int i;
int c =0;

for (i=0; i<50; i++)
if (i%2==0)
L[c] = i;



Why can't you continue doing it ? As far as I am seeing you are going good.

Just one thing, if you know you are going to put only even numbbers in the array from amongst 50 numbers, instead of declaring the array as

int L[]=new int[50];

you can safely do this:

int [] L = new int[50/2];

Out of any set of fifty numbers there are never going to be more than 25 even numbers, isn't it so you are saving space on 25 numbers where each one is 4 bytes 25 x 4 = 100 bytes.

and you could do the next:

int[] evens = new int[25];
// as Verruckt pointed out, you don't need one of size 50
int location = 0;
for ( int i = 2; i < 50; i = i + 2){
  evens[location] = i;
  location += 1;

there's not really the need to perform a check for evens.
with the (i % 2) test you'll get the right contents, but it's easier just to add 2 every time during the loop

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.