for-loop interview questions

Top 15 for-loop interview questions

33773 Jobs openings for for-loop

Avoiding if statement inside a for loop?

I have a class called Writer that has a function writeVector like so:

void Drawer::writeVector(vector<T> vec, bool index=true)
    for (unsigned int i = 0; i < vec.size(); i++) {
        if (index) {
            cout << i << "\t";
        cout << vec[i] << "\n";

I'm trying not to have a duplicate code, while still worrying about the performance. In the function, I'm doing the if (index) check on every round of my for-loop, even though the result is always the same. This is against "worrying about the performance".

I could easily avoid this by placing the check outside of my for-loop. However, I'll get loads of duplicate code:

void Drawer::writeVector(...)
    if (index) {
        for (...) {
            cout << i << "\t" << vec[i] << "\n";
    else {
        for (...) {
            cout << vec[i] << "\n";

So these are both "bad" solutions for me. What I've been thinking, is two private functions, one of them outs the index and then calls the other. The other one only outs the value. However, I can't figure out how to use it with my program, I'd still need the if check to see which one to call...

According to the problem, polymorphism seems like a correct solution. But I can't see how should I use it here. What would be the preferred way to solve this kind of problem?

This is not a real program, I'm just interested in learning how this kind of problem should be solved.

Source: (StackOverflow)

Breaking out of a nested loop

If I have a for loop which is nested within another, how can I efficiently come out of both loops (inner and outer) in the quickest possible way?

I don't want to have to use a boolean and then have to say go to another method, but rather just to execute the first line of code after the outer loop.

What is a quick and nice way of going about this?


I was thinking that exceptions aren't cheap/should only be thrown in a truly exceptional condition etc. Hence I don't think this solution would be good from a performance perspective.

I don't feel it it is right to take advantage of the newer features in .NET (anon methods) to do something which is pretty fundamental.

Because of that, tvon (sorry can't spell full username!) has a nice solution.

Marc: Nice use of anon methods, and this too is great but because I could be in a job where we don't use a version of .NET/C# that supports anon methods, I need to know a traditional approach too.

Source: (StackOverflow)

Is it possible to implement a Python for range loop without an iterator variable?

Is is possible to do this;

for i in range(some_number):
    #do something

without the i? If you just want to do something x amount of times and don't need the iterator.

Source: (StackOverflow)

What do two left angle brackets mean? [duplicate]

This question already has an answer here:

I saw a loop which I've never seen before:

for (int i = 0; i < (1 << list.Count); i++)

I can't understand what (1 << list.Count) means, maybe someone could explain me this?

Source: (StackOverflow)

How to optimize for-comprehensions and loops in Scala?

So Scala is supposed to be as fast as Java. I'm revisiting some Project Euler problems in Scala that I originally tackled in Java. Specifically Problem 5: "What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?"

Here's my Java solution, which takes 0.7 seconds to complete on my machine:

public class P005_evenly_divisible implements Runnable{
    final int t = 20;

    public void run() {
        int i = 10;
        while(!isEvenlyDivisible(i, t)){
            i += 2;

    boolean isEvenlyDivisible(int a, int b){
        for (int i = 2; i <= b; i++) {
            if (a % i != 0) 
                return false;
        return true;

    public static void main(String[] args) {
        new P005_evenly_divisible().run();

Here's my "direct translation" into Scala, which takes 103 seconds (147 times longer!)

object P005_JavaStyle {
    val t:Int = 20;
    def run {
        var i = 10
            i += 2
    def isEvenlyDivisible(a:Int, b:Int):Boolean = {
        for (i <- 2 to b)
            if (a % i != 0)
                return false
        return true
    def main(args : Array[String]) {

Finally here's my attempt at functional programming, which takes 39 seconds (55 times longer)

object P005 extends App{
    def isDivis(x:Int) = (1 to 20) forall {x % _ == 0}
    def find(n:Int):Int = if (isDivis(n)) n else find (n+2)
    println (find (2))

Using Scala on Windows 7 64-bit. How do I improve performance? Am I doing something wrong? Or is Java just a lot faster?

Source: (StackOverflow)

Is there a way to access an iteration-counter in Java's for-each loop?

Is there a way in Java's for-each loop

for(String s : stringArray) {

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) {

the only way to have such a counter available in a for-each loop?

Source: (StackOverflow)

Elements order in a "for (… in …)" loop

Does the "for…in" loop in Javascript loop through the hashtables/elements in the order they are declared? Is there a browser which doesn't do it in order?
The object I wish to use will be declared once and will never be modified.

Suppose I have:

var myObject = { A: "Hello", B: "World" };

And I further use them in:

for (var item in myObject) alert(item + " : " + myObject[item]);

Can I expect 'A : "Hello"' to always come before 'B : "World"' in most decent browsers?

Source: (StackOverflow)

How to loop through a c++ map

How would I loop through a map in c++ i've searched but none seem to work for me. My map is defined as follows

std::map< std::string, std::map<std::string, std::string> >

So for example this holds data like this:

m["name1"]["value1"] = "data1";
m["name1"]["value2"] = "data2";
m["name2"]["value1"] = "data1";
m["name2"]["value2"] = "data2";
m["name3"]["value1"] = "data1";
m["name3"]["value2"] = "data2";

So how can I loop through this map and access the various values.

Source: (StackOverflow)

Can I use break to exit multiple nested for loops?

Is it proper to use the break function to exit several nested for loops? If so, how would you go about doing this? Can you also control how many loops the break exits?

Source: (StackOverflow)

How do I break out of a loop in Scala?

How do I break out a loop?

var largest=0
for(i<-999 to 1 by -1) {
    for (j<-i to 1 by -1) {
        val product=i*j
        if (largest>product)
            // I want to break out here
              largest=largest max product

How do I turn nested for loops into tail recursion?

From Scala Talk at FOSDEM 2009 http://www.slideshare.net/Odersky/fosdem-2009-1013261 on the 22nd page:

Break and continue Scala does not have them. Why? They are a bit imperative; better use many smaller functions Issue how to interact with closures. They are not needed!

What is the explanation?

Source: (StackOverflow)

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

I understand how this construct works:

for i in range(10):

    if i == 9:
        print("Too big - I'm giving up!")
    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)

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)

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)

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#.


for(int counter=0; counter<list.Count; counter++)


foreach(MyType current in list)

Source: (StackOverflow)

Java 8 Iterable.forEach() vs foreach loop

Which of the following is better practice in Java 8?


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


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?


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)