Question

1) write an example of an iterator with a while loop 2) write an example of...

1) write an example of an iterator with a while loop



2) write an example of a for each loop


I have a test tomorrow so I would like to know how to write both questions with a simple example
0 0
Add a comment Improve this question Transcribed image text
Answer #1

1.  

/* All solution are in java */

//Assuming we have some arraylist

ArrayList<String> list = new ArrayList<String>();

       list.add("A");
       list.add("B");
       list.add("C");
       list.add("D");
       list.add("E");

//Now we will create the iterator object which will contain all data of list
       Iterator iterator = list.iterator();

//Now we will get and print data of iterator using while loop

System.out.println("List elements : ");

       while (iterator.hasNext())
           System.out.print(iterator.next() + " ");

/* This is the output */

List elements : 
A B C D E 

/* 2. For each loop */

for each loop is used to iterate the data from begening to last without stopping and without worrying about the index.

Here is the example

Assuming we have array of integers:

int A[] = {1,2,3,4,5};

using for each loop, we will print it as below:

for(int data: A) //Print all data from A assigning in data variable

{

System.out.print(data+" ");

}

//Now output will be 1 2 3 4 5

This is the use of for each loop.

/* For C++ */

Add a comment
Know the answer?
Add Answer to:
1) write an example of an iterator with a while loop 2) write an example of...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT