This forum is now read-only. Please use our new forums! Go to forums

0 points
Submitted by Kristen von Clef
almost 11 years

What's a real world example for using "while" loops?

Just wanting to know, for understanding purposes, what an example of a use of a “while” loop in a program would be. (More than one would be appreciated, too!) Thanks!

Answer 513076b2e2ec491225007971

2 votes

Permalink

Any time your program needs to keep doing something (repeat the same or a similar action) until something happens and you don’t know in advance when or if that something happens, a while loop is useful. Every programming language has some sort of while loop construct, so I’m going to give you an example in pseudocode:

// music player loop:
while (user does NOT press stop AND NOT end of playlist) {
  get the next song
  play the song
}

// user input loop
ask user a yes-or-no question
get answer
while (answer is NOT "yes" AND answer is NOT "no") {
  repeat the question // this must be a fairly stupid user
}
points
Submitted by Alex J
almost 11 years

1 comments

Kristen von Clef almost 11 years

Thanks!

Answer 5130968aba280229e5008a49

1 vote

Permalink

while your game character is level 1, she can only do 5 points damage

while you press the accelerator, you do drive

while the timer is running, the timer counter is progressing…

etc

Sorry, I can only think in game terms, but I think these would all work with while loops..

points
Submitted by Guido Gautsch
almost 11 years

1 comments

Kristen von Clef almost 11 years

Thanks!