Loops: For, While and Do-While - Забони барномасозии C++ барои барномасозии рақобатӣ
Week 3Loops, Counters and Accumulators, Digit Processing
Loops: For, While and Do-While
Repeating code, one step at a time: the for loop piece by piece and how it runs, using the loop variable, counting down, bigger steps, counting iterations without an off-by-one, the while loop, break, continue, do-while, and loops that never end.
Назария
Дарси 1 аз 6
Хониш: 15 дақиқа
Саволҳо: 5
Print the numbers from 1 to 5: five cout lines will do. From 1 to 1000? Nobody
writes a thousand lines. And from 1 to n, where n is read from the input,
can't be written out at all — the program doesn't know n until it runs.
A loop repeats a piece of code: once for each number, once for each line
of input, or for as long as something stays true. This lesson builds up the
three loops of C++ one step at a time: for first, then while, then
do-while.
Your first loop
Here is a loop that prints the numbers from 1 to 5:
It prints 1 2 3 4 5. Read it piece by piece:
Piece
What it says
for
"repeat the code in the braces"
int i = 1
the start: make a variable i and set it to 1
i <= 5
the check: keep going while this is true
i++
the step: after each pass, make i one bigger
{ cout << i << " "; }
the body: the code that is repeated
The three parts in the brackets are separated by semicolons, not commas.
The variable i is the loop variable, or counter: it counts the passes.
One pass through the body is called an iteration.
навбатӣ
Practice: Loops
Ranges, steps, multiples, squares, powers of two and the first divisor, with one loop.
The four parts don't run in the order they are written. The start runs only
once; after that, the loop goes round the same circle until the check fails:
So with i <= 5 the body runs for i = 1, 2, 3, 4 and 5. Then i becomes 6,
the check 6 <= 5 is false, and the program moves on to the line after the
loop.
Step through a loop that reads n and counts up to it, here with n = 3.
Watch the highlighted line jump back to the for line after every pass:
A for loop, one step at a time
C++
1#include <bits/stdc++.h>
2using namespace std;
3
4int main() {
5 ios_base::sync_with_stdio(false);
6 cin.tie(NULL);
7
8 int n;
9 cin >> n;
10 for (int i = 1; i <= n; i++) {
11 cout << i << " ";
12 }
13 cout << "\n";
14 return 0;
15}
Read n
сатр 9
n is 3: the loop should print 1 2 3.
вуруд
3
n3i—
пахш кун
1 / 13
Two things the trace shows:
The check runs before every pass, the first one too. If n were 0, the
check 1 <= 0 would fail at once and the body would run zero times.
The check runs once more than the body. For n = 3 it ran four times:
three times true, and the last time false.
Using the loop variable
The body can use i however it likes — print it, or calculate with it:
Read n and print its multiplication table: ten lines, from n x 1 = … to
n x 10 = ….
Input
Output
Here i is the multiplier: it goes from 1 to 10, and each pass prints one line.
A variable made in the for line, like int i, exists only inside its loop.
After the closing brace there is no i any more, so the next loop can make its
own.
Counting down
To count down, turn all three parts around: start high, step with i--, and
check that i is still big enough:
It prints 5 4 3 2 1. The check has to look the other way too. Write
i <= 1 there by mistake, and 5 <= 1 is false at once — the loop runs zero
times and prints nothing.
Steps bigger than one
The step can move i by any amount, as long as it moves towards the end:
Loop
Values of i
for (int i = 1; i <= 9; i += 2)
1 3 5 7 9
for (int i = 20; i > 0; i -= 5)
20 15 10 5
for (int i = 1; i <= 100; i *= 2)
1 2 4 8 16 32 64
i += 2 jumps over the even numbers, so the first loop prints the odd numbers.
In the last one i doubles: 64 · 2 = 128 fails the check.
How many times does it run?
Most loop mistakes are off by one: the loop runs one time too many or one
too few. Count before you run:
Loop
Iterations
for (int i = 1; i <= n; i++)
n
for (int i = 0; i < n; i++)
n — the same count, starting from 0
for (int i = 1; i < n; i++)
n - 1
for (int i = a; i <= b; i++)
b - a + 1
< against <= is the usual culprit. When a loop has to run n times, pick
one of the first two forms and keep to it. When it covers a range from a to
b, test the smallest case by hand: from 3 to 3 is one number, and
b - a + 1 says 1.
The while loop
A for loop is a short way of writing a more basic loop, while. Here is the
same 1-to-5 loop, written with while:
while has only the check in its brackets. It checks; if the check is true it
runs the body and comes back to check again; the first time it is false, the
loop ends. The start goes before the loop and the step goes inside the body —
forget the step, and i stays 1 forever.
So why have both? Use for when you count: from 1 to n, n times. Use
while when the loop runs until something happens, and nobody can say in
advance how many passes that takes:
Read n (n ≥ 2) and print its largest divisor smaller than n.
Input
Output
Going down from n - 1, the first divisor the loop meets is the largest,
so it stops right there. It always stops, because 1 divides every number. For
91 it tries 90, 89, …, 14 and stops at 13, since 91 = 7 · 13.
Now you build the loops. Set the start, the check and the step so the loop
prints exactly what is asked — and in the last round, write one as a while:
Make the loop print thisсанҷида бин!
Stopping in the middle: break
break ends a loop at once, wherever it stands in the body, and the program
goes on after the loop. It is useful when the moment to stop is in the middle
of the body, not at the check:
A snail is at the bottom of a well h metres deep. Every day it climbs u
metres; every night it slides back d metres (u > d). On which day does it
get out?
Input
Output
while (true) has a check that is always true, so on its own it would repeat
forever; the break is the way out. It sits between the climb and the slide:
once the snail is out, there is no night slide. For h = 10, u = 3, d = 1
the snail reaches 3, 5, 7 and 9 metres on the first four days and slides back
each night; on day 5 it reaches 11 and is out.
Skipping a pass: continue
continue skips the rest of the body and goes straight on to the next
iteration — in a for, the step still runs:
It prints 1 to 20 without 5, 10, 15 and 20. An if around the cout would do
the same; continue is handy when the body is long and the decision to skip is
made at its top.
The do-while loop
do-while is a while turned upside down: it runs the body first and
checks afterwards, so the body always runs at least once.
This prints the digits of n from the right. For n = 0 it prints 0, while
the same loop written with while (n > 0) { … } would print nothing — its check
fails before the first pass. Mind the semicolon after while (…): do-while is
the only loop that ends with one.
Loops that never end
A loop whose check never becomes false runs forever — the judge stops it and
reports Time Limit Exceeded. The usual ways in:
Code
Why it never ends
while (i <= n) { cout << i; }
nothing changes i
for (int i = 10; i >= 1; i++)
the step goes the wrong way
for (int i = 1; i != 10; i += 2)
i jumps over 10: 1, 3, …, 9, 11, …
Prefer < and <= to != in a check: they stop the loop even when the counter
jumps past the bound.
Check your understanding
How a for loop runs
Start — int i = 1 runs once, before anything else.
Check — is i <= 5 true? If it is false, the loop is over.
Body — the code in the braces runs.
Step — i++ runs, and the loop goes back to the check.
Did you know?
On 31 December 2008, thousands of Microsoft Zune music players froze at once.
The code that turned "days since 1980" into a year had a while loop that
subtracted 366 days in a leap year — but only when more than 366 days were
left. On the 366th day of the leap year 2008, exactly 366 were left: nothing
was subtracted, and the loop went round forever. The players worked again the
next day, once the date had moved on.
for(int i = 1; i <= 5; i++){ cout << i << " ";}
худро санҷ1 хол
How many times does the body of for (int i = 3; i <= 10; i++) run?
Барои ҷавоб додан ва нигоҳ доштани пешрафт ворид шавед.Ворид шудан
худро санҷ1 хол
With n = 0, the body of for (int i = 1; i <= n; i++) runs once.
Барои ҷавоб додан ва нигоҳ доштани пешрафт ворид шавед.Ворид шудан
худро санҷ1 хол
What is s after this loop?
Барои ҷавоб додан ва нигоҳ доштани пешрафт ворид шавед.Ворид шудан
худро санҷ1 хол
What is c at the end?
Барои ҷавоб додан ва нигоҳ доштани пешрафт ворид шавед.Ворид шудан
худро санҷ1 хол
What does this print?
Як ҷавобро интихоб кунед
Барои ҷавоб додан ва нигоҳ доштани пешрафт ворид шавед.Ворид шудан
7
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
7 x 6 = 42
7 x 7 = 49
7 x 8 = 56
7 x 9 = 63
7 x 10 = 70
91
13
10 3 1
5
#include <bits/stdc++.h>using namespace std;int main(){ ios_base::sync_with_stdio(false); cin.tie(NULL); int n; cin >> n; for(int i = 1; i <= 10; i++){ // i takes the values 1, 2, ..., 10 cout << n << " x "<< i << " = "<< n * i << "\n";} return 0;}
for(int i = 5; i >= 1; i--){ cout << i << " ";}
int i = 1; // the start, before the loopwhile(i <= 5){ // the check cout << i << " "; i++; // the step, at the end of the body}
#include <bits/stdc++.h>using namespace std;int main(){ ios_base::sync_with_stdio(false); cin.tie(NULL); int n; cin >> n; int d = n - 1; while(n % d != 0){ // the first divisor found going down is the largest d--;} cout << d << "\n"; return 0;}
#include <bits/stdc++.h>using namespace std;int main(){ ios_base::sync_with_stdio(false); cin.tie(NULL); int h, u, d; cin >> h >> u >> d; int height = 0, day = 0; while(true){ day++; height += u; // climbs during the day if(height >= h){ break; // out of the well: no night slide} height -= d; // slides back at night} cout << day << "\n"; return 0;}
for(int i = 1; i <= 20; i++){ if(i % 5 == 0){ continue; // multiples of 5 are skipped} cout << i << " ";}
do{ cout << n % 10; n /= 10;} while(n > 0);
int s = 0;for(int i = 1; i <= 10; i++){ if(i == 5){ break;} s += i;}
int n = 0, c = 0;do{ c++; n /= 10;} while(n > 0);
for(int i = 20; i > 0; i -= 6){ cout << i << " ";}