Questions tagged [for-loop]

A for loop is a control structure used by many programming languages to iterate over a range. It is a way of repeating statements a number of times until the loop ends. Depending on the language this may be over a range of integers, iterators, etc.

for-loop
Filter by
Sorted by
Tagged with
4015 votes
46 answers
5.4m views

Loop through an array in JavaScript

In Java, you can use a for loop to traverse objects in an array as follows: String[] myStringArray = {"Hello", "World"}; for (String s : myStringArray) { // Do something } Can ...
Mark Szymanski's user avatar
3581 votes
48 answers
2.8m views

How do I loop through or enumerate a JavaScript object?

I have a JavaScript object like the following: var p = { "p1": "value1", "p2": "value2", "p3": "value3" }; How do I loop ...
Tanmoy's user avatar
  • 45k
2990 votes
3 answers
257k views

Why is printing "B" dramatically slower than printing "#"?

I generated two matrices of 1000 x 1000: First Matrix: O and #. Second Matrix: O and B. Using the following code, the first matrix took 8.52 seconds to complete: Random r = new Random(); for (int i = ...
Kuba Spatny's user avatar
  • 26.8k
2176 votes
20 answers
1.8m views

How do I iterate over a range of numbers defined by variables in Bash?

How do I iterate over a range of numbers in Bash when the range is given by a variable? I know I can do this (called "sequence expression" in the Bash documentation): for i in {1..5}; do ...
eschercycle's user avatar
  • 22.6k
2076 votes
28 answers
1.0m views

Why is using "for...in" for array iteration a bad idea?

I've been told not to use for...in with arrays in JavaScript. Why not?
lYriCAlsSH's user avatar
  • 57.7k
1261 votes
9 answers
1.2m views

How do I iterate through two lists in parallel?

I have two iterables, and I want to go over them in pairs: foo = [1, 2, 3] bar = [4, 5, 6] for (f, b) in iterate_together(foo, bar): print("f:", f, " | b:", b) That should ...
Nathan Fellman's user avatar
1230 votes
21 answers
761k views

Difference between ( for... in ) and ( for... of ) statements?

I know what is a for... in loop (it iterates over the keys), but I have heard about for... of for the first time (it iterates over values). I am confused about for... of loop. var arr = [3, 5, 7]; arr....
Mukund Kumar's user avatar
  • 22.3k
1166 votes
21 answers
1.7m views

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?
The.Anti.9's user avatar
946 votes
9 answers
527k views

A for-loop to iterate over an enum in Java

I have an enum in Java for the cardinal and intermediate directions: public enum Direction { NORTH, NORTHEAST, EAST, SOUTHEAST, SOUTH, SOUTHWEST, WEST, NORTHWEST } How can I ...
Nick Meyer's user avatar
  • 39.7k
832 votes
6 answers
1.3m views

How to loop over files in directory and change path and add suffix to filename

I need to write a script that starts my program with different arguments. I start my program with: ./MyProgram.exe Data/data1.txt [Logs/data1_Log.txt]. Here is the pseudocode for what I want to do: ...
Dobrobobr's user avatar
  • 8,546
751 votes
25 answers
312k views

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&...
Kent Boogaart's user avatar
679 votes
13 answers
1.2m views

Get loop counter/index using for…of syntax in JavaScript

I understand that the basic for...of syntax in JavaScript looks like this: for (let obj of myArray) { // ... } But how do I get the loop counter/index when iterating with this syntax? (With the ...
hobbes3's user avatar
  • 29k
555 votes
8 answers
507k views

Java 8 Iterable.forEach() vs foreach loop

Which of the following is better practice in Java 8? Java 8: joins.forEach(join -> mIrc.join(mSession, join)); Java 7: for (String join : joins) { mIrc.join(mSession, join); } I have lots ...
nebkat's user avatar
  • 8,515
480 votes
8 answers
912k views

How do you loop through a std::map?

I want to iterate through each element in the map<string, int> without knowing any of its string-int values or keys. What I have so far: void output(map<string, int> table) { map&...
NoName's user avatar
  • 10.1k
454 votes
17 answers
825k views

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?
Vhaerun's user avatar
  • 13.1k
440 votes
41 answers
316k views

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 ...
423 votes
24 answers
374k views

Can I use break to exit multiple nested 'for' loops?

Is it possible 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?
Faken's user avatar
  • 11.6k
411 votes
7 answers
60k views

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

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 #...
Mark's user avatar
  • 8,578
410 votes
5 answers
348k views

How to use range-based for() loop with std::map?

The common example for C++11 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 <&...
Stéphane's user avatar
  • 19.8k
404 votes
13 answers
664k views

What is the most efficient way to loop through dataframes with pandas?

I want to perform my own complex operations on financial data in dataframes in a sequential manner. For example I am using the following MSFT CSV file taken from Yahoo Finance: Date,Open,High,Low,...
Muppet's user avatar
  • 5,889
400 votes
13 answers
726k views

Pythonic way to combine for-loop and if-statement

I know how to use both for loops and if statements on separate lines, such as: >>> a = [2,3,4,5,6,7,8,9,0] ... xyz = [0,12,4,6,242,7,9] ... for x in xyz: ... if x in a: ... print(...
ChewyChunks's user avatar
  • 4,609
392 votes
7 answers
428k views

Django - iterate number in for loop of a template

I have the following for loop in my django template displaying days. I wonder, whether it's possible to iterate a number (in the below case i) in a loop. Or do I have to store it in the database and ...
orschiro's user avatar
  • 20.8k
385 votes
20 answers
1.1m views

How to get the selected radio button’s value? [duplicate]

I’m having some strange problem with my JS program. I had this working properly but for some reason it’s no longer working. I just want to find the value of the radio button (which one is selected) ...
mkyong's user avatar
  • 12.7k
383 votes
9 answers
275k views

How to get the current index in for each Kotlin

How to get the index in a for each loop? I want to print numbers for every second iteration For example for (value in collection) { if (iteration_no % 2) { //do something } } In java, ...
Adolf Dsilva's user avatar
  • 13.7k
361 votes
3 answers
623k views

Get loop count inside a for-loop [duplicate]

This for loop iterates over all elements in a list: for item in my_list: print item Is there a way to know within the loop how many times I've been looping so far? For instance, I want to take a ...
greye's user avatar
  • 9,031
353 votes
23 answers
317k views

Difference between pre-increment and post-increment in a loop?

Is there a difference in ++i and i++ in a for loop? Is it simply a syntax thing?
GurdeepS's user avatar
  • 66.2k
335 votes
16 answers
311k views

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) { doSomethingWith(s); } to find out how often the loop has already been processed? Aside from using the old and well-known for(...
Kosi2801's user avatar
  • 22.6k
332 votes
11 answers
149k views

How to make my custom type to work with "range-based for loops"?

Like many people these days I have been trying the different features that C++11 brings. One of my favorites is the "range-based for loops". I understand that: for(Type& v : a) { ... } Is ...
ereOn's user avatar
  • 54.6k
322 votes
8 answers
264k views

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 ...
Nathan Osman's user avatar
  • 72.2k
321 votes
34 answers
378k views

What is the pythonic way to detect the last element in a 'for' loop?

How can I treat the last element of the input specially, when iterating with a for loop? In particular, if there is code that should only occur "between" elements (and not "after" ...
e.tadeu's user avatar
  • 5,154
315 votes
19 answers
259k views

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 ...
TiansHUo's user avatar
  • 8,609
315 votes
5 answers
528k views

How to check if all elements of a list match a condition?

I have a list that contains many sub-lists of 3 elements each, like: my_list = [["a", "b", 0], ["c", "d", 0], ["e", "f", 0], .....] The ...
alwbtc's user avatar
  • 28.8k
309 votes
7 answers
659k views

How do I loop through a list by twos? [duplicate]

I want to loop through a Python list and process 2 list items at a time. Something like this in another language: for(int i = 0; i < list.length(); i+=2) { // do something with list[i] and list[...
froadie's user avatar
  • 81.4k
302 votes
10 answers
607k views

For every character in string

How would I do a for loop on every character in string in C++?
Jack Wilsdon's user avatar
  • 6,857
297 votes
34 answers
147k views

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 ...
djdd87's user avatar
  • 68k
294 votes
14 answers
1.1m views

Iterate through a C++ Vector using a 'for' loop

I am new to the C++ language. I have been starting to use vectors, and have noticed that in all of the code I see to iterate though a vector via indices, the first parameter of the for loop is always ...
Flynn's user avatar
  • 6,081
287 votes
22 answers
618k views

Check if object value exists within a Javascript array of objects and if not add a new object to array

If I have the following array of objects: [ { id: 1, username: 'fred' }, { id: 2, username: 'bill' }, { id: 2, username: 'ted' } ] Is there a way to loop through the array to check whether a ...
user2576960's user avatar
  • 2,983
282 votes
27 answers
87k views

Why use iterators instead of array indices?

Take the following two lines of code: for (int i = 0; i < some_vector.size(); i++) { //do stuff } And this: for (some_iterator = some_vector.begin(); some_iterator != some_vector.end(); ...
Jason Baker's user avatar
276 votes
6 answers
101k views

How do I annotate types in a for-loop?

I want to annotate a type of a variable in a for-loop. I tried this but it didn't work: for i: int in range(5): pass What I expect is working autocomplete in PyCharm 2016.3.2, but using pre-...
Artem Yu's user avatar
  • 4,302
273 votes
4 answers
206k views

How to use continue in jQuery each() loop?

In my application i am using AJAX call. I want to use break and continue in this jQuery loop. $('.submit').filter(':checked').each(function() { });
Ravi Kant's user avatar
  • 4,915
268 votes
5 answers
470k views

TypeScript for ... of with index / key?

As described here TypeScript introduces a foreach loop: var someArray = [9, 2, 5]; for (var item of someArray) { console.log(item); // 9,2,5 } But isn't there any index/key? I would expect ...
Mick's user avatar
  • 8,594
250 votes
12 answers
274k views

Post-increment and pre-increment within a 'for' loop produce same output [duplicate]

The following for loops produce identical results even though one uses post increment and the other pre-increment. Here is the code: for(i=0; i<5; i++) { printf("%d", i); } for(i=0; i<5; +...
theReverseFlick's user avatar
249 votes
26 answers
249k views

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 ...
GurdeepS's user avatar
  • 66.2k
244 votes
16 answers
160k views

Is it possible to make a `for` loop without an iterator variable? (How can I make code loop a set number of times?)

Is it possible to do following without the i? for i in range(some_number): # do something If you just want to do something N amount of times and don't need the iterator.
238 votes
6 answers
369k views

GoTo Next Iteration in For Loop in java

Is there a token in java that skips the rest of the for loop? Something like VB's Continue in java.
user1277170's user avatar
  • 3,197
238 votes
6 answers
827k views

How can I loop through a List<T> and grab each item?

How can I loop through a List and grab each item? I want the output to look like this: Console.WriteLine("amount is {0}, and type is {1}", myMoney.amount, myMoney.type); Here is my code: static ...
user1929393's user avatar
  • 4,187
234 votes
8 answers
178k views

Are list-comprehensions and functional functions faster than "for loops"?

In terms of performance in Python, is a list-comprehension, or functions like map(), filter() and reduce() faster than a for loop? Why, technically, they run in a C speed, while the for loop runs in ...
Ericson Willians's user avatar
231 votes
7 answers
247k views

How to add leading zeros for for-loop in shell? [duplicate]

I have a basic number for loop which increments the variable num by 1 over each iteration... for (( num=1; num<=5; num++ )) do echo $num done Which outputs: 1 2 3 4 5 I'm trying to make it ...
Bruce Blacklaws's user avatar
228 votes
10 answers
110k views

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 ...
chakrit's user avatar
  • 61.3k
219 votes
18 answers
239k views

How to efficiently remove all null elements from a ArrayList or String Array?

I try with a loop like that // ArrayList tourists for (Tourist t : tourists) { if (t != null) { t.setId(idForm); } } But it isn't nice. Can anyone suggest me a better ...
Juan de Dios's user avatar
  • 2,753

1
2 3 4 5
1440