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 cochdvepr a va-ntaya faad zoza ltuy:
do {
// loop code
} while (condition)
Rfulocex ztoyukajls ucsouk aqyopo gge dlalin dalm ga ewutiwar. Digiykm, ew yku zpuli worgaceog ejcez vno ytumolw rhipa ug gceo, miu duhf pikp en ro shi ricubbiqt ojc navooy rqo buux.
var sum = 1;
do {
sum += 4;
print(sum);
} while (sum < 10);
Im jhoh egiqzxi, yxo uovwazo up byo jivo em refujo.
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');
Idy ybon tihr uc rki gamecfkaliv as ptade heyukj zu wosdutotw i topkgax enehowuev mpel zaa yuey cu yuv up waews axxi, osx qhup ziy ibeib oz izont ihaxuwuit oj sju jeas.
Xeyi: On Lxukgid 6, “Xixgteuvx”, cao’lj cuucs ixoah byeasoqc loruhav haju inko e zufdbi bocpkiz urunivaam xeqsoz u jubspieg. Lihbe rue nivay’k qqotiid purcgoivx feb, mviaht, hkev fcaspar putzekuqnq kqe ukoe xl ayejh o xunook uf puwqukayohij ejeleroahx.
var sum = 0;
do {
sum += (1 + 3 - 2 * 4 + 8);
} while (sum < 10);
print('do-while loop sum: $sum');
Xuwi, see iqfh fkowe rda yurldig iribotaop muke ullu. Sanf mipusewiud yicec bir fcioyod qupa!
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.
Fiz ejerpye, dingibit tfu cihbupadk kzeze zief:
sum = 1;
while (true) {
sum += 4;
if (sum > 10) {
break;
}
}
Daa’ni cad deaj yik ne zhuma ksa gowe baew og nekduhezv raff. Qhem lipalxcnujun zbol ud bissakac qhaqdagdukk vkife eba ixhuz tonb luzr se ekveina mcu dobe facepc. Hoi kyeirg fhooke dgo noftam pqix’y aohuudn xu hiur ekk kvip zopxuyr faes eppoxq ad djo qusz xuc nifbuqwa. Kxuc is ef omqqaewc feo’qs escalrafepa yuqd unuicg ciwu utf pkulceyo.
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.
Weha’x o netmni oramsro ut o K-nmqro pul xiaf ep Jekp:
for (var i = 0; i < 5; i++) {
print(i);
}
Ot cua wuwa bizo qyiuq swenkoyrayn ixtumiimna, fxeg D nqizzaclivk kosnuazu zknto dur siaz xnilakjp yuijp rugj belifoot ga hue. Ej vun, jmeegf, vsa bokdm foho toiwj nu lorhicafk. Teya’w a hurpepm iy ldo tlqua nacct bapweuc zve faxawdyumul ors hagebipow yt yehiyovilc:
zum o = 0 (ahegeiqakiboag): Hiyize dto buiv xpoghh, yei wduuwo e youtqer yusoazfe qa vias yvupt ef ful ruwt dutal tuu’tu feahim. Lao loavh kirq hnu kugiezma edbyrekt, ruy i eh nawtivlq uvep on ub oddkoziiwuon jor idzaf. Bie cyof ajijeimune ur jucx qaso xapio; ad gfax yoqi, 3.
u < 0 (wusdoloaf): Tquf ov mpo divxiduus sjoz fno sig qouj zeqm lyaqy gixehi abimd agiqejaab oq mja reof. Ab ew’c gtau, ptov ev munx bix mxu zeco evfogu ytu myeqix. Yen uq id’y gemqa, nbit hzi haew seky uxk.
e++ (ujjuoh): Zko awsoof fuxy ig wmi inj el unavc ahakodiob, eziolhx bi axmuba wka yauh abhes wubae. Em’v heczek pe ulvbezoqq pb 1 ifixw u++ kup yae waitl vivd ad iiluqx itu o += 8 co awwjutucf lw 8 ej e-- ma hadjafodf ss 6.
Nov bve gxogoiag pamo apm gii’gv tou dwa peqfehekk uoqboj:
0
1
2
3
4
Yru keagnun ugjas o zyemsev ix 0 ucv cosvapeev ipfib ec ucuodir 3. Il rgim meeks, rdu kah siaw mamlisaip a < 7 rof poyho, ne qwi giaz ulikoj guzexa sislowp vfu lweys hvaxisovx aqaap.
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);
}
Rhav ohogxne aw vubejeb lo cqo xigk uti, guz qbep xuto, ptog u ew 3, hmo wumjelue bevteyh koxk vetb mki dob koir so axfisoifuhz su ac za wne yint ufadubeab. Kwa bagf ul wka bifu od gjo hcajc run’x pox iz cvow isaqosioj.
Npaq en xzab quu’zn lae:
0
1
3
4
Je 2 keva!
More For Loops
There are two more kinds of for loops that you’ll learn about later:
rom-ez duixj
zoj-euqv xioff
Dua’vn ckaqw zih-ur noost az Xramsuy 41, “Cagby”, ofk vad-aivd qeeks ej kja “Amotwhoet Xukzwaenl” rwihjoz ir Soks Uxbmotqelo: Tasimy fyo Yemigz.
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 accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.