0% found this document useful (0 votes)
16 views55 pages

Lecture 06 - Looping

Lecture 5 covers various looping constructs in programming, including while, do-while, and for loops, as well as nested loops. It emphasizes the importance of control variables for managing loop execution and provides examples of input validation using loops. Additionally, the lecture discusses increment/decrement operators and different loop design patterns such as counter-controlled, sentinel-controlled, and flag-controlled loops.

Uploaded by

asmita.maheshk
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views55 pages

Lecture 06 - Looping

Lecture 5 covers various looping constructs in programming, including while, do-while, and for loops, as well as nested loops. It emphasizes the importance of control variables for managing loop execution and provides examples of input validation using loops. Additionally, the lecture discusses increment/decrement operators and different loop design patterns such as counter-controlled, sentinel-controlled, and flag-controlled loops.

Uploaded by

asmita.maheshk
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Lecture 5: Looping Part I

Professor Marquise Pullen


Agenda
• while Loop
• do-while Loop
• for Loop
• Nested Loops
Operator Precedence 3.0 – Defines the priority
for evaluating operations in a program
Highest Significance Operator Description Type Associativity Week

Naming :: Scope Resolution General 1-2

Grouping ( ) Parentheses General 1-2

Unary + - ! plus minus negation 2

Multiplicative * / % product quotient remainder Math / Logic


2
Additive + - add subtract

I/O << >> Insertion Extraction Stream 2

Comparison > >= < <= greater less Relational


4
Logic == != equal not equal Equality

Assigning = += -= *= /= %= Assignment General 2

Conditional && And


Logic 4
Logic || Or

Lowest Separator , Common General 1


Flow of Control
Sequential conditional Looping
entry entry entry

statement1 condition condition true statement1

true false false


statement2
statement1 statement2 statement2

statementN

exit exit exit


while loop – Pre-test loop that repeats while a
condition is satisfied
Looping
entry pre-test – a loop that tests before
repeating the conditional code
condition true statement

Syntax: while(condition)
false statement;

exit
5.1 Intro to the while Loop
While Loop – Mechanics
1. Initialize a control variable
2. Perform test w/ control variable
3. While test is true
4. Execute some code / Update control variable

Syntax: init-control;
while(test-control){
execute / update-control
}
5.1 Intro to the while Loop
Validation – Checking the user input to ensure
program can use it
Algorithm:
1. Check input for validity
2. If invalid
1. Print error message
2. Ask for input again
3. Repeat step 1
3. Else proceed w/ the rest of the program

Relation to Test-Suite:
• Normal / Boundary cases are valid
• Extreme / Error cases are invalid
• The goal of validation is to prevent extreme/error cases from happening
5.2 – Using the While Loop for Input Validation
1.
2.
Input Validation w/ if Statement
3. Example
4.
5. unsigned input;
6. cout << "Enter an integer N between 1 and 15: ";
7. cin >> input;
8.
9. bool isValid = input >= 1 && input <= 15;
10.
11. if (!isValid)
12. return 0;
13.
14. cout << " Our number is valid. ";
15.
1.
2.
Input Validation w/ while Loop
3. Example
4.
5. unsigned input;
6. cout << "Enter an integer N between 1 and 15: ";
7. cin >> input;
8.
9. bool isValid = input >= 1 && input <= 15;
10.
11. while (!isValid){
12. cout << "Enter an integer N between 1 and 15: ";
13. cin >> input;
14. isValid = input >= 1 && input <= 15;
15. }
Loop Control Variable – specifically created to
control when to loop and when to end the loop
Requirements for finite loop:
1. Initialize control variable
2. Test w/ control variable
3. Execute loop code
4. Update control variable, repeat step 2

Note: infinite loop is the result of not updating a loop control


variable

3.4 Overflow and Underflow


1.
2.
Infinite w/ while Loop
3. Example
4. Control variables

5. unsigned num_tries = 0;
6. Test w/ Control
7. while (num_tries > -1){
8. cout << "Number of tries is " << num_tries;
9. num_tries++; Update Control
10. }
11.
12.
13.
14.
15.
Lab #1 Case Study – Stricting the number of
User Attempts
Description: The program asks a user to enter an integer N
between 1 and 15 and computes the sum of integers from 0 to
N. The user has only two tries. If the user failed to enter an
integer between 1 and 15 on the second try then the program
should exit without computing the sum.

Analysis: Code Logic:


Input : integer ( 1 ≥ 𝑁𝑁 ≤ 15) 𝑁𝑁 ≥ 1 && 𝑁𝑁 ≤ 15
Equation: x = ∑𝑁𝑁
𝑖𝑖=0 𝑖𝑖 Loop from 0 to N
Constraint: User has only two tries. tries ≤ 2
Output: x
3.4 Overflow and Underflow
Lab #1 Case Study – Stricting the number of
User Attempts
Solution:
1. Set a counter to 0
2. Ask user to enter integer N between 1 and 15
3. Check user input
a. If input is valid perform calculation
b. If input is invalid && counter has not equal to 2 (Extreme
Case)
 Increment counter
 Repeat step 2
4. Display Calculation and/or End Program 3.4 Overflow and Underflow
Lab #1 Case Study – Stricting the number of
User Attempts
Constraint #1: integer N between 1 and 15

𝑁𝑁 ≥ 1 && 𝑁𝑁 ≤ 15

What does this mean for valid vs. invalid inputs?

3.4 Overflow and Underflow


Increment/Decrement – change a value by 1

• Operators that changes a variable by 1


• Applies to a single variable
• Often used to update loop control variables

Syntax Prefix: (op)variable;


Syntax Postfix: variable(op);
Example: x++;
5.3 The increment and decrement operator
Lab #1 Case Study – Stricting the number of User
Attempts
Solution:
1. SET a counter to 0
2. PROMPT/GET user to enter integer N between 1 and 15
3. CHECK user input
a. IF input is valid perform calculation
b. IF input is invalid && counter less than 2 (Extreme Case)
 Increment counter
 Repeat step 2
4. DISPLAY Calculation and/or End Program
3.4 Overflow and Underflow
Lab #1 Case Study – Stricting the number of User
Attempts
Solution:
1. SET a counter to 0
2. PROMPT/GET user to enter integer N between 1 and 15
3. CHECK user input
a. IF input is valid perform calculation
b. IF input is invalid && counter less than 2 (Extreme Case)
 ++ counter
 Repeat step 2
4. DISPLAY Calculation and/or End Program
3.4 Overflow and Underflow
Operator Precedence 4.0 – Defines the priority
for evaluating operations in a program
Highest Significance Operator Description Type Associativity Week

Naming :: Scope Resolution General 1-2

Grouping ( ) ++ -- Parentheses post-fix incr/decr General 1-2, 5, 6

Unary + - ! ++ -- plus/minus negation pre-fix 2, 4, 5,6

Multiplicative * / % product quotient remainder Math / Logic


2
Additive + - add subtract

I/O << >> Insertion Extraction Stream 2

Comparison > >= < <= greater less Relational


4
Logic == != equal not equal Equality

Assigning = += -= *= /= %= Assignment General 2

Conditional && And


Logic 4
Logic || Or

Lowest Separator , Common General 1


Increment/Decrement – Operators Modes

Prefix mode
E.g. m = 3;
n = ++m;

Postfix mode
E.g. m = 3;
n = m++;

5.3 The increment and decrement operator


1.
2.
Increment/Decrement Operators
3. Example
4.
5. int num = 4 // num starts out with 4
6.
7. // display the value in num
8. cout << "The variable num is " << num << '\n’;
9. cout << "I will now increment num. \n\n";
10.
11. // User postfix ++ to increment num
12. num++;
13. cout << "Now the variable num is " << num << '\n’;
14. cout << "I will increment num again. \n\n";
15.
16. //User prefix ++ to increment num
17. ++num;
18. cout << "Now the variable num is " << num << '\n’;
19. cout << "I will decrement num again. \n\n";
20.
21. //User postfix -- to decrement num
22. num--;
23. cout << "Now the variable num is " << num << '\n’;
24. cout << "I will decrement num again. \n\n";
25.
26. //User prefix -- to decrement num
27. --num;
28. cout << "Now the variable num is " << num << '\n';
29.
30.
Increment/Decrement – Notes

Can be used in expressions:


result = num1++ + --num2;
Must be applied to something that has a memory.
Cannot have:
result = (num1 + num2)++;
Can be used in logical expressions:
if (++num > limit)
pre- and post-operations will cause different comparisons

5.3 The increment and decrement operator


Prefix vs. Postfix– Notes

 ++ and -- operators can be used in complex statements and


expressions

 In prefix mode (++val, --val)


1. increment/decrement variable’s value
2. use new value of variable in expression
 In postfix mode (val++, val--)
1. Use current value of the variable in expression
2. Increment/decrement variable’s value

5.3 The increment and decrement operator


1.
2.
Increment/Decrement Operators
3. Example
4.
5. int num, val = 12;
6.
7. cout << val++;
8. cout << ++val;
9.
10.
num = --val;
11.
12.
num = val--;
13.
14.
15.
Loop Design Patterns

1. Counter-Controlled
2. Sentinel-Controlled
3. Flag-Controlled

3.4 Overflow and Underflow


Counter – loop control variable that counts up/down

Requirements for counter-controlled loop:


1. Set the counter (initialize)
2. Test w/ counter
3. Execute loop code
4. Update counter (increment/decrement)
5. Repeat step 2

Note: Counter type should be an integer, not a float


5.4 The counter-controlled Loop
1.
2.
Counter-controlled w/ while Loop
3. Example
4.
5. unsigned num_tries = 0; Counter

6.
Test w/ counter
7. while (num_tries < 2)
8. {
9. num_tries++; update counter

10. }
11.
12. cout << "Number of tries is " << num_tries;
13.
14.
15.
Lab #1 Case Study – Stricting the number of User
Attempts
Solution:
1. SET a counter to 0
2. PROMPT/GET user to enter integer N between 1 and 15
3. CHECK user input
a. IF input is valid perform calculation
b. IF input is invalid && counter less than 2 (Extreme Case)
 ++ counter
 Repeat step 2
4. DISPLAY Calculation and/or End Program
3.4 Overflow and Underflow
1.
2.
Input Validation & Counting
3. Case-study Example Version 1
4. Counter Control variables

5. unsigned num_tries = 0, input;


6. cout << "Enter an integer N between 1 and 15: ";
7. cin >> input;
8. Invalid Input # of attempts
9. while ((input < 1 || input > 15)&& num_tries < 2){
10. cout << "Invalid entry, Enter an integer N between";
11. cout << " 1 and 15: ";
12. cin >> input; Update control #1

13. if (++num_tries == 2) Update control #2


14. return 0;
15. }
1.
2.
Running Total
3. Example
4.
5. unsigned total = 0, input; INITIALIZE total

6.
7. cout << "Enter an integer N between 1 and 15: "; PROMPT

8. cin >> input; GET input

9.
10. for (unsigned i = 0; i <= input; i++)
11. total += i; UPDATE total

12.
13. cout << "The sum of all numbers from 0 to "
14. << input << " is " << total; DISPLAY total

15.
Sentinel – a specific pre-determined value used to
signal the end of reading input
Sentinel Loop Strategy:
1. Set the sentinel (initialize)
2. Test w/ sentinel and control variable
3. Execute loop code
4. Read the next data item into control variable (update)
5. Repeat step 2

Note: Has same type as the input data read in


5.6 The sentinel-controlled Loop
1.
2.
Sentinel Controlled Loop
3. Example
4.
5. int grade = 0, sum = 0, num_students = 30;
6. const int SENTINEL = -1; INITIALIZE sentinel

7. cout << “Enter the grade or -1 to finish\n"; PROMPT

8. cin >> grade; GET input

9.
10. while (grade != SENTINEL) { TEST control w/ SENTINEL

11. sum = sum + grade;


12. num_students = num_students + 1;
13. cout << "Please insert the grade or -1 to finish\n";

14. cin >> grade; UPDATE control

15. }
Flag – a variable that signals that a condition has
been met
Flag Loop Strategy:
1. Set the flag (initialize)
2. Test w/ flag (condition not met)
3. Execute loop code
4. CHECK if condition is met (update flag)
5. Repeat step 2

Note: Flags can be integers or bools


1.
2.
Flag Controlled Loop
3. Example
4.
5. int grade, sum = 0, num_students = 0;
6. bool isValid = false; // flag INITIALIZE flag

7.
8. // validate input
9. while (!isValid) TEST w/ flag

10. {
11. cout << "Enter the grade : \n";
DO something
12. cin >> grade;
13. isValid = grade > 0; UPDATE flag

14. }
15.
do-while loop – Pos-test loop that repeats while a
condition is satisfied
Looping
entry • post-test – a loop that tests after
conditional code is executed
statement true
• Only Loop that ends with a semi-colon
condition
Syntax: do
false statement;
Syntax: while(condition);

exit
5.7 The do-while Loop
do-while Loop – Mechanics

1. Initialize a control variable


2. Execute some code / Update control variable
3. Perform test w/ control variable
4. While test is true repeat Step 2

Syntax: init-control;
do{
execute / update-control
} while(test-control);
5.7 The do-while Loop
1.
2.
do-while Loop
3. Example
4.
5. int grade, sum = 0, num_students = 0; INITIALIZE control

6. do{
7. cout << “Enter the grade or -1 to finish\n";
8. cin >> grade; UPDATE control

9.
10. if(grade != -1){ DO something

11. sum = sum + grade;


12. num_students = num_students + 1;
13. }
14. } while (grade != -1); TEST w/ control

15.
1.
2.
Input Validation & Counting
3. Case-study Example Version 2
4.
5. unsigned num_tries = 0, input; INITIALIZE Control variables
6. do{ Do Something

7. if (num_tries == 2) TEST w/ control

8. return 0;
9. cout << "Enter an integer N between 1 and 15: ";
10. cin >> input;
11. Update control(s)

12. num_tries++;
13. } while (input < 1 || input > 15 ); TEST w/ control

14.
15.
do-while Loop – Notes

• Loop always executes at least once


• Execution continues as long as expression is true
• Useful in menu-driven programs to bring user back to menu to
make another choice
• Often used to implement data-validation

5.7 The do-while Loop


for loop – Pre-test loop that repeats for a finite
number of iterations
Looping
entry • pre-test – a loop that tests before
repeating the conditional code
condition true statement • Uses the counter-controlled strategy

Syntax:for(init; test; update)


false body

exit
5.8 The for Loop
for Loop – Mechanics

1. Initialize a control variable


2. Perform test w/ control variable
3. While test is true
4. Execute some code
5. Update control variable

Syntax: for(init-ctrl; test-ctrl; update)


body

5.8 The for Loop


1.
2.
Repeated Phrase
3. Example
4. INITIALIZE
5. int count;
6. TEST UPDATE
7. for (count = 1; count <= 5; count++)
8. cout << “Hello” << endl; DO something

9.
10.
11.
12.
13.
14.
15. 5.8 The for Loop
1.
2.
Factorial
3. Example
4.
5. int count;
6.
7. int product, n;
8. product = 1;
9. cin >> n;
10. INITIALIZE TEST UPDATE
11. for (int i = n; i > 1; i--)
12. product *= i; DO something

13.
14. cout << n << "! = " << product;
15.
1.
2.
Multiple Initialization/Test/Updates
3. Example
4.
5. int count;
6. INITIALIZE
7. int x, y;
8. TEST UPDATE
9. for (x = 1, y = 1; x <= 5, y <= 3; x++, y++)
10. {
11. cout << x << " plus " << y << " equals «
DO something
12. << (x + y) << endl;
13. }
14.
15.
for Loop – Notes

• Usually used when:


1. Initialization at the start of the loop is required
2. Update after each iteration is required
3. You know how many times you need to repeat something
• Initialization can be optional if you already initialized a control
variable
• Test is optional, jump statement would be required to end loop

5.8 The for Loop


Deciding Which Loop to Use
• The while loop is a conditional pretest loop
• Iterates as long as a certain condition exits
• Validating input
• Reading lists of data terminated by a sentinel

• The do-while loop is a conditional posttest loop


• Always iterates at least once
• Repeating a menu

• The for loop is a pretest loop


• Built-in expressions for initializing, testing, and updating
• Situations where the exact number of iterations is known

5.9 Deciding Which Loop to Use


Nested Loops – Loop contained inside of another
loop
entry

condition#1
Condition true statement1 entry

false
Condition #2 true statement1
statement2
false

statement3

exit exit

5.10 Nested Loop


Nested Loops

• A nested loop has two parts:


1. Inner (inside) loop
2. Outer (outside) loop

for (init;
(row=1;test;
row<=3; row++)
condition) //outer
for (col=1; col<=3; col++)
statement; //inner
cout << row * col << endl;

5.10 Nested Loop


Nested Loop - Notes

• Inner loop goes through all repetitions for each repetition of


outer loop

• Inner loop repetitions complete sooner than outer loop

• Total number of repetitions for inner loop is product of number


of repetitions of the two loops.

5.10 Nested Loop


1.
2.
Nested Loop
3. Example
4.
5. cout << setw(12) << "i" << setw(6) << "j\n";
6.
7. for (int i = 0; i < 4; i++)
8. { Outer Loop

9. cout << "Outer" << setw(7) << i << endl;


10. for (int j = 0; j < i; ++)
11. cout << " Inner" << setw(10) << j << endl; Inner Loop

12. } // end outer loop


13.
14.
15.
Nested for Loop

51
1.
2.
Nested Loop
3. Example
4.
5. for (int row = 0; row < 11; row++)
6. { Outer Loop
7. cout << "Multiples of " << row << endl;
8. for (int col = 0; col < 11; col++) {
9. cout << row << " x " << col << " = " << row * col
10. << " " << endl; Inner Loop
11. }
12. cout << endl;
13. }
14.
15.
Nested Loop – Multiplication Table

53
Jumping Loops – Jump statements alter the control
flow of loops
• continue – skips to the next iteration of the loop
• break – ends the execution of the loop (poor design)

Syntax: break;
Syntax Pcontinue;

5.11 Breaking Out of A Loop


1.
2.
Nested for Loop w/ continue
3. Example
iteration
4.
5. for (int i = 0; i < 100; i++){
6. if (i % 5 != 0 || i % 13 != 0) Outer Loop
7. continue; JUMP
8. int total = 0;
9.
10. for (int j = 0; j < i; j++){
11. total += j;
12. } Inner Loop

13. cout << total << endl;


14. }
15.

You might also like