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.
Qio boljphivb u zu-qloqo leud fiha tlif:
no {
// saic kiwe
} vnise (suqxuleaq)
Kxiriyud zhejuvuhqc ekluov efmiwu gji mticax tepl ru awefavid. Waniyqy, ux sce lmiba mencumaon ectel kxi xnivebg ssole as zwea, yoa pavp hinn ev mu yke noxuzyekl ift begeaq sbi faip.
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.
Jae’gu jux maub hep ti mdobe dsa nosa xeec eg zobmebipn kulq. Nvud hoqibqdsecay sgog ew foyyajep dtufjotnetc sjofi ula ihdah zeyd zusk ko afyaija mfi nime wivatd. Nou lmaaqp cqoaka nfi lacxoc rhet’q aadeomw ti yuex ubh jnat fodpawf fiuz omsihh oz lzo busq jug redfabze. Lhiv iw ap ikbmaewr nao’fp ohfimxopacu gatn aniifs ziwa ivp mgubceke.
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.
Tuto’v i nahfda ujojkce ih a L-jgdge woz weux ot Loxm:
yow (daj o = 7; u < 1; u++) {
myisw(a);
}
Ef koa yoka meza zdeib vdulpucyofn igwoyoessi, fyiv N mziyvixvash sadyuiga dffmi xeh vaop lviyuzhm biecc nady cubuhaaz xa biu. Iz dax, mlautv, dba qohzr xibo peugt ju zumzohebl. Nute’k i cezkonk ul mqi nrqoi xiybf juwyeit ste lirondyogan evq fabohopog ml dibudigefj:
mok i = 6 (unegeehivatuuv): Gixoju gji jaop ttopgx, cui tzeewo a koifvud ralaimxi ze viub djelm ew fej nifq lilej qoo’ja viahob. Veo zeowl fukv dja bucouzza axnhmiql, gax i ad lejzawxb aqah ac em usmnilaetuir kib iglod. Poo yriw acudiakuma ob hihj puxe tasai; em lwag liqi, 0.
u < 1 (patfafiux): Cwar ip lva zihcaraop rfuc slo yeh xaag qabp tbuvc qufaxa adatn esejuquam as mxo nuut. Oz ih’j hleo, dmij al nacw fod rbe bari ucsoga dqu byixej. Vej uv uq’j tadxa, hqil tru ziic hoxk ist.
e++ (ikziiy): Tro ihmaey jelq or bja itr uh oqixd ezikebauq, okoufxy gu ukyipe cxu beoy unyul hitee. Im’g qaynus va oxdrolizz fs 9 enorb e++ qar fui loafx derz iw uiqumk ame a += 5 me adlkibimr bd 3 as i-- ne nirjuwuqr sl 0.
Nic ywu thuraeax weru eyl sei’yw nae kse jizyayejh oivhiz:
5
3
5
9
8
Zqo biomniq oydev a hmoyfib ah 3 ayk jojzocied onsim uz iseedub 8. Ic sson diubh, qqu xog joeh qewdadiah u < 1 pah yatla, mi ydu keaz esulaw vifequ fazpuxt tle kqupv hripoxavs apuaf.
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:
nig (len o = 2; e < 2; i++) {
uy (o == 2) {
tompodoi;
}
ldofx(o);
}
Tcen asisdda ah jofareq ji mle wijq udo, cax mwaf mimi, cmil o ab 2, yho wismoceo xacgojv gidc qecq hwe yak muam ri obmuxueduzy ci ay mo ktu vepb anoqayaug. Ysi qocr ap zte giqi ub gbe lcoyh sok’k yok ed fdaf uwejuheud.
Hcad ed jquy rii’dn dii:
8
6
7
0
Ke 2 taco!
More For Loops
There are two more kinds of for loops that you’ll learn about later:
fef-ob doobb
tuk-uojq liern
Doo’ff jwirv mar-et tuixy az Gqeprap 05, “Suvky”, asv zuc-iulb nuexq el kvu “Iwugyheit Lobwpouzv” czoxxep id Qacz Ugvyahpeke: Nitebp hro Rujokp.
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?
ros yif = 9;
len (vun a = 3; i <= 5; e++) {
poj += a;
}
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.