Questions tagged [while-loop]

A while loop is a control structure used in many programming languages to continuously execute a set of instructions as long as a particular condition is met.

In most computer programming languages, a while loop is a control flow statement that allows code to be executed repeatedly based on a given boolean condition. The while loop can be thought of as a repeating if statement.

The while construct consists of a block of code and a condition. The condition is evaluated, and if the condition is true, the code within the block is executed. This repeats until the condition becomes false. Because the while loop checks the condition before the block is executed, the control structure is often also known as a pre-test loop. Compare this with the do-while loop, which tests the condition after the loop has executed.

The syntax for the while loop for many computer languages is as follows:

while (true) {
    //do complicated stuff
    if (someCondition)
        break;
    //more stuff
}

(excerpted from http://en.wikipedia.org/wiki/While_loop, with minor changes)

There are several types of different while loops in modern computing. One of these loops is called a sentinel loop. This loop will run until a "sentinel" value is hit. An example follows in pseudo code (this example is a simple accumulator):

Initialize a data type to not the sentinel value 
while(data!=(sentinel value)){
do something

ask for more data (which will be put into the data variable)
}

See also: , , , and .

22538 questions
919
votes
18 answers

How to emulate a do-while loop?

I need to emulate a do-while loop in a Python program. Unfortunately, the following straightforward code does not work: list_of_ints = [ 1, 2, 3 ] iterator = list_of_ints.__iter__() element = None while True: if element: print element …
grigoryvp
  • 33,993
  • 56
  • 155
  • 263
703
votes
13 answers

Syntax for a single-line while loop in Bash

I am having trouble coming up with the right combination of semicolons and/or braces. I'd like to do this, but as a one-liner from the command line: while [ 1 ] do foo sleep 2 done
Brian Deacon
  • 19,494
  • 12
  • 36
  • 40
608
votes
5 answers

Why is “while ( !feof (file) )” always wrong?

I've seen people trying to read files like this in a lot of posts lately: #include #include int main(int argc, char **argv) { char *path = "stdin"; FILE *fp = argc > 1 ? fopen(path=argv[1], "r") : stdin; if( fp ==…
William Pursell
  • 174,418
  • 44
  • 247
  • 279
596
votes
23 answers

Which is faster: while(1) or while(2)?

This was an interview question asked by a senior manager. Which is faster? while(1) { // Some code } or while(2) { //Some code } I said that both have the same execution speed, as the expression inside while should finally evaluate to true…
Nikole
  • 4,511
  • 3
  • 14
  • 14
348
votes
12 answers

Else clause on Python while statement

I've noticed the following code is legal in Python. My question is why? Is there a specific reason? n = 5 while n != 0: print n n -= 1 else: print "what the..."
Ivan
  • 21,917
  • 6
  • 22
  • 21
283
votes
12 answers

How do I plot in real-time in a while loop using matplotlib?

I am trying to plot some data from a camera in real time using OpenCV. However, the real-time plotting (using matplotlib) doesn't seem to be working. I've isolated the problem into this simple example: fig = plt.figure() plt.axis([0, 1000, 0, 1]) i…
Chris
  • 7,745
  • 13
  • 39
  • 60
277
votes
34 answers

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…
djdd87
  • 63,008
  • 24
  • 149
  • 191
273
votes
6 answers

How can you run a command in bash over and over until success?

I have a script and want to ask the user for some information, but the script cannot continue until the user fills in this information. The following is my attempt at putting a command into a loop to achieve this but it doesn't work for some…
J V
  • 9,736
  • 7
  • 41
  • 64
256
votes
20 answers

Declaring variables inside or outside of a loop

Why does the following work fine? String str; while (condition) { str = calculateStr(); ..... } But this one is said to be dangerous/incorrect: while (condition) { String str = calculateStr(); ..... } Is it necessary to declare…
Harry Joy
  • 55,133
  • 29
  • 149
  • 204
247
votes
5 answers

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

I have a list consisting of like 20000 lists. I use each list's 3rd element as a flag. I want to do some operations on this list as long as at least one element's flag is 0, it's like: my_list = [["a", "b", 0], ["c", "d", 0], ["e", "f", 0],…
alwbtc
  • 23,407
  • 50
  • 123
  • 177
228
votes
3 answers

Java method with return type compiles without return statement

Question 1: Why does the following code compile without having a return statement? public int a() { while(true); } Notice: If I add return after the while then I get an Unreachable Code Error. Question 2: On the other hand, why does the…
Willi Mentzel
  • 21,499
  • 16
  • 88
  • 101
222
votes
21 answers

Are "while(true)" loops so bad?

I've been programming in Java for several years now, but I just recently returned to school to get a formal degree. I was quite surprised to learn that, on my last assignment, I lost points for using a loop like the one below. do{ //get some…
JHarnach
  • 3,754
  • 6
  • 38
  • 45
217
votes
8 answers

A variable modified inside a while loop is not remembered

In the following program, if I set the variable $foo to the value 1 inside the first if statement, it works in the sense that its value is remembered after the if statement. However, when I set the same variable to the value 2 inside an if which is…
Eric Lilja
  • 2,573
  • 4
  • 15
  • 13
189
votes
14 answers

How can I make sense of the `else` clause of Python loops?

Many Python programmers are probably unaware that the syntax of while loops and for loops includes an optional else: clause: for val in iterable: do_something(val) else: clean_up() The body of the else clause is a good place for certain…
alexis
  • 43,587
  • 14
  • 86
  • 141
163
votes
2 answers

How to break out of a loop in Bash?

I want to write a Bash script to process text, which might require a while loop. For example, a while loop in C: int done = 0; while(1) { ... if(done) break; } I want to write a Bash script equivalent to that. But what I usually used and as…
lulyon
  • 5,745
  • 7
  • 26
  • 46
1
2 3
99 100