Logo 
Search:

Java Forum

Ask Question   UnAnswered
Home » Forum » Java       RSS Feeds

convert me this below program first into a new program using the while loop

  Asked By: Matilda    Date: Dec 20    Category: Java    Views: 3540
  

can anyone convert me this below program first into a new
program using the while loop. And then the program using the do
while loop.


// This class will test the performance of the for loop
public class IterativeStatements {


public static void main(String[] args) {

// Save the start time.
long timeStarted = System.currentTimeMillis();

// Create an array of integers, and populated
int[] numbers = new int[1000000];
for(int i=0; i<numbers.length; i++)
numbers[i] = i;

for(int i=2; i<numbers.length; i++)
if(numbers[i]!=0)
for(int j=i*2; j<numbers.length; j+=i)
numbers[j] = 0;

// Program finished
long timeFinished = System.currentTimeMillis();
System.out.println("Time taken in milli seconds: "
+(timeFinished-timeStarted));

/*
* Display only those which are not zero,
* therefore the prime numbers
*/
for(int i=0; i<numbers.length; i++)
if(numbers[i]!=0)
System.out.println(numbers[i]);
}
}

Share: 

 

1 Answer Found

 
Answer #1    Answered By: Edith Mcdonald     Answered On: Dec 20

FOR LOOP:

for(int i=0; i<numbers.length; i++)
numbers[i] = i;

WHILE LOOP:

int i=0;
while (i<numbers.length) {
numbers[i] = i;
i++;
}

DO WHILE LOOP:

int i=0;
if (i<numbers.length) {
do {
numbers[i] = i;
i++;
}
while (i<numbers.length);
}

Here are a couple notes:

The do/while loop  is not appropriate for this problem. The do/while loop is
only
used in cases where you need to run the loop at least once.

Speed is approximately the same. The three constructs are used in different
situations and speed is not a factor. For the loops given here the for loop is
the
appropriate construct.

 




Tagged: