Hello everybody,
It’s Michael, and today’s lesson will be on Java loops. For those who do not know, loops repeat groups of statements in Java by executing the same actions over and over until a certain condition is met. The block of code inside the loop is called the body, while each repeat of the loop is referred to as an iteration of the loop.
Loops are important because Java programs often need to repeat actions. For instance, if you were trying to make a step-counter program, you would need a loop to increase the step-count by 1 every time a step is taken. You would ideally want to keep increasing by 1 until a certain count is reached-let’s say 10,000 steps (though you could also make your step-counter loop infinite).
There are three types of loops-while, do-while, and for-which each have their own distinct functions.
First off, I’ll discuss the for loop. Here’s a program demonstrating the use of a for loop (source code below)-For loops demo.
package javalessons;
public class JavaLessons
{
public static void main(String[] args)
{
for (int i = 2; i <= 400; i*=2)
{
System.out.println(i);
}
}
}
The basic structure of the for loop goes like this:
- for (variable assignment; condition to end the for loop; updating action), followed by the body
- ALWAYS remember to write your loop in this order; the compiler will throw error messages if you try to do otherwise!
In this program, I am using a for loop to calculate successive powers of 2 and display the results from top to bottom. My variable assignment-int i=2-goes first so that the loop knows the starting condition (that I am starting off with 2). The condition to end the loop-i <= 400-goes next so that the loop knows where to end (the program will keep displaying powers of 2 until a number that is either the closest to 400 or exactly 400 is reached). The updating condition-i*=2-tells the loop how to update the output (keep multiplying i by 2 until the ending condition is met).
- By the way, you can put
i = i* 2 instead of i*=2 . Either will be accepted by the compiler, the latter is just convenient shorthand. The same logic goes for addition, division, and subtraction.
Now let’s try some sample output:
run:
2
4
8
16
32
64
128
256
BUILD SUCCESSFUL (total time: 0 seconds)
The program will display all the powers of 2 that are less than 400, starting with 2 and ending with the maximum power of 2 that is less than 400-296.
Next I’ll discuss the while loop, with a demo program (source code below)-
package javalessons;
import java.util.Scanner;
public class JavaLessons
{
public static void main(String[] args)
{
Scanner sc = new Scanner (System.in);
System.out.println(“Pick an even numbered year: “);
int year = sc.nextInt();
int baseYear = 2100;
while (year < baseYear)
{
if (year % 4 != 0)
{
System.out.println (year);
System.out.println(“Winter Olympics Year”);
}
else
{
System.out.println (year);
System.out.println(“Summer Olympics Year”);
}
year += 4;
}
}
}
The basic structure of the while loop goes like this:
- while (condition to keep while loop going), followed by the body.
- Variable declarations are always included outside of the while loop; ideally just above the line where the while loop begins.
In this program, I enter an even numbered year and the program will tell me if it’s a Winter or Summer Olympics year and based on that, it will tell me the next Winter/Summer Olympics years until 2100 (since my while condition was that the loop will keep going and increasing the year by 4 until 2100 is reached).
- If you’re wondering what the % means in Java, it means remainder. The statement
if (year % 4 != 0) executes the output in the body of the code if the year entered has a remainder and isn’t divisible by 4, since Winter Olympics years occur during even numbered years that aren’t easily divisible by 4 (2006, 2010, 2014, and so on). If the year entered is divisible by 4, then Summer Olympics years would be displayed, since they occur during even-numbered leap years (which are years divisible by 4)-think 2012, 2016, 2020 and so on.
Let’s try some sample output:
Output 1:
run:
Pick an even numbered year:
2014
2014
Winter Olympics Year
2018
Winter Olympics Year
2022
Winter Olympics Year
2026
Winter Olympics Year
2030
Winter Olympics Year
2034
Winter Olympics Year
2038
Winter Olympics Year
2042
Winter Olympics Year
2046
Winter Olympics Year
2050
Winter Olympics Year
2054
Winter Olympics Year
2058
Winter Olympics Year
2062
Winter Olympics Year
2066
Winter Olympics Year
2070
Winter Olympics Year
2074
Winter Olympics Year
2078
Winter Olympics Year
2082
Winter Olympics Year
2086
Winter Olympics Year
2090
Winter Olympics Year
2094
Winter Olympics Year
2098
Winter Olympics Year
BUILD SUCCESSFUL (total time: 10 minutes 55 seconds)
I chose an even-numbered non-leap year, 2014, and the program printed out all Winter Olympics years from 2014 until the Games happening right before the year 2100 (the 2098 Winter Games).
Output 2:
run:
Pick an even numbered year:
2020
2020
Summer Olympics Year
2024
Summer Olympics Year
2028
Summer Olympics Year
2032
Summer Olympics Year
2036
Summer Olympics Year
2040
Summer Olympics Year
2044
Summer Olympics Year
2048
Summer Olympics Year
2052
Summer Olympics Year
2056
Summer Olympics Year
2060
Summer Olympics Year
2064
Summer Olympics Year
2068
Summer Olympics Year
2072
Summer Olympics Year
2076
Summer Olympics Year
2080
Summer Olympics Year
2084
Summer Olympics Year
2088
Summer Olympics Year
2092
Summer Olympics Year
2096
Summer Olympics Year
BUILD SUCCESSFUL (total time: 3 seconds)
I chose an even-numbered leap-year, 2020, and the program printed out all Summer Olympics years from the year 2020 until the Games right before the year 2100 (which would be the 2096 Summer Games).
Output 3:
run:
Pick an even numbered year:
2110
BUILD SUCCESSFUL (total time: 3 seconds)
I chose a year greater than 2100-2110 and the loop doesn’t execute at all, since my initial response exceeded the base year.
The main difference between the while and for loops is that variable declarations and updating conditions (like incrementing variables) are done either in the body of the loop or outside the loop when dealing with while, but both of those things are handled in the constructor of the loop when dealing with for.
Finally, the last loop I will discuss is the do-while loop, which is very similar to the while loop, except that the body of a do-while loop always runs at least once, while the body of a while loop might not run at all. This is because the body of the do-while loop comes before the constructor, not after.
Here’s the basic structure of the do-while loop:
- do {body of loop} while (condition to keep loop running)
- After each iteration, the condition is checked to see if it still holds true. As long as it does, the loop keeps running.
Here’s a sample program (code below)-Do-while loop demo:
package javalessons;
import java.util.Scanner;
public class JavaLessons
{
public static void main(String[] args)
{
Scanner sc = new Scanner (System.in);
System.out.println(“Pick a number: “);
double number = sc.nextDouble();
double base = 1000;
do
{
number *= 1.05;
System.out.print (number + ” , “);
} while (number <= base);
}
}
In this program, I enter a number and the do-while loop will calculate 5% growth so long as the number being increased by 5% is less than the base of 1000. I could’ve written the program using a while loop, but there would’ve been a chance that the while loop might not have run at all, but the do-while loop will run at least once, which I wanted (plus I felt it was important to discuss).
Let’s try some sample output:
Pick a number:
456
478.8 , 502.74 , 527.8770000000001 , 554.2708500000001 , 581.9843925000001 , 611.0836121250002 , …..
I typed in 456, and the program kept displaying 5% increases starting with the first increase-478.8-until the program reached a number that was either 1000 or the closest possible calculation to 1000.
Now, when dealing with Java loops, one thing you should watch out when writing your code is the infinite loop, which are loops that don’t end.
Infinite loops can be caused by something as simple as a sign. Here’s an infinite loop from the do-while example in this post (code first, then output)-:
package javalessons;
import java.util.Scanner;
public class JavaLessons
{
public static void main(String[] args)
{
Scanner sc = new Scanner (System.in);
System.out.println(“Pick a number: “);
double number = sc.nextDouble();
double base = 1000;
do
{
number *= 1.05;
System.out.print (number + ” , “);
} while (number >= base);
}
}
run:
Pick a number:
45600
47880.0 , 50274.0 , 52787.700000000004 , 55427.08500000001 , 58198.43925000001 , 61108.361212500015 , 64163.779273125016 , 67371.96823678126 , 70740.56664862033 , 74277.59498105134 , 77991.47473010392 , 81891.04846660912 , 85985.60088993958 , 90284.88093443656 , 94799.12498115838 , 99539.08123021631 , 104516.03529172714 , 109741.8370563135 , 115228.92890912917 , 120990.37535458563 , 127039.89412231492 , 133391.88882843067 , 140061.4832698522 , 147064.55743334483 , 154417.78530501208 , 162138.6745702627 , 170245.60829877583 , 178757.88871371464 , 187695.78314940038 , 197080.5723068704 , 206934.60092221393 , 217281.33096832462 , 228145.39751674086 , 239552.66739257792 , 251530.3007622068 , 264106.81580031716 , 277312.15659033303 , 291177.7644198497 , 305736.6526408422 , 321023.4852728843 , 337074.6595365285 , 353928.39251335495 , 371624.8121390227 , 390206.05274597387 , 409716.3553832726 , 430202.1731524362 , 451712.28181005805 , 474297.89590056095 , 498012.79069558904 , 522913.4302303685 , 549059.1017418869 , 576512.0568289813 , 605337.6596704304 , 635604.5426539519 , 667384.7697866495 , 700754.008275982 , 735791.7086897811 , 772581.2941242702 , 811210.3588304837 , 851770.876772008 , 894359.4206106084 , 939077.3916411388 , 986031.2612231958 , 1035332.8242843556 , 1087099.4654985734 , 1141454.4387735021 , 1198527.1607121774 , 1258453.5187477863 , 1321376.1946851755 , 1387445.0044194343 , 1456817.2546404062 , 1529658.1173724267 , 1606141.023241048 , 1686448.0744031004 , 1770770.4781232555 , 1859309.0020294185 , 1952274.4521308895 , 2049888.1747374341 , 2152382.583474306 , 2260001.7126480215 , 2373001.7982804226 , 2491651.8881944437 , 2616234.482604166 , 2747046.2067343746 , 2884398.5170710934 , 3028618.442924648 , 3180049.3650708804 , 3339051.8333244245 , 3506004.4249906456 , 3681304.646240178 , 3865369.8785521872 , 4058638.372479797 , 4261570.291103787 , 4474648.805658977 , 4698381.245941926 , 4933300.308239022 , 5179965.323650974 , 5438963.589833523 , 5710911.7693252 , 5996457.35779146 , 6296280.225681033 , 6611094.236965085 , 6941648.94881334 , 7288731.396254007 , 7653167.966066708 , 8035826.364370043 , 8437617.682588546 , 8859498.566717973 , 9302473.495053872 , 9767597.169806566 , 1.0255977028296895E7 , 1.076877587971174E7 , 1.1307214673697326E7 , 1.1872575407382194E7 , 1.2466204177751305E7 , 1.308951438663887E7 , 1.3743990105970815E7 , 1.4431189611269357E7 , 1.5152749091832826E7 , 1.5910386546424467E7 , 1.6705905873745691E7 , 1.7541201167432975E7 , 1.8418261225804623E7 , 1.9339174287094854E7 , 2.0306133001449596E7 , 2.1321439651522078E7 , 2.2387511634098183E7 , 2.3506887215803094E7 , 2.468223157659325E7 , 2.5916343155422915E7 , 2.7212160313194063E7 , 2.8572768328853767E7 , 3.0001406745296456E7 , 3.150147708256128E7 , 3.3076550936689347E7 , 3.4730378483523816E7 , 3.646689740770001E7 , 3.829024227808501E7 , 4.020475439198926E7 , 4.2214992111588724E7 , 4.432574171716816E7 , 4.654202880302657E7 , 4.8869130243177906E7 , 5.1312586755336806E7 , 5.387821609310365E7 , 5.6572126897758834E7 , 5.9400733242646776E7 , 6.237076990477912E7 , 6.548930840001808E7 , 6.876377382001899E7 , 7.220196251101995E7 , 7.581206063657095E7 , 7.96026636683995E7 , 8.358279685181947E7 , 8.776193669441044E7 , 9.215003352913097E7 , 9.675753520558752E7 , 1.0159541196586691E8 , 1.0667518256416026E8 , 1.1200894169236827E8 , 1.1760938877698669E8 , 1.2348985821583603E8 , 1.2966435112662785E8 , 1.3614756868295926E8 , 1.4295494711710724E8 , 1.5010269447296262E8 , 1.5760782919661075E8 , 1.654882206564413E8 , 1.7376263168926337E8 , 1.8245076327372655E8 , 1.915733014374129E8 , 2.0115196650928354E8 , 2.1120956483474773E8 , 2.2177004307648513E8 , 2.328585452303094E8 , 2.4450147249182487E8 , 2.5672654611641613E8 , 2.695628734222369E8 , 2.830410170933488E8 , 2.971930679480162E8 , 3.12052721345417E8 , 3.276553574126879E8 , 3.4403812528332233E8 , 3.6124003154748845E8 , 3.793020331248629E8 , 3.9826713478110605E8 , 4.181804915201614E8 , 4.390895160961695E8 , 4.6104399190097797E8 , 4.840961914960269E8 , 5.0830100107082826E8 , 5.337160511243697E8 , 5.604018536805882E8 , …
As you can see, I changed the sign in the do-while loop from “less than or equal to” to “greater than or equal to”. If you type a number greater than the base of 1000, then your loop can go on and on, as you can see here (of course, you can always hit the stop button).
Before I go, here are the answers to the number conversion problems from my previous post Java Lesson 5: Java Numbering Systems:
Binary-to-Decimal
- 0110-6
- 10011-19
- 1100001-97
- 1001001-73
Octal-to-Decimal
- 523-339
- 3455-1837
- 123023-42515
- 2346523-642387
Hexadecimal-to-Decimal
- 4BF-1215
- 67AC-26540
- AF12-44818
- 192DCC-1650124
Thanks for reading.
Michael