foreach interview questions
Top foreach frequently asked interview questions
I was wondering if there's a way to do something like a PHP foreach loop in JavaSript. The functionality I'm looking for is something like this: (PHP Snippet)
foreach($data as $key => $value) { }
I was looking at the JS for..in
loop, but there seems to be no way to specify the as
. If I do this with a 'normal' for loop (for(var i = 0; i < data.length; i++
), is there a way to grab the key => value pairs?
Source: (StackOverflow)
Are there any advantages of std::for_each
over for
loop? To me, std::for_each
only seems to hinder the readability of code. Why do then some coding standards recommend its use?
Source: (StackOverflow)
Is there a foreach construct in the Go language? Can I iterate over a slice or array using a for?
Source: (StackOverflow)
This question already has an answer here:
Is there a C# equivalent of Python's enumerate() and Ruby's each_with_index?
Source: (StackOverflow)
Is there a way in Java's for-each loop
for(String s : stringArray) {
doSomethingWith(s);
}
to find out how often the loop has already been processed?
Aside from using using the old and well-known for(int i=0;i<
boundary;i++)-loop, is the construct
int i = 0;
for(String s : stringArray) {
doSomethingWith(s);
i++;
}
the only way to have such a counter available in a for-each loop?
Source: (StackOverflow)
I am porting some code to Parallel.ForEach
and got an error with a continue
I have in the code. Is there something equivalent I can use in a Parallel.ForEach
functionally equivalent to continue
in a foreach
loop?
Parallel.ForEach(items, parallelOptions, item =>
{
if (!isTrue)
continue;
});
Source: (StackOverflow)
I have a foreach
loop and need to execute some logic when the last item is chosen from the List
, e.g.:
foreach (Item result in Model.Results)
{
//if current result is the last item in Model.Results
//then do something in the code
}
Can I know which loop is last without using for loop and counters?
Source: (StackOverflow)
I know NSDictionaries
as something where you need a key
in order to get a value
. But how can I iterate over all keys
and values
in a NSDictionary
, so that I know what keys there are, and what values there are? I know there is something called a for-in-loop in JavaScript
. Is there something similar in Objective-C
?
Source: (StackOverflow)
I just had a quick question regarding loops in Ruby. Is there a difference between these two ways of iterating through a collection?
# way 1
@collection.each do |item|
# do whatever
end
# way 2
for item in @collection
# do whatever
end
Just wondering if these are exactly the same or if maybe there's a subtle difference (possibly when @collection
is nil).
Source: (StackOverflow)
How can I loop through all the objects in an array using JavaScript?
I thought of something like this (where objects is my array of objects):
forEach(instance in objects)
But this does not seem to be correct.
Source: (StackOverflow)
When using lambda expressions or anonymous methods in C#, we have to be wary of the access to modified closure pitfall. For example:
foreach (var s in strings)
{
query = query.Where(i => i.Prop == s); // access to modified closure
...
}
Due to the modified closure, the above code will cause all of the Where
clauses on the query to be based on the final value of s
.
As explained here, this happens because the s
variable declared in foreach
loop above is translated like this in the compiler:
string s;
while (enumerator.MoveNext())
{
s = enumerator.Current;
...
}
instead of like this:
while (enumerator.MoveNext())
{
string s;
s = enumerator.Current;
...
}
As pointed out here, there are no performance advantages to declaring a variable outside the loop, and under normal circumstances the only reason I can think of for doing this is if you plan to use the variable outside the scope of the loop:
string s;
while (enumerator.MoveNext())
{
s = enumerator.Current;
...
}
var finalString = s;
However variables defined in a foreach
loop cannot be used outside the loop:
foreach(string s in strings)
{
}
var finalString = s; // won't work: you're outside the scope.
So the compiler declares the variable in a way that makes it highly prone to an error that is often difficult to find and debug, while producing no perceivable benefits.
Is there something you can do with foreach
loops this way that you couldn't if they were compiled with an inner-scoped variable, or is this just an arbitrary choice that was made before anonymous methods and lambda expressions were available or common, and which hasn't been revised since then?
Source: (StackOverflow)
Let me prefix this by saying that I know what foreach
is, does and how to use it. This question concerns how it works under the bonnet, and I don't want any answers along the lines of "this is how you loop an array with foreach
".
For a long time I assumed that foreach
worked with the array itself. Then I found many references to the fact that it works with a copy of the array, and I have since assumed this to be the end of the story. But I recently got into a discussion on the matter, and after a little experimentation found that this was not in fact 100% true.
Let me show what I mean. For the following test cases, we will be working with the following array:
$array = array(1, 2, 3, 4, 5);
Test case 1:
foreach ($array as $item) {
echo "$item\n";
$array[] = $item;
}
print_r($array);
/* Output in loop: 1 2 3 4 5
$array after loop: 1 2 3 4 5 1 2 3 4 5 */
This clearly shows that we are not working directly with the source array - otherwise the loop would continue forever, since we are constantly pushing items onto the array during the loop. But just to be sure this is the case:
Test case 2:
foreach ($array as $key => $item) {
$array[$key + 1] = $item + 2;
echo "$item\n";
}
print_r($array);
/* Output in loop: 1 2 3 4 5
$array after loop: 1 3 4 5 6 7 */
This backs up our initial conclusion, we are working with a copy of the source array during the loop, otherwise we would see the modified values during the loop. But...
If we look in the manual, we find this statement:
When foreach first starts executing, the internal array pointer is automatically reset to the first element of the array.
Right... this seems to suggest that foreach
relies on the array pointer of the source array. But we've just proved that we're not working with the source array, right? Well, not entirely.
Test case 3:
// Move the array pointer on one to make sure it doesn't affect the loop
var_dump(each($array));
foreach ($array as $item) {
echo "$item\n";
}
var_dump(each($array));
/* Output
array(4) {
[1]=>
int(1)
["value"]=>
int(1)
[0]=>
int(0)
["key"]=>
int(0)
}
1
2
3
4
5
bool(false)
*/
So, despite the fact that we are not working directly with the source array, we are working directly with the source array pointer - the fact that the pointer is at the end of the array at the end of the loop shows this. Except this can't be true - if it was, then test case 1 would loop forever.
The PHP manual also states:
As foreach relies on the internal array pointer changing it within the loop may lead to unexpected behavior.
Well, let's find out what that "unexpected behavior" is (technically, any behavior is unexpected since I no longer know what to expect).
Test case 4:
foreach ($array as $key => $item) {
echo "$item\n";
each($array);
}
/* Output: 1 2 3 4 5 */
Test case 5:
foreach ($array as $key => $item) {
echo "$item\n";
reset($array);
}
/* Output: 1 2 3 4 5 */
...nothing that unexpected there, in fact it seems to support the "copy of source" theory.
The Question
What is going on here? My C-fu is not good enough for me to able to extract a proper conclusion simply by looking at the PHP source code, I would appreciate it if someone could translate it into English for me.
It seems to me that foreach
works with a copy of the array, but sets the array pointer of the source array to the end of the array after the loop.
- Is this correct and the whole story?
- If not, what is it really doing?
- Is there any situation where using functions that adjust the array pointer (
each()
, reset()
et al.) during a foreach
could affect the outcome of the loop?
Source: (StackOverflow)
List<String> someList = new ArrayList<String>();
// add "monkey", "donkey", "skeleton key" to someList
for (String item : someList) {
System.out.println(item);
}
What would the equivalent for loop look like without using the for each syntax?
Source: (StackOverflow)
I'd like to do the equivalent of the following in LINQ, but I can't figure out how:
IEnumerable<Item> items = GetItems();
items.ForEach(i => i.DoStuff());
What is the real syntax?
Source: (StackOverflow)
Is there some rare language construct I haven't encountered (like the few I've learned recently, some on Stack Overflow) in C# to get a value representing the current iteration of a foreach loop?
For instance, I currently do something like this depending on the circumstances:
int i=0;
foreach (Object o in collection)
{
// ...
i++;
}
Source: (StackOverflow)