Loops: While and Do while - Introduction to Programming - C++
Loops: While and Do while
Loops: While and Do while
Introduction: Overall idea of while and do while
Loops are used when we want to repeat the same action many times. In the previous lecture, we used the loop for, which is very comfortable when we already know how the counter should start, when it should stop, and how it should change.
The loop while is useful when the repetition depends on a condition. We keep repeating the body while the condition is true. This is especially useful when we do not know in advance how many repetitions will happen.
There is also a loop called do while. It is similar to while, but with one important difference: do while runs the body first, and checks the condition after that. So the body always runs at least once.
Core concept: How while works
The general form of a while loop is:
There are two important parts:
<condition> decides whether the loop should continue.
<body> is the code that we want to repeat.
The loop works in this order:
The most important detail is that while checks the condition before running the body. If the condition is false from the beginning, the body will not run even once.
Let us print numbers from 1 to 10 using while:
Here is what each part means:
Before the loop, we set i=.
1
The condition is i≤10.
The body prints the current value of i.
Inside the body, we change i using i=i+1.
The loop goes like this:
Notice that 11 is not printed. The condition is checked before the body runs.
How a `while` loop checks, prints, and updates
C++
source · C++line 1
1int i = 1;
2
3while (i <= 10) {
4 cout << i << ' ';
5 i = i + 1;
6}
Set the start value
L1
Before the loop, we create i and set its first value.
inv
A `while` loop checks the condition before every body execution.
Variables box
Map
currentPart
start before loop
i
1
condition
not checked
lastPrinted
nothing yet
outputSoFar
empty
currentPartstart before loopi⤳1conditionnot checkedlastPrintednothing yetoutputSoFarempty
iterations0
L1
01 / 32
A while loop does not have a special place for the update. We must write the update ourselves inside the body. If we forget i=i+1, then i will stay equal to 1, the condition i≤10 will always be true, and the loop will never stop.
We can also jump by 2. For example, to print odd numbers from 1 to 10:
This prints: 13579
Now after every repetition, i becomes larger by 2. The loop visits 1,3,5,7,9, then i becomes 11, and the condition i≤10 becomes false.
How a `while` loop jumps by 2
C++
source · C++line 1
1int i = 1;
2
3while (i <= 10) {
4 cout << i << ' ';
5 i = i + 2;
6}
Set the start value
L1
Before the loop, we create i and set its first value.
inv
A `while` loop checks the condition before every body execution.
Variables box
Map
currentPart
start before loop
i
1
condition
not checked
lastPrinted
nothing yet
outputSoFar
empty
currentPartstart before loopi⤳1conditionnot checkedlastPrintednothing yetoutputSoFarempty
iterations0
L1
01 / 17
A while loop can also go backwards:
This prints: 10987654321
So with while, we control everything ourselves: the start value before the loop, the condition in the loop header, and the update inside the body.
Core concept: How do while works
The general form of a do while loop is:
There are again two important parts:
<body> is the code that runs first.
<condition> is checked after the body finishes.
The loop works in this order:
The main difference is simple: do while always runs the body at least once.
Let us print numbers from 1 to 10 using do while:
The result is the same: 12345678910
But the order is different. First we print i, then we increase it, and only after that we check whether i≤10.
How `do while` runs body before condition
C++
source · C++line 1
1int i = 1;
2
3do {
4 cout << i << ' ';
5 i = i + 1;
6} while (i <= 10);
Set the start value
L1
Before the loop, we create i and set it to 1.
inv
The body always runs at least once before the first condition check.
Variables box
Map
currentPart
start before loop
i
1
condition
not checked
lastPrinted
nothing yet
outputSoFar
empty
currentPartstart before loopi⤳1conditionnot checkedlastPrintednothing yetoutputSoFarempty
iterations0
L1
01 / 31
Examples
Example 1: Print numbers from 1 to n using while
Given one integer n, print all numbers from 1 to n.
Example:
Approach and solution
We need a variable i that starts from 1. While i≤n, we print i and then increase it by 1.
Algorithm:
Implementation:
Example 2: Sum numbers from 1 to n using while
Given one integer n, find the sum of all numbers from 1 to n.
Example:
Because 1+2+3+4+5=15.
Approach and solution
We keep a variable sum, which stores the answer so far. At the beginning, sum=0. Then we go through all values of i from 1 to n and add each i to sum.
Algorithm:
Implementation:
We use longlong for sum because the answer can become large when n is large.
Example 3: Read numbers until 0
You are given several integers. The last integer is 0. Print the sum of all numbers before 0.
Example:
Because 4+7+2=13.
Approach and solution
Here we do not know how many numbers will be given before 0. That is why while is more natural than for.
We first read one number x. While x=0, we add it to sum and read the next number. When x=0, the loop stops.
Algorithm:
Implementation:
Example 4: Count digits using do while
Given one integer n, where n≥0, print how many digits it has.
Example:
For n=0, the answer should be 1.
Approach and solution
Every time we divide n by 10, we remove its last digit. We count how many times we can do this until n becomes 0.
The number 0 is the reason do while is useful here. If we used a normal while with condition n>0, then for n=0 the body would not run at all. But 0 still has one digit, so we need the body to run at least once.
Algorithm:
Counting digits with `do while`
C++
source · C++line 1
1int n = 507;
2int cnt = 0;
3
4do {
5 cnt = cnt + 1;
6 n = n / 10;
7} while (n > 0);
Initial value of n
L1
We start with the given number.
inv
The loop body must run at least once, even when n = 0.
Variables box
Map
currentPart
start
n
507
cnt
0
condition
not checked
currentPartstartn⤳507cnt0conditionnot checked
iterations0
L1
01 / 11
Implementation:
Example 5: Print numbers from n down to 1 using while
Given one integer n, print numbers from n down to 1.
Example:
Approach and solution
Now the loop variable goes down. We start with i=n, continue while i≥1, and decrease i by 1 after every repetition.
Algorithm:
Implementation:
1. Check the condition.
2. If the condition is false, stop the loop.
3. If the condition is true, run the body.
4. Go back to step 1.
while(<condition>){<body>}
int i = 1;while(i <= 10){ cout << i << ' '; i = i + 1;}
i = 1 -> condition is true -> print 1 -> i becomes 2
i = 2 -> condition is true -> print 2 -> i becomes 3
i = 3 -> condition is true -> print 3 -> i becomes 4
...
i = 10 -> condition is true -> print 10 -> i becomes 11
i = 11 -> condition is false -> stop
1. Run the body.
2. Check the condition.
3. If the condition is true, run the body again.
4. If the condition is false, stop the loop.
Input:
5
Output:
1 2 3 4 5
1. Read n.
2. Set i = 1.
3. While i <= n:
1. Print i.
2. Increase i by 1.
Input:
5
Output:
15
1. Read n.
2. Set sum = 0.
3. Set i = 1.
4. While i <= n:
1. Add i to sum.
2. Increase i by 1.
5. Print sum.
Input:
4 7 2 0
Output:
13
1. Set sum = 0.
2. Read x.
3. While x != 0:
1. Add x to sum.
2. Read the next x.
4. Print sum.
Input:
507
Output:
3
1. Read n.
2. Set cnt = 0.
3. Do:
1. Increase cnt by 1.
2. Remove the last digit from n.
4. Continue while n > 0.
5. Print cnt.
Input:
5
Output:
5 4 3 2 1
1. Read n.
2. Set i = n.
3. While i >= 1:
1. Print i.
2. Decrease i by 1.
int i = 1;while(i <= 10){ cout << i << ' '; i = i + 2;}
int i = 10;while(i >= 1){ cout << i << ' '; i = i - 1;}
do{<body>} while(<condition>);
int i = 1;do{ cout << i << ' '; i = i + 1;} while(i <= 10);
#include <bits/stdc++.h>using namespace std;int main(){ int n; cin >> n; int i = 1; while(i <= n){ cout << i << ' '; i = i + 1;} return 0;}
#include <bits/stdc++.h>using namespace std;int main(){ int n; cin >> n; long long sum = 0; int i = 1; while(i <= n){ sum = sum + i; i = i + 1;} cout << sum << '\n'; return 0;}
#include <bits/stdc++.h>using namespace std;int main(){ long long sum = 0; int x; cin >> x; while(x != 0){ sum = sum + x; cin >> x;} cout << sum << '\n'; return 0;}
#include <bits/stdc++.h>using namespace std;int main(){ int n; cin >> n; int cnt = 0; do{ cnt = cnt + 1; n = n / 10;} while(n > 0); cout << cnt << '\n'; return 0;}
#include <bits/stdc++.h>using namespace std;int main(){ int n; cin >> n; int i = n; while(i >= 1){ cout << i << ' '; i = i - 1;} return 0;}