The ability to repeat tasks, such as statements, in computer
programming really helps allow the programmer to represent just about any real
life situation, thus making loop statements very important. Loop statements are written using either FOR
or WHILE, and are extremely helpful. The
number of possibilities is almost endless.
However, even though they are great programming tools, if you’re new to
writing code like me, you may experience a bit of a struggle getting used to
properly using them.
A WHILE
loop is sort of like an IF statement.
“An IF statement looks at the test one time and then maybe executes the
body once. The while loop extends this
idea, executing the body again and again, checking the test each time.”
(Parlante, 2012, fourth paragraph, second sentence). Parlante goes on to include a WHILE loop
consists of three things: a test, work, and an increment. WHILE loops differ than FOR loops in that the
number of repetitions is not known exactly at first. It’s even possible for a WHILE loop to repeat
an infinite number of times. A real life
example of a WHILE loop might be:
While there are still more grocery items on my list
Find
item
Cross
off my list
Endwhile
“A FOR
loop is a variant of the WHILE loop, specialized to deal with a particular
looping problem.” (Parlante, 2012, sixth section, first sentence)What that
means is FOR loops are used when you know exactly how many steps you take to
accomplish your loop. An example of a
FOR loop would be seen in the code written to represent shuffling and dealing
cards. You would have a set number of
cards to shuffle, therefor you’d have a finite number of repetitions. For example:
For cards 1 to 52
Shuffle
cards
Endfor
Reference
Parlante, N. (2012). CodingBat Java For While Loops.
Retrieved May 12, 2015, from
http://codingbat.com/doc/java-for-while-loops.html
0 comments :
Post a Comment