CSC425 - Chapter 4 (Part 1)
CSC425 - Chapter 4 (Part 1)
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;
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
i=i+1
Sentinel-controlled loops
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
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