UNIVERSITY OF AGRICULTURE, FAISALABAD
Department of Computer Science
LECTURE 16 · STUDENT NOTES
Loop-Based Problem Solving
CS-307 Programming Fundamentals · BSCS Semester 1
Week | Slides | Linked practical | Reference ID |
6 | Lecture16_Loop_Problem_Solving.pptx | Practical 11 | N16 |
Learning Outcomes
SLO | By the end of this lecture you can… | Builds CLO | Bloom level |
|---|---|---|---|
SLO 16.1 | Break a loop problem into steps with top-down design before coding | CLO1: Identify the necessary properties of good problem-solving techniques. | C3 |
SLO 16.2 | Write loop programs for digits, prime numbers, series and number checks | CLO4: Describe the syntax and semantics of the C++ programming language. | C3 |
SLO 16.3 | Test loop programs with edge cases and fix the logic errors found | CLO1: Identify the necessary properties of good problem-solving techniques. | C4 |
How to use these notes Read these notes after the lecture and before the practical. Section numbers (for example §3.2) are used in the question bank, so you can always find where an answer comes from. Type every code example yourself — do not copy-paste. |
1. Top-Down Design for Loop Problems
Top-down design (Lecture 7) means solving a big problem by splitting it into small steps, then splitting those steps again until each one is easy to code. (Slide L16-S05)
For a loop problem, answer four questions before coding:
Question | Example: print all primes up to N and count them |
|---|---|
What repeats? | Checking each number n = 2 … N |
What changes each round? | n goes up by 1 |
When does it stop? | After n = N |
What do I keep track of? | A count of primes (count pattern) |
Step-wise refinement of the example:
1. For each n from 2 to N:
2. Is n prime? ← this step needs its own loop (an inner loop)
3. If yes: print n and add 1 to the count
4. Print the count
Rule Write the steps in plain words first. A step that itself needs repeating becomes an inner loop. |
2. Digits of a Number
Two operations do all the work: n % 10 gives the last digit and n / 10 removes it (integer division). (Slide L16-S06)
digits.cpp #include <iostream> using namespace std;
int main() { int n, count = 0, sum = 0; cout << "Enter a number: "; cin >> n; do { sum += n % 10; // last digit count++; n = n / 10; // remove last digit } while (n > 0); cout << "Digits: " << count << ", sum: " << sum << endl; return 0; } |
Session Enter a number: 4075 Digits: 4, sum: 16 |
n | n % 10 | sum | count |
|---|---|---|---|
4075 | 5 | 5 | 1 |
407 | 7 | 12 | 2 |
40 | 0 | 12 | 3 |
4 | 4 | 16 | 4 |
0 | loop stops |
A do-while is used so that the input 0 still counts as one digit (see §6). The same two steps are used to reverse a number (Lecture 11), check a palindrome and find Armstrong numbers.
3. Prime Numbers
3.1 Is n prime?
A prime number has exactly two divisors: 1 and itself. The program uses the flag pattern and the search pattern (Lecture 14). (Slide L16-S07)
prime.cpp #include <iostream> using namespace std;
int main() { int n; cout << "Enter n: "; cin >> n; bool isPrime = (n >= 2); // 0 and 1 are not prime for (int d = 2; d * d <= n; d++) { if (n % d == 0) { isPrime = false; // found a divisor break; } } if (isPrime) cout << n << " is prime" << endl; else cout << n << " is not prime" << endl; return 0; } |
Input | 1 | 2 | 29 | 91 | 97 |
|---|---|---|---|---|---|
Output | not prime | prime | prime | not prime (7 × 13) | prime |
- The flag starts as (n >= 2) because 0 and 1 are not prime.
- We stop testing when *d d > n**: every factor pair has one factor no bigger than √n. For 97 we test only d = 2 … 9.
- As soon as a divisor is found, there is no need to test more — break.
3.2 All primes up to a limit
The design from §1 turns into a nested loop: the outer loop is step 1, the inner loop is step 2. (Slide L16-S08)
primes_list.cpp #include <iostream> using namespace std;
int main() { int limit, count = 0; cout << "Primes up to: "; cin >> limit; for (int n = 2; n <= limit; n++) { // step 1: every number bool isPrime = true; for (int d = 2; d * d <= n; d++) { // step 2: test it if (n % d == 0) { isPrime = false; break; } } if (isPrime) { // step 3: print, count cout << n << " "; count++; } } cout << endl << "Count: " << count << endl; return 0; } |
Session Primes up to: 50 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 Count: 15 |
Note: isPrime = true is written inside the outer loop so that every n starts fresh. With 100 the count is 25.
4. Series and GCD
4.1 Fibonacci series
Each term is the sum of the two terms before it. Keep the last two terms in variables and shift them each round. (Slide L16-S09)
fibonacci.cpp #include <iostream> using namespace std;
int main() { int a = 0, b = 1; for (int i = 1; i <= 10; i++) { cout << a << " "; int next = a + b; a = b; b = next; } cout << endl; return 0; } |
Output 0 1 1 2 3 5 8 13 21 34 |
4.2 GCD by Euclid's method
The GCD (greatest common divisor, also called HCF) is the biggest number that divides both. Euclid's method replaces (x, y) by (y, x % y) until y becomes 0. LCM = a / GCD × b.
gcd.cpp #include <iostream> using namespace std;
int main() { int a, b; cout << "Two numbers: "; cin >> a >> b; int x = a, y = b; while (y != 0) { // Euclid's method int r = x % y; x = y; y = r; } cout << "GCD = " << x << ", LCM = " << a / x * b << endl; return 0; } |
x | y | x % y |
|---|---|---|
48 | 18 | 12 |
18 | 12 | 6 |
12 | 6 | 0 |
6 | 0 | stop → GCD 6 |
Session Two numbers: 48 18 GCD = 6, LCM = 144 |
Real-world: a floor of 48 × 18 units can be covered by equal square tiles of at most 6 × 6.
5. Number Checks: Armstrong Numbers
A 3-digit Armstrong number equals the sum of the cubes of its digits, e.g. 153 = 1³ + 5³ + 3³ = 1 + 125 + 27. A digit loop runs inside a range loop. (Slide L16-S10)
armstrong.cpp #include <iostream> using namespace std;
int main() { for (int n = 100; n <= 999; n++) { int t = n, sum = 0; while (t > 0) { int dgt = t % 10; sum += dgt * dgt * dgt; t /= 10; } if (sum == n) cout << n << " "; } cout << endl; return 0; } |
Output 153 370 371 407 |
Work on a copy The digit loop divides t, a copy of n. Dividing n itself would destroy the outer loop's counter. |
6. Testing With Edge Cases
An edge case is an unusual input at the 'edge' of what is allowed: 0, 1, a negative number, the smallest or largest value, equal inputs. A program that works for normal input can still fail on these. (Slide L16-S12)
digits_zero_bug.cpp #include <iostream> using namespace std;
int main() { int n, count = 0; cin >> n; while (n > 0) { // never runs for 0 count++; n = n / 10; } cout << "Digits: " << count << endl; return 0; } |
Input and output — wrong (0 has one digit) 0 Digits: 0 |
prime_bug.cpp #include <iostream> using namespace std;
int main() { int n; cin >> n; bool isPrime = true; // wrong for 0 and 1 for (int d = 2; d < n; d++) { if (n % d == 0) isPrime = false; } cout << (isPrime ? "prime" : "not prime") << endl; return 0; } |
Input | 0 | 1 | 7 | 9 |
|---|---|---|---|---|
prime_bug output | prime ✗ | prime ✗ | prime | not prime |
- digits_zero_bug: the while test fails at once for 0. Fix: use do-while (digits.cpp).
- prime_bug: the flag starts true and the loop never runs for 0 and 1. Fix: start with (n >= 2).
- gcd.cpp with 0 0: x becomes 0 and a / x divides by zero — the program crashes (Floating point exception). Fix: check for 0 0 before dividing.
Edge-case checklist |
|---|
0 · 1 · a negative number · smallest allowed · largest allowed · equal values · first and last item |
7. Word Bank (Key Terms)
Word | Simple meaning |
|---|---|
Top-down design | Solving a big problem by splitting it into smaller steps |
Prime number | A number ≥ 2 whose only divisors are 1 and itself |
Divisor | A number that divides another with remainder 0 |
GCD / HCF | The greatest number that divides two numbers |
LCM | The smallest number that both numbers divide |
Series | A list of numbers made by a rule, e.g. Fibonacci |
Edge case | An unusual input at the limit of what is allowed |
8. Self-Check Questions
1. What are the digit count and digit sum of 90210?
2. Print the Fibonacci terms below 100. How many are there?
3. Is 97 prime? Which values of d does prime.cpp test?
4. Which two operators give and remove the last digit?
5. Why is isPrime = true written inside the outer loop of primes_list.cpp?
6. Name three edge cases for a prime checker.
Answers: 5 digits, sum 12; 0 1 1 2 3 5 8 13 21 34 55 89 — 12 terms; prime, d = 2 … 9; % 10 and / 10; §3.2; 0, 1, 2 (and a square like 49). Homework is on Slide L16-S14.