0% found this document useful (0 votes)
16 views

CSC425 - Chapter 4 (Part 1)

The document discusses repetition or looping control structures in programming. It covers the different types of loops - while, do-while and for loops. It explains that loops allow statements to repeat efficiently using variables. Examples are given to illustrate how loops can input and process multiple values with fewer variables than without loops. The key components of a loop statement - initialization, evaluation and updating the loop counter - are explained. Finally, counter-controlled and sentinel-controlled loops are introduced.

Uploaded by

Apis Zizan
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 views

CSC425 - Chapter 4 (Part 1)

The document discusses repetition or looping control structures in programming. It covers the different types of loops - while, do-while and for loops. It explains that loops allow statements to repeat efficiently using variables. Examples are given to illustrate how loops can input and process multiple values with fewer variables than without loops. The key components of a loop statement - initialization, evaluation and updating the loop counter - are explained. Finally, counter-controlled and sentinel-controlled loops are introduced.

Uploaded by

Apis Zizan
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
You are on page 1/ 44

CHAPTER 4[PART 1]

Control Structure III: Repetition / Looping


Lesson Outcomes
 At the end of these lessons, students should be able to:
 Learn about repetition (looping) control structures.
 Understand the requirement of while , do-while and for in a program.
 Identify while , do-while and for design structure.

 Explore how to construct and use counter-controlled and


sentinel-controlled loop.
 Discover how to form and use nested control structures.
Overview
 Loop: a control structure that causes a statement or group of
statements to repeat.
 Why Is Repetition Needed?
 Repetition allows you to efficiently use variables.
 Can input, add, and average multiple numbers using a limited
number of variables.
 For example, to add five numbers:
 Declare a variable for each number, input the numbers and add the
variables together.
 Create a loop that reads a number into a variable and adds it to a variable
that contains the sum of the numbers.
Example 1
Without Using Repetition Using Repetition
Statement Statement

int main() int main()


{ {
cout<<"Hello! World"<<endl; int i = 1;
cout<<"Hello! World"<<endl; while(i<= 5)
cout<<"Hello! World"<<endl; {
cout<<"Hello! World"<<endl; cout<<“Hello! World”
<<endl;
cout<<"Hello! World"<<endl;
i++;
cout<< Hello! World <<endl;
}
return 0;
return 0;
}
}
Example 2 Using Repetition
Without Using Repetition Statement
Statement
int main()
{
int main()
int num, sum=0;
{ int i = 1;
while(i<= 5)
int num1,num2,num3,num4,num5,sum;
{
cout<<"Enter 5 numbers: "; cout<<“Enter a number”;
cin>>num1>>num2>>num3>>num4>>num5; cin>>num;
i= i + 1;
sum=num1+num2+num3+num4+num5; sum = sum + num;
cout<<“The sum is ”<<sum; }
cout<<“The sum is ”<<sum;
return 0;
return 0;
} }

Number of variables used = 6


Number of variables used = 3
Components of Loop Statement
 Initialization
 Initialize the loop control variable (LCV)

 Evaluation
 Test the loop control variable – to determine whether the
looping should continue or not
 Updating
 Update/change loop control variable – the
increment/decrement by which the control variable is modified
each time through the loop
Example
int main() i is loop control variable (LCV)
{
int i = 1; <-- initialize the loop control variable
while(i<= 5) <-- test the loop control variable
{
cout<<“Hello! World”<<endl; <-- statement to be executed
i = i + 1; <-- change/modify the loop control variable
}
return 0;
}
Example
int main()
{
int num, sum=0;
int i = 1; Initialize loop control variable (LCV)
while(i<= 5)
Body of loop { Test the loop control variable (LCV)
-This code is cout<<“Enter a number”;
executed as long as
cin>>num;
the condition is
TRUE and is sum = sum + num;
skipped when the i = i + 1; Change/modify the loop control
condition is FALSE } variable (LCV)
cout<<“The sum is ”<<sum;
return 0;
}
Pseudocode
Start
set i=1, sum=0
While (i <=5)
display “Enter a number”
get num;
sum = sum + num;
i=i+1
EndWhile
Display “The sum is ”, sum;
end
Flow Chart i = 1, sum = 0

i <= 5 false

true
Display “Enter a number”
Get num

sum=sum + num

i=i+1

Display “The
sum is”, sum
The Increment & Decrement Operator
 ++ is the increment operator.
It adds one to a variable.
val++; is the same as val = val + 1;

 ++ can be used before (prefix) or after (postfix) a variable:


++val; val++;
The Increment & Decrement Operator
(cont.)
 -- is the decrement operator.
It subtracts one from a variable.
val--; is the same as val = val - 1;

 -- can be also used before (prefix) or after (postfix) a


variable:
--val; val--;
Prefix vs. Postfix
 ++ and -- operators can be used in complex statements
and expressions
 In prefix mode (++val, --val) the operator
increments or decrements, then returns the value of the
variable
 In postfix mode (val++, val--) the operator returns
the value of the variable, then increments or decrements
Prefix vs. Postfix - Examples
int num, val = 12;
cout << val++; // displays 12,
// val is now 13;
cout << ++val; // sets val to 14,
// then displays it
num = --val; // sets val to 13,
// stores 13 in num
num = val--; // stores 13 in num,
// sets val to 12
Basic Types
 Three types of repetition control structures:
 the while loop
 the do-while loop
 the for loop

 The difference between these structures is how they control


the repetition.
Repetition Structure

while loop
Pre-test:
Condition is
tested first
Repetition for loop
Structure
Post-test:
condition is tested do-while loop
later
Pre- Test
i = 1, sum = 0
Condition is tested
first

i <= 5 false

true
Display “Enter a number”
Get num

sum=sum + num

i=i+1

Display “The
sum is”, sum
Post-Test
i = 1, sum = 0

Display “Enter a number “


Get num
Condition is tested The loop body will be
later executed at least once
sum = sum + num

i=i+1

true false Display “The


i <= 5
sum is “,sum
How Loops are Controlled
Counter-controlled loops

• Know exactly how many times certain


statements need to be executed.

Sentinel-controlled loops

• Do not always know how many pieces of data


need to be read, but you may know that the last
entry is a special value (sentinel).
Counter-controlled Loop
while Loop Syntax
 The general form of the while statement is:

 while is a reserved word.


 The statement can be simple or compound
while Loop Syntax (cont.)
 The expression acts as a decision maker and is usually a
logical expression (return true or false)
 The statement is called the body of the loop
 The parentheses are part of the syntax
Steps of Actions
 Step 1. Condition is evaluated
 Step 2. If condition is TRUE:
 the specified statement or body of loop executed.
 go back to step 1

 Step 3. Otherwise (if condition is FALSE):


 The loop terminates and the control transferred to the next
statement following it.
General Form of while Loop
 Syntax:
LCV = initial_value; //initialize the LCV
while(LCV <= final_value)//expression test the LCV
{
statement_to_be_executed;
:
LCV = LCV + step; //update the LCV
}
Flowchart
LCV = initial Value

false
Test LCV
true

Step x

Update LCV

Step n
Example
 Consider:
int count = 0; //initialize the LCV
while (count < 3) //test the LCV
{
cout << “Hi” << endl; //Loop Body
count = count + 1; //Update LCV
}
 Loop body executes how many times?
Tracing Table
count
count < 3 Output
(count = count + 1)
0 0 < 3 (T) Hi
1 1 < 3 (T) Hi
2 2 < 3 (T) Hi
3 3 < 3 (F) exit

So, loop body executes 3 times


Exercise 1 (while loop)
for Loop
Introduction
 A for loop simplifies the writing of a counter-controlled
while loop
 Also known as pretest loop.

 In C++, for is a reserved word.


 The syntax of the for loop is:
for(initializeLCV; testCondition; updateLCV)
{
statements
}
Introduction (cont.)
 for structure:
Introduction (cont.)
 The for loop executes as follows:
 1. the initial statement executes.
 2. the loop condition is evaluated. If the loop condition
evaluates to true:
 i. Execute the for loop statemant(s) (loop body)
 ii. Execute the update statement (the third expression in the parentheses)

 Repeat Step 2 until the loop condition evaluates to false.


Introduction (cont.)
 Example:
Introduction (cont.)
 Example:
 You can count backward using for loop
for(int i = 10;i > 0; i--)
cout << i << " ";
cout << endl;

Output:
10 9 8 7 6 5 4 3 2 1
Introduction (cont.)
 Putting a semicolon at the end of the for loop (before the
body of the for loop) is a semantic error. In this case, the
action of the for loop is empty.
 Example:
for(int i = 0;i < 5; i++);//Line 1
cout << "*" << endl;//Line 2

 The semicolon at the end of the for statement (Line 1)


terminates the for loop.
 The action of this for loop is empty, that is, null.
Exercise 1
 Find the output for the following segment code:
int w = 0;
for (int i = 0; i < 4; i++)
{
w = 2 + w * 5 – i;
cout << w << “ “;
}
cout << endl;
do-while Loop
Introduction
 Executes at least once and up to many times depending on
expression.
 Syntax of do...while statement:

 In C++, do is a reserved word.


 Statement can be simple or compound (multiple statements); if
compound, they must be in braces.
Introduction (cont.)
 do...while loop executes as follows:
 The statement executes first, and then expression is evaluated.
 If expression evaluates to true, statement executes again.
 As long as expression in a do...while statement is
true, statement executes.
 Like other loops, to avoid an infinite loop, loop body must
contain a statement that makes expression false.
Introduction (cont.)
 Example:
//printing 1 - 10 using do while loop
int num=1; //initialize the LCV, num
do
{
cout << num << " " ;
num=num + 1; //update the lCV
} while(num <= 10); //test the LCV
Introduction (cont.)
 A do...while loop can be used for input validation.
 For example, a program prompts a user to enter a test score,
which must be greater than or equal to 0 and less than or equal
to 50. If the user enters a score less than 0 or greater than 50,
the user should be prompted to re-enter the score.
Exercise 1 (do…while loop)
 Find the output for the following segment code:
Infinite Loop
 Infinite Loop: continues to execute endlessly
 Example:

 How do you avoid an infinite loop?


 Verify that the loop’s body contains statement(s) that assure the
exit condition will eventually be false.
TO BE CONTINUED…

You might also like