UNIVERSITY OF AGRICULTURE, FAISALABAD
Department of Computer Science
LECTURE 13 · STUDENT NOTES
Repetitive Statements III: the for Loop
CS-307 Programming Fundamentals · BSCS Semester 1
Week | Slides | Linked practical | Reference ID |
5 | Lecture13_For_Loop.pptx | Practical 9 | N13 |
Learning Outcomes
SLO | By the end of this lecture you can… | Builds CLO | Bloom level |
|---|---|---|---|
SLO 13.1 | Write a for loop and explain its three parts | CLO4: Describe the syntax and semantics of the C++ programming language. | C3 |
SLO 13.2 | Convert between for and while loops and choose the right loop for a problem | CLO4: Describe the syntax and semantics of the C++ programming language. | C2 |
SLO 13.3 | Use for loops for counting, totals, tables and simple series | CLO1: Identify the necessary properties of good problem-solving techniques. | C3 |
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. Three Parts, One Line
Every counter loop has a start, a condition and an update (Lecture 11). In a while loop they are on three different lines, so it is easy to forget one. The for loop puts all three inside its brackets, separated by two semicolons. (Slide L13-S05)
while version int i = 1; // start while (i <= 5) { // condition cout << i << " "; i++; // update } |
for version for (int i = 1; i <= 5; i++) { cout << i << " "; } |
Both print 1 2 3 4 5 |
2. The for Loop
2.1 Order of steps
(Slide L13-S06)
Step | Part | In for (int i = 1; i <= 5; i++) | When |
|---|---|---|---|
1 | start | int i = 1 | only once, at the beginning |
2 | condition | i <= 5 | before every round; false → leave the loop |
3 | body | { … } | when the condition is true |
4 | update | i++ | after the body, then back to step 2 |
Real-world: running 10 laps — stand on the start line once; before each lap ask "fewer than 10 laps done?"; run a lap; add one to the lap count.
2.2 Example: multiplication table
(Slide L13-S07)
table7.cpp #include <iostream> using namespace std;
int main() { for (int i = 1; i <= 10; i++) { cout << "7 x " << i << " = " << 7 * i << endl; } return 0; } |
Output 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 |
2.3 Other steps and directions
The update can be any change: i += 2 jumps by two, i-- counts down. The condition must match the direction. (Slide L13-S08)
even_sum.cpp #include <iostream> using namespace std;
int main() { int sum = 0; for (int i = 2; i <= 100; i += 2) { sum += i; } cout << "Sum of even numbers 2 to 100 = " << sum << endl; return 0; } |
Output Sum of even numbers 2 to 100 = 2550 |
countdown.cpp #include <iostream> using namespace std;
int main() { for (int i = 10; i >= 1; i--) { cout << i << " "; } cout << "Lift-off!" << endl; return 0; } |
Output 10 9 8 7 6 5 4 3 2 1 Lift-off! |
3. Choosing a Loop
3.1 for and while are interchangeable
(Slide L13-S09) Any for loop can be written as a while loop: the start goes before the while, the condition stays, and the update becomes the last statement of the body.
Part | In a for loop | In a while loop |
|---|---|---|
start | first part of ( ) | a statement before the loop |
condition | middle part of ( ) | inside while ( ) |
update | last part of ( ) | last statement of the body |
3.2 Which loop should I use?
(Slide L13-S10)
Loop | Use when | Examples |
|---|---|---|
for | we know how many times | tables, sum of 1 … n, marks of n students |
while | repeat until something happens; may run 0 times | digits, savings goal, sentinel input |
do-while | must run at least once | menus, input validation, PIN |
4. Patterns with for
4.1 The product pattern: factorial
n! ("n factorial") = 1 × 2 × 3 × … × n. A product accumulator must start at 1 (a sum starts at 0). (Slide L13-S11)
factorial.cpp #include <iostream> using namespace std;
int main() { int n; cout << "Enter n: "; cin >> n;
long long fact = 1; // start at 1, not 0 for (int i = 1; i <= n; i++) { fact = fact * i; } cout << n << "! = " << fact << endl; return 0; } |
n | Output |
|---|---|
5 | 5! = 120 |
0 | 0! = 1 |
10 | 10! = 3628800 |
20 | 20! = 2432902008176640000 |
21 | 21! = -4249290049419214848 |
Overflow 21! is larger than the biggest value a long long can hold, so the result wraps round to a wrong negative number. C++ gives no error — check the size of your answers. |
4.2 A savings growth table
Rs. 100,000 at an example rate of 10% profit per year. Each year's profit is added, so the next profit is larger (compound growth). (Slide L13-S12)
savings_table.cpp #include <iostream> #include <iomanip> using namespace std;
int main() { double amount = 100000; // deposit in Rs. const double RATE = 0.10; // 10% profit per year (example)
cout << "Year Amount (Rs.)" << endl; cout << fixed << setprecision(2); for (int year = 1; year <= 5; year++) { amount = amount + amount * RATE; cout << setw(4) << year << " " << setw(12) << amount << endl; } return 0; } |
Output Year Amount (Rs.) 1 110000.00 2 121000.00 3 133100.00 4 146410.00 5 161051.00 |
4.3 Reading n values
When the user tells us the count first, the loop is counter-controlled → for. (Slide L13-S13)
average.cpp #include <iostream> using namespace std;
int main() { int n; double marks, total = 0; cout << "How many students? "; cin >> n; for (int i = 1; i <= n; i++) { cout << "Marks of student " << i << ": "; cin >> marks; total += marks; } cout << "Average = " << total / n << endl; return 0; } |
Output How many students? 3 Marks of student 1: 70 Marks of student 2: 85 Marks of student 3: 64 Average = 73 |
Danger: n = 0 makes total / n divide by zero — validate n with a do-while (Lecture 12).
5. Two Traps
(Slide L13-S15)
5.1 Stray semicolon
trap_semicolon.cpp #include <iostream> using namespace std;
int main() { int i; for (i = 1; i <= 5; i++); // stray semicolon { cout << "i = " << i << endl; } return 0; } |
Output — printed once, not five times i = 6 |
The ; is an empty body: the loop counts to 6 doing nothing, then the block runs once. g++ -Wall warns: this 'for' clause does not guard....
5.2 Using the loop variable after the loop
trap_scope.cpp #include <iostream> using namespace std;
int main() { for (int i = 1; i <= 3; i++) { cout << i << " "; } cout << "Last i: " << i << endl; // i does not exist here return 0; } |
g++ says error: 'i' was not declared in this scope |
A variable declared inside the for brackets exists only inside the loop — this is its scope. Declare it before the loop if you need it afterwards.
6. Word Bank (Key Terms)
Word | Simple meaning |
|---|---|
for loop | A loop with start; condition; update in its brackets |
Loop variable | The counter of a for loop, often i |
Step | How much the loop variable changes each round |
Product accumulator | A variable that collects a product; starts at 1 |
Factorial (n!) | 1 × 2 × … × n |
Overflow | A number too big for its type; the value becomes wrong without warning |
Compound growth | Growth where each year's profit is added before the next year |
Scope | The part of the program where a variable exists |
7. Self-Check Questions
1. Write the parts of for (int i = 1; i <= 5; i++) and the order in which they run.
2. Rewrite as a for loop: int k = 5; while (k <= 50) { cout << k; k += 5; }
3. How many times does for (int i = 0; i < 10; i += 3) run?
4. Which loop would you use for: (a) the table of 9, (b) reading marks until -1, (c) a menu?
5. Why must a product start at 1? What happens with 21! in a long long?
6. What is printed by trap_semicolon.cpp and why?
Answers are in §2.1, §3.1 (for (int k = 5; k <= 50; k += 5)), the teaching guide (4 times), §3.2, §4.1 and §5.1. Homework is on Slide L13-S17.