0% found this document useful (0 votes)
6 views21 pages

Lecture 03 - Repetition

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)
6 views21 pages

Lecture 03 - Repetition

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/ 21

3/9/2022

“You cannot download success!”


- Unknown
Control Structures
• Controls the flow of program execution
CSE102 • Sequence
• Selection

Computer Programming with C • Repetition


• Repetition structure
• Repetition of steps (loop body): loop
• while, for, and do-while statements
2021-2022 Spring Semester • Each has advantages for some type of repetitions
Repetition • Ex: calculate payroll for several employees
© 2015-2022 Yakup Genç

March 2022 CSE102 Computer Programming 2

Repetition Loop Choice

• How to design repetition


• Solve the problem for a specific case
• Try to generalize
• Answer the following questions for repetition
• Do I need to repeat any step?
• How many times to repeat the steps?
• How long to continue repetition?
• Decide on the loop type based on the answers.
• The flow chart on the next slide

March 2022 CSE102 Computer Programming 3 March 2022 CSE102 Computer Programming 4

1
3/9/2022

Comparison of Loop Kinds Counter Controlled Loop


• Repetition is managed by a loop control variable
• For example a counter

General format:
set counter to 0 /* initialization */
while counter < final value /* test */
do one or more things /* loop body */
increase counter by one /* updating */

March 2022 CSE102 Computer Programming 5 March 2022 CSE102 Computer Programming 6

Flowchart for a while Loop Program Fragment with a Loop

March 2022 CSE102 Computer Programming 7 March 2022 CSE102 Computer Programming 8

2
3/9/2022

while statement Payroll calculator


General syntax: • Calculate payroll for several employees
while (loop repetition control) • Calculate the total payroll as well
statement • Input:
• For each employee
Example • Hours, rate, pay
count_star = 0; • Number of employees
while (count_star < N) { • Output
printf(“*”); • For each employee
count_star = count_star +1; • Payroll

} • Total payroll

March 2022 CSE102 Computer Programming 9 March 2022 CSE102 Computer Programming 10

Payroll calculator Payroll calculator

(continued)

March 2022 CSE102 Computer Programming 11 March 2022 CSE102 Computer Programming 12

3
3/9/2022

Generalized conditional loop Compound assignment


• Ex: multiplying a list of numbers Simple assignment Compound assignment
• Ask for numbers
• Multiply as long as the product is less than 10000 count = count + 1; count += 1;
time = time – 1; time -= 1;
product = 1;
while (product < 10000){
product = product * item; product *= item;
printf(“%d \n Enter next item >”, product); n = n / (d + 1); n /= (d + 1);
scanf(“%d”, &item);
value = value % 7; value %= 7;
product = product * item;
}

In general: In general:
var = var op exp var op= exp

March 2022 CSE102 Computer Programming 13 March 2022 CSE102 Computer Programming 14

for statement for Statement in a Counting Loop


• for statement is another repetition structure
• supplies a designated space for each of the loop components
• Initialization of the loop control variable
• Test of the loop repetition control
• Change of the loop control variable

• Syntax:
for (intialization expression;
loop repetition condition;
update expression)
statement;

March 2022 CSE102 Computer Programming 15 March 2022 CSE102 Computer Programming 16

4
3/9/2022

for statement Increment and Decrement Operators

for (count_star = 0; • Unary operators


count_star < N; • Side effect
count_star += 1) • ++ increments the operand
printf(“*”); • -- decrements the operand
• The value of the operation depends on the position of the operator
for (i = 0; i < max; i +=1) • Pre-increment : operand is after the operator
• Value is the variable’s value after incrementing
printf(“%d \n”, i); • Post-increment : operand is before the operator
• Value is the variable’s value before incrementing
for (product = 1; product < 10000; product *= item) • Similar for decrement operator
scanf(“%d”, &item);
March 2022 CSE102 Computer Programming 17 March 2022 CSE102 Computer Programming 18

Prefix and Postfix Increments Increment and Decrement Operators

• What is the result of following code fragments


n = 4;
printf(“%3d”, --n);
printf(“%3d”, n);
printf(“%3d”, n--);
printf(“%3d”, n);
y = n * 4 + ++n;
x = n++ * --n;

• Write a function to compute factorial of an integer

March 2022 CSE102 Computer Programming 19 March 2022 CSE102 Computer Programming 20

5
3/9/2022

Function to Compute Factorial

March 2022 CSE102 Computer Programming 21 March 2022 CSE102 Computer Programming 22

Conditional Loops Conditional Loops


• If you do not know exact number of repetitions • Ex: Monitoring gasoline supply
• Ex: ensuring valid user input • Capacity 80000 barrels
• Continue to prompt user to enter a value as long as the response is not reasonable • Use of gasoline is entered in gallons
• 1 barrel = 42 gallons
Print an initial prompting message • Alert if the supply falls below 10% of the capacity
Get the number of observed values • Input:
While the number of value is negative • Current supply
Print a warning message and ask for another value • Several uses
Get the number of observed values
• Output
• Where is initialization, test and update steps? • Remaining supply
• How to write the loop in C? • Alert

March 2022 CSE102 Computer Programming 23 March 2022 CSE102 Computer Programming 24

6
3/9/2022

Monitoring Gasoline Storage Tank

(continued)
March 2022 CSE102 Computer Programming 25 March 2022 CSE102 Computer Programming 26

Monitoring Gasoline Storage Tank Monitoring Gasoline Storage Tank

March 2022 CSE102 Computer Programming 27 March 2022 CSE102 Computer Programming 28

7
3/9/2022

Sentinel Controlled Loops Sentinel Controlled Loops


• Input one additional data item at each repetition • Ex: Calculate sum of a collection of exam scores
• Usually number of items is not known in advance • Assume the number of students in not known
• When to stop reading data?
• What is the sentinel value?
• Sentinel value: unique value to stop repetition
• Should be an abnormal value • Input:
• Exam score
Get a line of data • Output:
While the sentinel value has not been encountered
Process the data line • Sum of scores
Get another line of data

• Where is initialization, test and update stages


March 2022 CSE102 Computer Programming 29 March 2022 CSE102 Computer Programming 30

Sentinel Controlled Loops Sentinel Controlled Loops


Algorithm: Correct Algorithm:

Initialize sum to zero Initialize sum to zero


while score is not the sentinel Get the first score
Get score while score is not the sentinel
Add score to sum Add score to sum
Get score

March 2022 CSE102 Computer Programming 31 March 2022 CSE102 Computer Programming 32

8
3/9/2022

Sentinel-Controlled while Loop Sentinel-Controlled for Loop

• Can we use for statement for sentinel controlled loops?

March 2022 CSE102 Computer Programming 33 March 2022 CSE102 Computer Programming 34

Sentinel-Controlled for Loop End-file Controlled Loops


Ex: Calculate sum of a list of integers in a file
• A data file is terminated by an endfile character
• detected by fscanf functions.
• special sentinel value is not required
• uses the status value returned by fscanf

printf(……); Algorithm:
for (scanf(“%d”,&score); Initialize sum to zero
score != SENTINEL; Read the first value
scanf(“%d”,&score)) { while end of file is not reached
sum += score; Add value to sum
printf(…….); Read the next value
}
March 2022 CSE102 Computer Programming 35 March 2022 CSE102 Computer Programming 36
36

9
3/9/2022

******* int i,j,n;


*******
******* n = 7;
*******
******* for (j=0;j<n;j++) {
******* for (i=0;i<n;i++) printf(“*”);
******* printf(“\n”);
}

March 2022 CSE102 Computer Programming 37 March 2022 CSE102 Computer Programming 38

End-file Controlled Loops


void printline(int n); void printline(int n) {
void main () { int i;
int i,j,n; for (i=0;i<n;i++) rintf(“*”);
n = 7; printf(“\n”;
for (j=0;j<n;j++) { }
printline(n);
}
}

March 2022 CSE102 Computer Programming 39 March 2022 CSE102 Computer Programming 40

10
3/9/2022

Infinite Loop on Faulty Data Infinite Loop on Faulty Data


• If the file contains a faulty data 7o, fscanf • Solution: Change the loop repetition condition to
• stops at the letter ‘o’, while (input_status == 1)
• stores the value 7 in score • loop exits on
• leaves the letter ‘o’ unprocessed.
• end of file (input_status negative) OR
• returns a status value of one
• faulty data (input_status zero)
• On the next loop iteration, fscanf
• finds the letter ‘o’ awaiting processing
• leaves the variable score unchanged • Add an if statement after the loop to decide whether to print the results or to warn of
• leaves the letter ' o ' unprocessed, bad input.
• returns a status value of zero
if (input_status == EOF)
• In the previous program printf (’Sum of exam scores is %d\n", sum);
• the return value of fscanf is not checked for values other than EOF else {
• unsuccessful attempt to process the letter ‘o’ repeats over and over. fscanf (inp, “%c”, &bad_char);
printf("*** Error in input: %c ***\", bad_char);
Infinite loop!... }

March 2022 CSE102 Computer Programming 41 March 2022 CSE102 Computer Programming 42

Nested Loops Nested Loops


• Loops may be nested like other control structures.
• an outer loop with one or more inner loops.
• Each time the outer loop is repeated, the inner loops are reentered,

Ex: Audubon Club members’ sightings of bald eagles

• Input: for each month a group of integers followed by a zero


• Output: for each month total sightings

• program contains a sentinel loop (for sightings in a month) nested within a


counting loop (for months).

March 2022 CSE102 Computer Programming 43 March 2022 CSE102 Computer Programming 44

11
3/9/2022

Nested Loops Nested Loops


• Ex: a simple program with two nested counting Ioops.
• The outer loop is repeated three times (for i = 1, 2 3).
• The number of times the inner loop is repeated depends on the current value
of i.

March 2022 CSE102 Computer Programming 45 March 2022 CSE102 Computer Programming 46

Nested Loops Nested Loops


• The output of the algorithm:

March 2022 CSE102 Computer Programming 47 March 2022 CSE102 Computer Programming 48

12
3/9/2022

Nested Loops do-while Statement

• What is displayed by the following program segments, assuming m is 3 and n is 5? • for statements and while statements evaluate loop repetition condition before
the first execution of the loop body.
• Pretest is usually undesirable
• when there may be no data items to process
• when the initial value of the loop control variable is outside its expected range.
• Sometimes loop must execute at least once
• Ex: interactive input

1. Get a data value.


2. If data value isn’t in the acceptable range, go back to step 1.

March 2022 CSE102 Computer Programming 49 March 2022 CSE102 Computer Programming 50

do-while Statement do-while Statement

• C provides the do-while statement to implement such loops • SYNTAX:


do {
1. Get a data value. statements
2. If data value isn’t in the acceptable range, go back to step 1. } while ( loop repetition condition );

do { • Ex: Find first even input


printf(“Enter a letter from A to E> ”);
scanf(“%c”, &letter); do
status = scanf(”%d”, &num);
} while (letter < ‘A’ || letter > ‘E’);
while (status > 0 && (num % 2) != 0);

March 2022 CSE102 Computer Programming 51 March 2022 CSE102 Computer Programming 52

13
3/9/2022

Flag Controled Loops

• If loop repetition condition is complex


• Use a flag is a type int (values: 1 (true) and 0 (false))
• Flag represents whether a certain event has occurred.

• Ex: Input Validation


• The do-while is often used in checking for valid input
• An input is always needed
• Two nested loops
• Repeat reading input when the input is not valid
• not in range OR not a number
• Repeat reading input to skip invalid input line
• Not to have infinite loop

March 2022 CSE102 Computer Programming 53 March 2022 CSE102 Computer Programming 54

Flag Controled Loops

• Execution results

Enter an integer in the range from 10 to 20 inclusive> @20


Invalid character >>@>>. Skipping rest of line.
Enter an integer in the range from 10 to 20 inclusive> 2o
Number 2 is not in range.
Enter an integer in the range from 10 to 20 inclusive> 20

March 2022 CSE102 Computer Programming 55 March 2022 CSE102 Computer Programming 56
56

14
3/9/2022

Do While Statement and Flag Controled Loops Do While Statement and Flag Controled Loops

• Do they behave similarly? Why? • Which of the following code is better way to implement a sentinel-controlled loop?
Why?
do {
scanf(“%d”, &num);
scanf(“%d”, &num); /* process num */ scanf(“%d”, &num);
while (num != SENT) { do {
} while (num != SENT); while (num != SENT) {
/* process num */ /* process num */
scanf(“%d”, &num);
scanf(“%d”, &num); scanf(“%d”, &num); if (num != SENT)
} } /* process num */
} while (num != SENT);

March 2022 CSE102 Computer Programming 57 March 2022 CSE102 Computer Programming 58
58

Do While Statement and Flag Controled Loops Case Study:


• Rewrite the following code using do-while statement with no decisions in the Problem: Collecting area for Solar-Heated House
loop body:

• Area depends on several factors


sum = 0; • the average number of heating degree days for each month
for (odd = 1; odd < n; odd+=2) • the product of the average difference between inside and outside temperatures and the
number of days in the month
sum += odd;
• the average solar insolation for each month
• rate at which solar radiation falls on one square foot of a given location
• heating requirement per square foot of floor space
• floor space
• efficiency of the collection method

March 2022 CSE102 Computer Programming 59 March 2022 CSE102 Computer Programming 60
59

15
3/9/2022

Case Study: Case Study:


• The formula for the desired collecting area (A) Problem Inputs
Average heating degree days file
A = heat loss / energy source Average solar insolation file
heat_deg_days /* average heating degree days for coldest month */ coldest_mon /* coldest
• heat loss is the product of the heating requirement, the floor space, and the month (number 1..12)
solar_insol /* average daily solar insolation for coldest month*/ heating_req
heating degree days. /* Btu/degree day Ft2 */
• energy resource is the product of the efficiency of the collection method, the efficiency /* % of solar insolation converted to usable heat */ floor_space /*
average solar insolation per day and the number of days. square feet */

Program Variables
energy_resrc /* usable solar energy available in coldest month
• Two data files (Btus obtained from 1 Ft2 of collecting area) */
• hdd.txt contains numbers representing the average heating degree days for
each months. Problem Outputs
heat_loss /* Btus of heat lost by structure in coldest month */ collect_area /*
• solar.txt contains the average solar insolation for each month approximate size Ft2 of collecting area needed */

March 2022 CSE102 Computer Programming 61 March 2022 CSE102 Computer Programming 62

Case Study:
• Algorithm
1. Determine the coldest month and the average heating degree days for this
month.
2. Find the average daily solar insolation per Ft2 for the coldest month.
3. Get the other problem inputs from the user :
heating_req, efficiency, floor_space.
1. Estimate the collecting area needed.
2. Display results.

March 2022 CSE102 Computer Programming 63 March 2022 CSE102 Computer Programming 64

16
3/9/2022

Program to Approximate Solar Collecting Area Size

March 2022 CSE102 Computer Programming 65 March 2022 CSE102 Computer Programming 66

March 2022 CSE102 Computer Programming 67 March 2022 CSE102 Computer Programming 68

17
3/9/2022

March 2022 CSE102 Computer Programming 69 March 2022 CSE102 Computer Programming 70

Altering Normal Operation of a Loop Altering Normal Operation of a Loop

March 2022 CSE102 Computer Programming 71 March 2022 CSE102 Computer Programming 72

18
3/9/2022

Altering Normal Operation of a Loop Altering Normal Operation of a Loop

March 2022 CSE102 Computer Programming 73 March 2022 CSE102 Computer Programming 74

How to Debug and Test Programs Common Programming Errors

• Error Types: Of-by-one Loop Errors


• syntax errors
• run time errors • A common logic error with loops
• logic errors • loop executes one more time or one less time than required
• run-time error or logic error is usually not obvious • In sentinel-controlled loops, an extra repetition is more dangerous.
• you may spend considerable time and energy locating it. • In counting loops, the initial and final values of counter should be correct and
the loop repetition condition should be right.
• Method: • Ex: the following loop body executes n + 1 times instead of n times.
• examine the program output and determine program part generating incorrect results for (i=0; i <= n; ++i)
• focus on the statements and try to determine the fault
sum += i;
• OR
• Use Debugger programs
• Debug without debugger

March 2022 CSE102 Computer Programming 75 March 2022 CSE102 Computer Programming 76

19
3/9/2022

Common Programming Errors Common Programming Errors


• Don’t Confuse • Don’t forget!!
• Use if statement to implement decision step !!
• Use while statement to implement loop !! = : is assigment operator
== : is equality operator
• In using while or for statements, don’t forget that
• The structure assumes that the loop body is a single statement!!
• Use (always) braces for consisting multiple statements !! • Wrong!! True
• Keep in mind that compiler ignore indentation!! while (x=1) while (x==1)
• Ex : x is 1000 and max is 0;
Wrong!! (infinite loop) True ….. ……..
while (x > max) while (x > max) {
sum+=x; sum+=x;
x++; x++;
}

March 2022 CSE102 Computer Programming 77 March 2022 CSE102 Computer Programming 78

Common Programming Errors Common Programming Errors


Brace Hierarchy • Improper usage of compound statement
a = a * b + c
if(ans==‘Y’){ there is no short way of doing this.
while(x > 0){
x--; • Do not use increment decrement operators twice for the same
sum += x; /* missing brace } */ operands on the same expression.
}
else /* compiler error here */

March 2022 CSE102 Computer Programming 79 March 2022 CSE102 Computer Programming 80
79 80

20
3/9/2022

Thanks for listening!

21

You might also like