Loops — while & do-while
I. In-Class Exercises
Programming Exercises
Sample Code
1// while loop drawing a regular 16-sided polygon
2#include "CTurtle.hpp"
3#include <bits/stdc++.h>
4using namespace std;
5using namespace cturtle;
6
7int main() {
8 // Create a canvas screen
9 TurtleScreen scr;
10 // Create a drawing turtle
11 Turtle turtle(scr);
12
13 int sides = 16;
14 int sideLength = 20;
15 double angle = 360.0 / sides;
16
17 int count = 0;
18 while (count < sides) {
19 turtle.forward(sideLength);
20 turtle.right(angle);
21 ++count;
22 }
23
24 // Pause the program
25 system("pause");
26 // End of program
27 return 0;
28}1// do-while loop drawing a regular 16-sided polygon
2#include "CTurtle.hpp"
3#include <bits/stdc++.h>
4using namespace std;
5using namespace cturtle;
6
7int main() {
8 // Create a canvas screen
9 TurtleScreen scr;
10 // Create a drawing turtle
11 Turtle turtle(scr);
12
13 int sides = 16;
14 int sideLength = 20;
15 double angle = 360.0 / sides;
16
17 int count = 0;
18 do {
19 turtle.forward(sideLength);
20 turtle.right(angle);
21 ++count;
22 } while (count < sides);
23
24 // Pause the program
25 system("pause");
26 // End of program
27 return 0;
28}1#include <bits/stdc++.h>
2using namespace std;
3
4int main() {
5 int n;
6 cin >> n;
7 int sum = 0;
8 int i = n;
9 while (i > 0) {
10 sum += i--;
11 }
12 cout << sum << endl;
13 return 0;
14}1#include <bits/stdc++.h>using namespace std;
2
3int main() {
4 int n;
5 cin >> n;
6 double sum = 0;
7 int i = 1;
8 while (i <= n) {
9 sum += 1.0 / i;
10 ++i;
11 }
12 printf("%.3f", sum);
13 return 0;
14}1#include <bits/stdc++.h>using namespace std;
2
3int main() {
4 int n;
5 cin >> n;
6 int sum = 0;
7 int i = 1;
8 while (i <= n) {
9 sum += i;
10 i += 2;
11 }
12 cout << sum << endl;
13 return 0;
14}II. Knowledge Summary
✨ What is a Loop
In daily life, many things need to be done repeatedly. For example:
- When running, you go around the track lap after lap until you've completed the required number of laps
- When doing homework, you solve problems one by one until they're all done
It's the same in programs. When we need to repeatedly execute a piece of code, we use loop structures. Loop structures allow programs to repeat automatically without writing the same code multiple times.
A loop typically consists of three parts:
- Initialize the loop variable: Preparation before the loop begins
- Loop condition: Determines whether to continue looping
- Update the loop variable: Changes the variable's value after each iteration so the loop eventually ends
✨ while Loop
Syntax
The while loop checks the condition first; if true, it executes the loop body; if false, it exits the loop.
1while (loop_condition) {
2 // If condition is true, execute code inside braces
3 Operation
4 Update loop variable
5}
6// If condition is false, exit loop and run subsequent codewhile Loop Flowchart
Comprehensive Example: Sum from 1 to n
Input an integer n, calculate 1+2+3+...+n.
1int n;
2cin >> n;
3int sum = 0;
4int i = 1;
5while (i <= n) {
6 sum += i;
7 ++i;
8}
9cout << sum << endl;✨ do-while Loop
Syntax
The do-while loop executes the loop body first, then checks the condition; if true, it continues; if false, it exits.
1do {
2 // Execute code inside braces first
3 Operation
4 Update loop variable
5} while (loop_condition); // Note the semicolon here
6// If condition is false, exit loop and run subsequent codedo-while Loop Flowchart
Comprehensive Example: Input Validation
Ask the user to input an integer between 1 and 100. If the input is invalid, prompt for re-entry until the input is correct. This scenario requires at least one input, making it perfect for do-while.
1int n;
2do {
3 cout << "Enter an integer from 1-100: ";
4 cin >> n;
5} while (n < 1 || n > 100);
6cout << "Valid input: " << n << endl;✨ Difference Between while and do-while
| while | do-while | |
|---|---|---|
| Check timing | Checks condition first, then executes body | Executes body first, then checks condition |
| Minimum executions | 0 times (doesn't execute if condition is false initially) | 1 time (always executes at least once) |
| Use case | Unknown iteration count, may not execute at all | Scenarios requiring at least one execution (e.g., input validation) |
1int i = 10;
2
3// while loop: condition is false, body doesn't execute, no output
4while (i < 5) {
5 cout << i << endl;
6 ++i;
7}
8
9// do-while loop: executes body first, outputs 10
10do {
11 cout << i << endl;
12 ++i;
13} while (i < 5);III. Homework
Programming Exercises
- Loop Output: L1114
- Common Factor Search: L1115
- Find Number II: L1116
- Fraction Addition and Subtraction: L1117