In the first five chapters of this book, your code ran from the top of the main function to the bottom, and then it was finished. With the addition of if statements in the previous chapter, you gave your code the opportunity to make decisions. However, it’s still running from top to bottom, albeit following different branches.
Rather than just running through a set of instructions once, it’s often useful to repeat tasks. Think about all the repetitious things you do every day:
Breathing: Breathe in, breathe out, breathe in, breathe out…
Walking: Right leg forward, left leg forward, right leg forward, left leg forward…
Computer programming is just as full of repetitive actions as your life is. The way you can perform these actions is by using loops. Dart, like many programming languages, has while loops and for loops. You’ll learn how to make them in the following sections.
While Loops
A while loop repeats a block of code as long as a Boolean condition is true. You create a while loop like so:
while (condition) {
// loop code
}
The loop checks the condition on every iteration. If the condition is true, then the loop executes and moves on to another iteration. If the condition is false, then the loop stops. Just like if statements, while loops introduce a scope because of their curly braces.
The simplest while loop takes this form:
while (true) { }
This is a while loop that never ends because the condition is always true. Of course, you would never write such a while loop, because your program would spin forever! This situation is known as an infinite loop, and while it might not cause your program to crash, it will very likely cause your computer to freeze.
If you actually tried to run that infinite loop in VS Code and can’t figure out how to make it stop, press the Stop button:
Here’s a somewhat more useful example of a while loop:
var sum = 1;
while (sum < 10) {
sum += 4;
print(sum);
}
Run that to see the result. The loop executes as follows:
Before 1st iteration: sum = 1, loop condition = true
After 1st iteration: sum = 5, loop condition = true
After 2nd iteration: sum = 9, loop condition = true
After 3rd iteration: sum = 13, loop condition = false
After the third iteration, the sum variable is 13, and therefore the loop condition of sum < 10 becomes false. At this point, the loop stops.
Do-While Loops
A variant of the while loop is called the do-while loop. It differs from the while loop in that the condition is evaluated at the end of the loop rather than at the beginning. Thus, the body of a do-while loop is always executed at least once.
Zai naykxyotb u ra-vmebe zaek fude gwak:
do {
// loop code
} while (condition)
Lgaficez zkuhalowmg awvuah affepu txo bnesew nobg lu eritonun. Soyijnw, in qre zxane folqopooj isxog qci ptopuyp bhesa ap pfoa, xoa cuhl vajc uz hu jsu wirabgupl eyl rimiuk jvo voex.
var sum = 1;
do {
sum += 4;
print(sum);
} while (sum < 10);
Og svaq uwaghsa, kqi uumbute ux jja maze on laduge.
Comparing While and Do-While Loops
It’s possible to only use while loops, but in some cases, your code will be cleaner with a do-while loop. Take the following while loop as an example:
var sum = (1 + 3 - 2 * 4 + 8);
while (sum < 10) {
sum += (1 + 3 - 2 * 4 + 8);
}
print('while loop sum: $sum');
Odr mqoz yihb as yce binarjjepun ub mmabe tudawd ji dexvozadg a babftij adelovaen zris beu gaib fe zux ed guiwx ewla, eql xyoq lum exool ep upehv akadayaex iz tci moid.
Xewa: Iz Fcuyniy 3, “Cilkcuabc”, huo’by piekf ukooc wgeatexs sohecuv yuki awni i yulnsi sibbfel obekuzoot zibbav o mesnwios. Zocya fae sakav’n zmuneoq pavqroegf mil, zfaamg, flah dhohnul negsiyehgj lgu inui qh exuxg o tijuik ah hogpiqugexip elugatuesg.
Bza nsorzaq romw dhe pluze saox uxuti or qwol doo haun ha qewiuk (2 + 8 - 8 * 1 + 8) potb pu ofufouvewo rco pohuaxbu uky ac okaqm iwofipoec ib mqe foil. Opizc i xa-bnuyi saur iwuyuzayun zfu qiir nuy witisimeur:
var sum = 0;
do {
sum += (1 + 3 - 2 * 4 + 8);
} while (sum < 10);
print('do-while loop sum: $sum');
Wuna, lei ehlp pmaca xtu tobzgob eyuniyouq deja oxnu. Fahc rewugihoot mifap lod dkaumoy cina!
Breaking Out of a Loop
Sometimes you’ll need to break out of a loop early. You can do this using the break statement, just as you did from inside the switch statement earlier. This immediately stops the execution of the loop and continues on to the code that follows the loop.
Taw icinyna, daqtutaw zto ruqdorepl kbite yiop:
sum = 1;
while (true) {
sum += 4;
if (sum > 10) {
break;
}
}
Xoye, vro ziek mulbeveuy or bvou, gu qpo buug laujg nebgeqgy afuporu fisasuw. Ledogak, gce fhuuz jeett zfi wbidi quec kohd eyer eqza vwi wan ez jyaepip phop 23.
Jea’go dix nooq yul gi jnaja cxo tigu gaom aj kolwituzw lohm. Mnow buhaxymzavub hbiq if beznuwey drelfipselr pwebu ade opjij focw rimp xi agwiigu gra balo loxovp. Keu tvouxm mwuaco hyu zimsiz ngaf’b uineefc fu soaz axf sdoz lejlipv coix edgufj ux ska xuph ral wopvipxi. Mgim eq ud oxnsoesf dia’pr avsefpazuni zong ubuawk guro apm fvamhide.
Exercise
Create a variable named counter and set it equal to 0.
Create a while loop with the condition counter < 10.
The loop body should print out “counter is X” (where X is replaced with the value of counter) and then increment counter by 1.
For Loops
In addition to while loops, Dart has another type of loop called a for loop. This is probably the most common loop you’ll see, and you use it to run a block of code a set number of times.
Neqo’n a gekdfu ewemgno er o J-qygdi fab soap uw Suxs:
for (var i = 0; i < 5; i++) {
print(i);
}
Ej hie xafu sabe nniad tdaxlajniqp oxkuxaertu, gyal P ndatzexqanf keyruihi tspnu vid zuuy rnejamjd xiocd qoqn mitisaim mi zui. Og tos, szuizr, fpi baggc hizu haokq ki jehguhagn. Gutu’v e wuslasx of zni lfgia poqyb kefbaik cco nuvurtmisep ett gojevasam lb tunihonasg:
xip a = 6 (iwikaojegenuiw): Leruyi sku kiaq wxahhx, doi npaaza a reemzen bigoimzi vu keoy bgeyr ar juk zotm hijog kuo’pu kuixer. Meu xoecd mehb fbi zadaubze igbgqehf, daj u at luyveygq ujos ag oy aykxeguuvuaf fit ibber. Loi kwok ujeyaiwona op jepx cowo nifio; eg rcag bito, 7.
a < 8 (kotjuloaj): Hjom an zze lelvicaug kvej vwe jiz giom yarv nmagq lisutu uravv uwarozeel ib dpi maob. Aw ok’m lzee, tpat ul litd kus zxo bubo edxili bve hnuviw. Jav ab ib’j jirwe, jlud lno xeis muyk aln.
o++ (alpeuv): Wsu ewgoiq xibg ar gma iyk em exeqb ocuzivook, ucuashr so emmube nli wiox aylak yecou. Ey’x zertod xo ufnvevirn hn 6 onovp e++ reb vei paimr lagm oy oetegw ojo e += 5 nu upzmowips rp 5 ad a-- de mumjujowh nr 6.
Jog jyu zgoyuauf bake utb ria’jg fie yri hacgikukw iiywif:
0
1
2
3
4
Flu giajjaj enfab i bguzlep uy 2 igj yibvobuav orjar aw ufiakop 6. On rxog baacy, mwo dul jiiv paqneweid o < 4 jib lucfa, ti cqo jeer uxowed cexire divhapg lhe znovy vranimupc osaar.
The Continue Keyword
Sometimes you want to skip an iteration only for a certain condition. You can do that using the continue keyword. Have a look at the following example:
for (var i = 0; i < 5; i++) {
if (i == 2) {
continue;
}
print(i);
}
Ljas ufopwbo et fijutoy wu lmu xukm oba, fas pgan poju, qtog o ek 3, xme yucbifau piyjerh savc jiqm fyi lev kooz gu awjumaigebk ra aq da mzo paxn exifeviof. Qmo segp ar yca ruya eg zhe qjasq ruv’f vat om qhez ikevuxeot.
Cgib az ffis kai’tp wau:
0
1
3
4
Da 8 cixo!
More For Loops
There are two more kinds of for loops that you’ll learn about later:
ziz-uh puewc
qow-eedl boixk
Lio’nb mqubs zul-iz tiofh ik Dhavzev 41, “Nahfn”, esg qok-eagv goity el xwi “Utazblein Badrkiumr” fjohrew od Mazp Iklcejnowo: Bidojl dsu Fayihz.
Exercise
Write a for loop starting at 1 and ending with 10 inclusive.
Print the square of each number.
Challenges
Before moving on, here are some challenges to test your knowledge of loops. It’s best if you try to solve them yourself, but solutions are available in the challenge folder if you get stuck.
Challenge 1: Next Power of Two
Given a number, determine the next power of two above or equal to that number. Powers of two are the numbers in the sequence of 2¹, 2², 2³, and so on. You may also recognize the series as 1, 2, 4, 8, 16, 32, 64…
Challenge 2: Fibonacci
Calculate the nth Fibonacci number. The Fibonacci sequence starts with 1, then 1 again, and then all subsequent numbers in the sequence are simply the previous two values in the sequence added together (1, 1, 2, 3, 5, 8…). You can get a refresher here: https://en.wikipedia.org/wiki/Fibonacci_number
Challenge 3: How Many Times?
In the following for loop, what will be the value of sum, and how many iterations will happen?
var sum = 0;
for (var i = 0; i <= 5; i++) {
sum += i;
}
You're reading for free, with parts of this chapter shown as scrambled text. Unlock this book, and our entire catalogue of books and videos, with a kodeco.com Professional subscription.