I am supposed to change an ordinary for loop into an enhanced for each loop. I have the following two problems:

1. for(int i = 1; i<data.length; i++)
sum = sum + data;
2.  for(int i = 0; i<data.length; i++)
if(data == target)
return i;

These are the only pieces of information given, I am just supposed to rewrite them in "for each" form. Thus far I have:

1. nothing - I can't figure out how to exclude the first element aka data[0]
2. for(x : data)
{
if(x==target)
return

however I don't know what to enter after the return in order to return the value of i, and not the value of data

I would love any hints/input, I have been struggling for a while now and can't figure any of these out.

Recommended Answers

All 3 Replies

You can't use a return statement unless you are in a method, so I'm assuming that is the case here.

And to figure out the index,
1. Keep a counter and increment it each time you don't find the element you're looking for. Then return the counter

I can't think of any other ways to figure out the index that don't defeat the purpose when using a for each loop as of now.

Yes, that is assumed. This is not part of any code, we are just asked to rewrite these loops. None of the values given are initialized either.

Ok, so for the second one I have:

int i = 0;
          for(x : data)
          {
	        i++;
	        if(x==target)
	            return i;
           }

Would this work? I don't know if this defeats the purpose of using a for each loop though...but if it works, I will stick with it since we are not asked to optimize it but to merely rewrite it so it serves the right purpose.

What about the first one tho? Any ideas about that?

You have to put the i++ after the if statement. If you put it before the if statement, you will be one ahead. (For example, if the first element is the one you want, you will have returned the index 1, but you want to return the index 0)

int i = 0;
          for(x : data)
          {
	        if(x==target)
	            return i;
                    i++;
           }

Also, you have to specify the type of x. int, Integer, String, whatever.

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.