A **loop** is a sequence of statements which is specified once but which may be carried out several times in succession.
-7
votes
1answer
124 views
Java: Why's this For-Loop thousands of times slower?
So I have a simple method I'm calling millions of times a second, and I noticed that it was taking 16% of all processing time!!
The offensive routine is as follows:
public void placeHolder(){
...
16
votes
7answers
2k views
Should <= and >= be avoided when using integers, such as in a For loop? [on hold]
I have explained to my students that equal-to testing is not reliable for float variables, but is fine for integers. The textbook I am using said that it is easier to read > and < than >= and ...
-1
votes
0answers
10 views
PyQt: How to dynamically call objectNames in a loop? [migrated]
I created 9 QPushButtons which objectName's are E1, E2, E3, ..., E9.
Now, I want to update their text field with strings I get from a database, so I want to do something like this:
...
-1
votes
4answers
144 views
Nested For Loops JavaScript
I have an app which gets data from the database (MongoDB) in JSON format. The returned data contains nested arrays and I want to access the values in the nested arrays. The returned JSON format looks ...
2
votes
1answer
93 views
printing in methods vs printing in the main/driver class
I'm fairly new to programming and am currently creating a blackjack game in Java.
I've progressed quite well, although could use some pointers with regards to the best way to implement a method.
At ...
0
votes
2answers
186 views
Do some built-in functions loop behind the scenes?
I mostly code in C# & VB, but I think this question is pretty universal. I try to limit loops to increase performance. For instance, string functions that split the string into an array, or do a ...
-1
votes
0answers
15 views
How we use while loop in latex to input multiple files in main document [migrated]
I am trying to input multiple files from different directories in my main latex document and I want to use while loop to do that so that all .tex files
can be read from a directory. Please give your ...
1
vote
2answers
95 views
Load to list in one loop and then process list in another or do it all at once
I have a dataset full of rows that I must initialize into myclass and then process.
I am currently looping through each row in the dataset, initializing a new instance of myclass, then adding that ...
-3
votes
3answers
93 views
Best way to handle variables used in a for loop? [duplicate]
From previous experience, I had always thought that, if you are going to use variables inside of a for loop, it was much better to declare them outside of the loop vs. inside the loop itself. I ...
20
votes
8answers
3k views
At what point is it taboo to have loops within loops?
Just curious. The most I have ever had was a for loop within a for loop, because after reading this from Linus Torvalds:
Tabs are 8 characters, and thus indentations are also 8 characters.
There ...
14
votes
2answers
1k views
Filtering foreach loops with a where condition vs continue guard clauses
I've seen some programmers use this:
foreach (var item in items)
{
if (item.Field != null)
continue;
if (item.State != ItemStates.Deleted)
continue;
// code
}
instead ...
109
votes
11answers
12k views
Is there anything that can be done with recursion that can't be done with loops?
There are times where using recursion is better than using a loop, and times where using a loop is better than using recursion. Choosing the "right" one can save resources and/or result in fewer lines ...
-1
votes
1answer
170 views
eradicating the array = loop mindset [closed]
I have noticed a common issue in code reviews, that takes this form:
// "arr" is an array
for (i = 0; i < arr.length; ++i) {
if (i == 3) {
// do something with arr[i]
}
if (i ...
6
votes
2answers
2k views
Is using for loop syntax for a “with(variable)” block an anti-pattern?
I fooled around with for-loops, remembered the with keyword from delphi and came up with following pattern (defined as a live template in IntelliJ IDEA):
for ($TYPE$ $VAR$ = $VALUE$; $VAR$ != null; ...
2
votes
2answers
133 views
Did labelled loops pre-date for loops?
Was the first implementation of looping control flow effectively the goto (or something like a labelled JMP in assembler) or was there another syntactic construction?
for (für) was introduced in ...
0
votes
0answers
65 views
Is there a school of thought where while(1) or while (true) is a code smell? [duplicate]
My employer requires code reviews for all devs, and new employees are required to to have their code reviewed by a senior dev. Initially, trainees get to pick a small project they are working on and ...
0
votes
1answer
108 views
Code readability on non-trivial loop variables [closed]
My co-worker and I discussing about the code readability on simple loops. Suppose a method takes an integer parameter and does some operation on the elements of an array depending on the parameter. ...
-2
votes
2answers
78 views
Find index of string in an array of strings where overlap could occur
I am having some trouble writing a variant of sub-string search. Essentially the goal is to write a method that can perform sub-string search except that the source data is in an array of Strings ...
0
votes
2answers
129 views
Refactoring method with nested loops and 6 variables [duplicate]
I have a method which implements a small section of a (complex) algorithm. This algorithm has taken me several weeks to perfect and is by far the fastest method I can find. The method in question has ...
3
votes
2answers
666 views
Using 'reduce' vs 'for' loop for returning boolean [closed]
I was wondering what people think about using a reduce function vs loop for returning true if a condition exists.
Example:
var a = [1, 5, 7, 4, 2, 5, 3];
var greaterThan5 = a.reduce(function(prev, ...
1
vote
2answers
89 views
Factored out loop control in Python
I have a for loop in python like this:
for item in items:
onwards = make_flow_decision(item)
if onwards == 'break':
break
elif onwards == 'continue':
continue
elif ...
3
votes
2answers
157 views
Handling exceptions in a loop without breaking the loop (try to process all members)
Scenario:
I have a loop that iterates over an Array of COM objects and does some work using them.
My fear, working with COM objects, is that some exception will creep up (possibly on another ...
0
votes
2answers
403 views
Loops to create nested loops
Is there a way to use a loop to create more nested loops? E.g. Doing this
for (int i = 0; i < iterations; i++)
{
//Do stuff
for (int ii = 0; ii < ...
0
votes
1answer
105 views
Recursion, iteration, and …? [closed]
Here are three common code structures that apply a function multiple times:
foo(x) {
if basecase(x) return k else return foo(g(x))
}
uses recursion.
for i in 0..10 {
n *= bar(i)
}
uses ...
0
votes
0answers
112 views
Does loop unrolling on a JIT platfrom (.NET or JVM) provide any benefit
I know in C, you can use loop unrolling (unwinding) to help reduce branching in your code but at the expense of program size. That seems to work when you compile to a target machine, however, does it ...
2
votes
1answer
137 views
Break big method into 2 methods, first containing a “for” loop and second a “break”
A method grew too big for its own good, and I need to break it up into two separate methods.
def big_method(dct):
# Initial code
# ...
for i in dct:
# More code
# ...
...
2
votes
2answers
218 views
How to iterate between these elements
I have an array of elements:
int[] elem = new int[] {A, B, C};
I need to calculate the sum of ALL the combinations of those elements, where only some of the elements can be optionally selected. I ...
-2
votes
1answer
115 views
How to name variables without plural in a for-each loop? [closed]
How do you name loop variables when the list item is named after something without a plural? For instance (in python): [x for x in sheep]. x is not a great name, but sheep have/has no plural that ...
8
votes
7answers
1k views
provability of while loop vs for loop
I have this teacher, he's quite smart (sometimes, haha) he said good programmers try to use while loops instead of for loops. the reason he gave for this is because while loops can be proven, as in, ...
0
votes
1answer
177 views
Sorting Sentences by New Words in Each
A very useful learning tool I stumbled across for Chinese was a massive list of sentences that, barring the first 10 or 15, only differed by the ones before by one or two words, or at least as few as ...
1
vote
1answer
553 views
adding the digits of a number
I am trying to write a program that asks the user for a decimal number and then calculates the sum of its digits. for example if the number is 123.25 then the sum will be 1+2+3+2+5=13.
I decided to ...
2
votes
3answers
241 views
The recommended Way to exit a Loop
Occasionally - but recurringly - I face the following loop pattern problem:
CodeSnippet1
DO WHILE LoopCondition //LoopCondition depends on some pre-calculation from CodeSnippet1
CodeSnippet2 ...
2
votes
1answer
41 views
Comparing path strings against list of rules
I am trying to find a way to enhance a filtering algorithm. I am developing a backup software that enables users to specify custom filters to exclude unwanted files/directories.
Currently when trying ...
1
vote
1answer
190 views
Most efficient way to calculate number of iterations to run
Let's say I have a batch process that executes 4 times per loop, and needs to execute a total of 9 items.
Example:
Iteration 1 executes 4 items of 9, leaving 5 left
Iteration 2 executes 4 times of ...
2
votes
0answers
69 views
Loop Unfolding and Named Significant Bits
I've been writing a Parser Compiler for the last seven or so years, and I recently got to the point (yet again, never satisfied) of structuring the portion dealing with the portions of the language ...
-3
votes
3answers
1k views
Real life scenario of why we would use loops [closed]
I am going to school to become a programmer, and I am doing some homework and I have a question. It wants me to give an example of why we would use loops in the real world. And I was thinking about ...
2
votes
1answer
110 views
Proper way to refactor multiple if based conditions [duplicate]
I took over a large legacy code base. It has a code like this:
if ($route == 'login' || $route == 'logout' || $route == 'forgot-password') {
return;
}
if ($loggedInUser == false && ...
0
votes
4answers
316 views
How to prove that this while loop calculates n^2
I'm studying for my exam of logic later this week and I have to prove that this while loop:
i := 0
s := 0
while i < n do
i := i + 1
s := s + (2*i -1)
calculates n^2. This question is ...
8
votes
5answers
6k views
How to structure a loop that repeats until success and handles failures
I am a self-taught programmer. I started programming about 1.5 years ago. Now I have started to have programming classes in school. We have had programming classes for 1/2 year and will have another ...
4
votes
5answers
2k views
Are there real-life usage and applications for “do while” loops? [closed]
When I see for and while loops all over production codes and mammoth projects, the last time I saw a do while loop is for a university assignment involving menu-based console input program. About 50 ...
1
vote
3answers
97 views
Using higher order functions to apply m out of M filter's and then transform data of size n?
Total no: of filters possible is M . User can select m filters where m <= M . A typical example is files from a folder , he could say modified between so and so date , start with so and so and so ...
4
votes
1answer
858 views
Functional programming for loop side effect
I am trying to get my head around as to why having a local variable or a for loop inside a function is not considered to be pure functional programming.
Given this function:
int as_int(char *str)
{
...
1
vote
3answers
156 views
Use of for loop conditional statement unrelated to iterating variable
Is it considered decent form to write code like this:
int done = 0;
for (x = 0; !done; x++) {
... something involving 'x', that might end early ...
if (!(x < max))
done = 1;
}
...
0
votes
1answer
82 views
How can I iterate over two loops of mismatched sizes, keeping them in sync?
I have a database table in which each row is one movie (with fields like 'title', 'director' and 'writer'), and a related table where each row is one screenshot from a movie (with the fields ...
4
votes
2answers
693 views
Loop runtime question
I had an exam today and I feel that I did pretty well, except I could not for the life of me figure out what appears to be an unbelievably simple question.
We were asked to give theta notation run ...
-4
votes
4answers
374 views
Why are for loops needed? [duplicate]
It seems to me that a while loop with the appropriate break statements can replace them entirely. I understand that a break statement may not feel as "smooth" as a for loop that does something a ...
1
vote
2answers
1k views
Infinite while loop CPU usage
I'm coding an script in C, which is going to check constantly an array of events, the idea is to check if the Date and time of certain event is equal to de current time and trigger something, i'm ...
5
votes
2answers
495 views
Why do some programming languages have break statements, but not higher-order break statements? [closed]
I may have been exposed to exactly the wrong languages, but though many have loops and break statements, none of the languages I am familiar with have higher-order break statements¹. While a regular ...
42
votes
2answers
5k views
How do I move away from the “for-loop” school of thought?
This is a rather conceptual question, but I was hoping I could get some good advice on this. A lot of the programming I do is with (NumPy) arrays; I often have to match items in two or more arrays ...
-1
votes
1answer
106 views
Finding “spare time” in a day from within a list of events
I have a list of events which is always sorted chronologically. The start time is always followed by the end time. Times are strings formatted as 'HHmmss'.
// list of events
var events = [
...