keko52
Cosplayer
2
MONTHS
2 2 MONTHS OF SERVICE
LEVEL 1
200 XP
There are cases in which a developer may want a program to repeat a certain function for a finite number of times. While loops allow the programmer to make a function repeat until certain conditions are met.
There are two common intended uses for loops. The first is to keep repeating a set of code until the user satisfies the criteria to exit the loop. The other is to repeat the code a certain number of times, just so that the programmer won't have to continuously write the same lines of code over and over.
Let's take the following line of code, for example:
while
(
i <
11
)
This line will repeat the code for as long as the value of i is less than 11. Combine that with two more lines of code and we have ourselves a loop that will repeat ten times.
This allows for the code to be run, i is increased, and then it is run again. Once i is no longer less than 11, the loop will exit.
Let's add a bit more code to make things interesting.
This prints to the screen all of the integers from 1 through 10, and displays their squares alongside them. You may run this and notice that it does not look very even (the digits don't all line up perfectly from top to bottom). I challenge you to separate while loops for 1-3, 4-9, and 10, to make all of the numbers line up perfectly from top to bottom.
Download
There are two common intended uses for loops. The first is to keep repeating a set of code until the user satisfies the criteria to exit the loop. The other is to repeat the code a certain number of times, just so that the programmer won't have to continuously write the same lines of code over and over.
Let's take the following line of code, for example:
while
(
i <
11
)
This line will repeat the code for as long as the value of i is less than 11. Combine that with two more lines of code and we have ourselves a loop that will repeat ten times.
- int
i =
1
;
- while
(
i <
11
)
- {
- System
.out
.println
(
"The value of i is "
+
i)
;
- i++;
//increases the value of i by 1 before the loop repeats
- }
This allows for the code to be run, i is increased, and then it is run again. Once i is no longer less than 11, the loop will exit.
Let's add a bit more code to make things interesting.
- public
class
squares
- {
- public
static
void
main(
String
[
]
args)
- {
- int
i =
1
;
- while
(
i <
11
)
- {
- System
.out
.println
(
i +
" squared is "
+
i *
i)
;
- i++;
- }
- }
- }
This prints to the screen all of the integers from 1 through 10, and displays their squares alongside them. You may run this and notice that it does not look very even (the digits don't all line up perfectly from top to bottom). I challenge you to separate while loops for 1-3, 4-9, and 10, to make all of the numbers line up perfectly from top to bottom.
Download
You must upgrade your account or reply in the thread to view hidden text.