Write a program for even numbers..

Reply

Join Date: Mar 2009
Posts: 3
Reputation: Tizzie is an unknown quantity at this point 
Solved Threads: 0
Tizzie Tizzie is offline Offline
Newbie Poster

Write a program for even numbers..

 
0
  #1
Mar 13th, 2009
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)
{
c++;
L[c] = i;

}







}
}
Reply With Quote Quick reply to this message  
Join Date: Nov 2008
Posts: 823
Reputation: verruckt24 is a jewel in the rough verruckt24 is a jewel in the rough verruckt24 is a jewel in the rough verruckt24 is a jewel in the rough 
Solved Threads: 73
verruckt24's Avatar
verruckt24 verruckt24 is offline Offline
Practically a Posting Shark

Re: Write a program for even numbers..

 
0
  #2
Mar 13th, 2009
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
  1. int L[]=new int[50];

you can safely do this:

  1. 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.
Last edited by verruckt24; Mar 13th, 2009 at 1:28 pm.
Get up every morning and take a look at the Forbes' list of richest people. If your name doesn't appear.... GET TO WORK !!!
Reply With Quote Quick reply to this message  
Join Date: Jan 2007
Posts: 706
Reputation: stultuske is a jewel in the rough stultuske is a jewel in the rough stultuske is a jewel in the rough 
Solved Threads: 84
stultuske's Avatar
stultuske stultuske is offline Offline
Master Poster

Re: Write a program for even numbers..

 
0
  #3
Mar 16th, 2009
and you could do the next:

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

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
Reply With Quote Quick reply to this message  
Reply

This thread is more than three months old.
Perhaps start a new thread instead?
Message:


Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC