EzDevInfo.com

for-loop interview questions

Top for-loop frequently asked interview questions

for loop to iterate over enum in Java?

I have an enum in Java for the cardinal & intermediate directions:

public enum Direction {
   NORTH,
   NORTHEAST,
   EAST,
   SOUTHEAST,
   SOUTH,
   SOUTHWEST,
   WEST,
   NORTHWEST
}

How can I write a for loop that iterates through each of these enum values?


Source: (StackOverflow)

What is the difference between ++i and i++

In C, what is the difference between using ++i and i++, and which should be used in the incrementation block of a for loop?


Source: (StackOverflow)

Advertisements

Last iteration of for loop in java

Is there a way to determine if the loop is iterating for the last time. My code looks something like this:

int[] array = {1, 2, 3...};
StringBuilder builder = new StringBuilder();

for(int i : array)
{
    builder.append("" + i);
    if(!lastiteration)
        builder.append(",");
}

Now the thing is I don't want to append the comma in the last iteration. Now is there a way to determine if it is the last iteration or am I stuck with the for loop or using an external counter to keep track.


Source: (StackOverflow)

Loop through array in JavaScript

In Java you can use a for() loop to go through objects in an array like so:

String[] myStringArray = {"Hello","World"};
for(String s : myStringArray)
{
    //Do something
}

Can you do the same in JavaScript?


Source: (StackOverflow)

Why does the order of the loops affect performance when iterating over a 2D array? [duplicate]

Possible Duplicate:
Which of these two for loops is more efficient in terms of time and cache performance

Below are two programs that are almost identical except that I switched the i and j variables around. They both run in different amounts of time. Could someone explain why this happens?

Version 1

#include <stdio.h>
#include <stdlib.h>

main () {
  int i,j;
  static int x[4000][4000];
  for (i = 0; i < 4000; i++) {
    for (j = 0; j < 4000; j++) {
      x[j][i] = i + j; }
  }
}

Version 2

#include <stdio.h>
#include <stdlib.h>

main () {
  int i,j;
  static int x[4000][4000];
  for (j = 0; j < 4000; j++) {
     for (i = 0; i < 4000; i++) {
       x[j][i] = i + j; }
   }
}

Source: (StackOverflow)

Is there a technical reason to use > (<) instead of != when incrementing by 1 in a 'for' loop? [duplicate]

This question already has an answer here:

I almost never see a for loop like this:

for (int i = 0; 5 != i; ++i)
{}

Is there a technical reason to use > or < instead of != when incrementing by 1 in a for loop? Or this is more of a convention?


Source: (StackOverflow)

Are loops really faster in reverse?

I've heard this quite a few times. Are JavaScript loops really faster when counting backward? If so, why? I've seen a few test suite examples showing that reversed loops are quicker, but I can't find any explanation as to why!

I'm assuming it's because the loop no longer has to evaluate a property each time it checks to see if it's finished and it just checks against the final numeric value.

I.e.

for (var i = count - 1; i >= 0; i--)
{
  // count is only evaluated once and then the comparison is always on 0.
}

Source: (StackOverflow)

Iterate all files in a directory using a for-loop

How can I iterate over each file in a directory using a for-loop? And how could I tell if a certain entry is a directory or if it's just a file?


Source: (StackOverflow)

Never seen before C++ for loop

I was converting a C++ algorithm to C#. I came across this for loop:

for (u = b.size(), v = b.back(); u--; v = p[v]) 
b[u] = v;

It gives no error in C++, but it does in C# (cannot convert int to bool). I really can't figure out this for loop, where is the condition?

Can someone please explain?

PS. Just to check, to adapt a VECTOR to a LIST does b.back() correspond to b[b.Count-1] ?


Source: (StackOverflow)

In .NET, which loop runs faster, 'for' or 'foreach'?

In C#/VB.NET/.NET, which loop runs faster, for or foreach?

Ever since I read that a for loop works faster than a foreach loop a long time ago I assumed it stood true for all collections, generic collections, all arrays, etc.

I scoured Google and found a few articles, but most of them are inconclusive (read comments on the articles) and open ended.

What would be ideal is to have each scenario listed and the best solution for the same.

For example (just an example of how it should be):

  1. for iterating an array of 1000+ strings - for is better than foreach
  2. for iterating over IList (non generic) strings - foreach is better than for

A few references found on the web for the same:

  1. Original grand old article by Emmanuel Schanzer
  2. CodeProject FOREACH Vs. FOR
  3. Blog - To foreach or not to foreach, that is the question
  4. ASP.NET forum - NET 1.1 C# for vs foreach

[Edit]

Apart from the readability aspect of it, I am really interested in facts and figures. There are applications where the last mile of performance optimization squeezed do matter.


Source: (StackOverflow)

Java 8 Iterable.forEach() vs foreach loop

Which of the following is better practice in Java 8?

Java8:

joins.forEach((join) -> mIrc.join(mSession, join));

Java7:

for (String join : joins) {
    mIrc.join(mSession, join);
}

I have lots of for loops that could be "simplified" with lambdas, but is there really any advantage of using them including performance and readability?

EDIT

I'll also extend this question to longer methods - I know that you cant return or break the parent function from a lambda and this should be mentioned to if they are compared, but is there anything else to be considered?


Source: (StackOverflow)

Performance difference for control structures 'for' and 'foreach' in C#

Which code snippet will give better performance? The below code segments were written in C#.

1.

for(int counter=0; counter<list.Count; counter++)
{
    list[counter].DoSomething();
}

2.

foreach(MyType current in list)
{
    current.DoSomething();
}

Source: (StackOverflow)

Is it possible to declare two variables of different types in a for loop?

Is it possible to declare two variables of different types in the initialization body of a for loop in C++?

For example:

for(int i=0,j=0 ...

defines two integers. Can I define an int and a char in the initialization body? How would this be done?


Source: (StackOverflow)

C++11: how to use range-based for() loop with std::map?

The common example for C++0x range-based for() loops is always something simple like this:

std::vector<int> numbers = { 1, 2, 3, 4, 5, 6, 7 };
for ( auto xyz : numbers )
{
     std::cout << xyz << std::endl;
}

In which case xyz is an int. But, what happens when we have something like a map? What is the type of the variable in this example:

std::map< foo, bar > testing = { /*...blah...*/ };
for ( auto abc : testing )
{
    std::cout << abc << std::endl;         // ? should this give a foo? a bar?
    std::cout << abc->first << std::endl;  // ? or is abc an iterator?
}

When the container being traversed is something simple, it looks like range-based for() loops will give us each item, not an iterator. Which is nice...if it was iterator, first thing we'd always have to do is to dereference it anyway.

But I'm confused as to what to expect when it comes to things like maps and multimaps.

(I'm still on g++ 4.4, while range-based loops are in g++ 4.6+, so I haven't had the chance to try it yet.)


Source: (StackOverflow)

Why does python use 'else' after for and while loops?

I understand how this construct works:

for i in range(10):
    print(i)

    if i == 9:
        print("Too big - I'm giving up!")
        break;
else:
    print("Completed successfully")

But I don't understand why else is used as the keyword here, since it suggests the code in question only runs if the for block does not complete, which is the opposite of what it does! No matter how I think about it, my brain can't progress seamlessly from the for statement to the else block. To me, continue or continuewith would make more sense (and I'm trying to train myself to read it as such).

I'm wondering how Python coders read this construct in their head (or aloud, if you like). Perhaps I'm missing something that would make such code blocks more easily decipherable?


Source: (StackOverflow)