943,697 Members | Top Members by Rank

Ad:
  • Java Discussion Thread
  • Unsolved
  • Views: 2136
  • Java RSS
Mar 13th, 2009
0

Write a program for even numbers..

Expand Post »
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;

}







}
}
Similar Threads
Reputation Points: 10
Solved Threads: 0
Newbie Poster
Tizzie is offline Offline
3 posts
since Mar 2009
Mar 13th, 2009
0

Re: Write a program for even numbers..

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
java Syntax (Toggle Plain Text)
  1. int L[]=new int[50];

you can safely do this:

java Syntax (Toggle Plain Text)
  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.
Reputation Points: 485
Solved Threads: 89
Posting Shark
verruckt24 is offline Offline
944 posts
since Nov 2008
Mar 16th, 2009
0

Re: Write a program for even numbers..

and you could do the next:

Java Syntax (Toggle Plain Text)
  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
Reputation Points: 919
Solved Threads: 354
Nearly a Posting Maven
stultuske is offline Offline
2,487 posts
since Jan 2007

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in Java Forum Timeline: How to build TreePath?
Next Thread in Java Forum Timeline: Creating a Jave file Dynamically





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC