C Programming Language - Repetition
C Programming Language - Repetition
Computer Programming
Control Structures
Controls the flow of program execution
Sequence Selection Repetition
Repetition structure
Repetition of steps (loop body) : loop while, for, and do-while statements
Each has advantages for some type ofrepetitions
Repetition
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?
Loop Choice
General format: set counter to 0 while counter < final value do something increase counter by one
GIT Computer Engineering Department
while statement
General syntax: while (loop repetition control) statement Example count_star = 0; while (count_star < N) { printf(*); count_star = count_star +1; }
GIT Computer Engineering Department
9
Payroll calculator
Calculate payroll for several employees
Calculate the total payroll as well
Input:
For each employee
Hours, rate, pay
Number of employees
Output
For each employee
Payroll
Total payroll
GIT Computer Engineering Department
10
11
12
13
Compound assignment
Simple assignment count = count + 1; time = time 1; product = product * item; n = n / (d + 1); value = value % 7; In general: var = var op exp Compound assignment count += 1; time -= 1; product *= item; n /= (d + 1); value %= 7; In general: var op= exp
14
for statement
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;
GIT Computer Engineering Department
15
16
for statement
for (count_star = 0; count_star < N; count_star += 1) printf(*); for (i = 0; i < max; i +=1) printf(%d \n, i); for (product = 1; product < 10000; product *= item) scanf(%d, &item);
GIT Computer Engineering Department
17
19
21
22
Conditional Loops
If you do not know exact number of repetitions Ex: ensuring valid user input
Continue to prompt user to enter a value as long as the response is not reasonable Print an initial prompting message Get the number of observed values While the number of value is negative Print a warning message and ask for another value Get the number of observed values
Conditional Loops
Ex: Monitoring gasoline supply
Capacity 80000 barrels Use of gasoline is entered in gallons
1 barrel = 42 gallons
Input:
Current supply Several uses
Output
Remaining supply Alert
GIT Computer Engineering Department
24
25
26
27
Input:
Exam score
Output:
Sum of scores
29
30
31
32
33
34
Algorithm: Initialize sum to zero Read the first value while end of file is not reached Add value to sum Read the next value
GIT Computer Engineering Department
35
36
Infinite loop!...
GIT Computer Engineering Department
37
Add an if statement after the loop to decide whether to print the results or to warn of bad input.
if (input_status == EOF) printf (Sum of exam scores is %d\n", sum); else { fscanf (inp, %c, &bad_char); printf("*** Error in input: %c ***\", bad_char); }
GIT Computer Engineering Department
38
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).
39
Nested Loops
40
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.
41
Nested Loops
42
Nested Loops
The output of the algorithm:
43
Nested Loops
What is displayed by the following program segments, assuming m is 3 and n is 5?
44
do-while Statement
for statements and while statements evaluate loop repetition condition before the first execution of the loop body. Pretest is usually desirable
when there may be no data items to process when the initial value of the loop control variable is outside its expected range.
45
do-while Statement
C provides the do-while statement to implement such loops
1. Get a data value. 2. If data value isnt in the acceptable range, go back to step 1. do { printf(Enter a letter from A to E> ); scanf(%c, &letter); } while (letter < A || letter > E);
46
do-while Statement
SYNTAX: do { statements } while ( loop repetition condition ); Ex: Find first even input do status = scanf(%d, &num); while (status > 0 && (num % 2) != 0);
47
48
49
50
51
52
Case Study:
Problem: Collecting area for Solar-Heated House
Area depends on several factors the average number of heating degree days for each month
the product of the average difference between inside and outside temperatures and the number of days in the month
heating requirement per square foot of floor space floor space efficiency of the collection method
53
Case Study:
The formula for the desired collecting area (A) A = heat loss / energy source heat lost is the product of the heating requirement, the floor space, and the heating degree days. energy resource is the product of the efficiency of the collection method, the average solar insolation per day and the number of days. Two data files hdd.txt contains numbers representing the average heating degree days for each months. solar.txt contains the average solar insolation for each month
GIT Computer Engineering Department
54
Case Study:
Problem Inputs Average heating degree days file Average solar insolation file heat_deg_days /* average heating degree days for coldest month */ coldest_mon /* coldest month (number 1..12) solar_insol /* average daily solar insolation for coldest month*/ heating_req /* Btu/degree day Ft2 */ efficiency /* % of solar insolation converted to usable heat */ floor_space /* square feet */ Program Variables energy_resrc
/* usable solar energy available in coldest month (Btus obtained from 1 Ft2 of collecting area) */
/* Btus of heat lost by structure in coldest month */ /* approximate size Ft2 of collecting area needed */
55
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 from the user the other problem inputs: heating_req, efficiency, floor_space. 1. Estimate the collecting area needed. 2. Display results.
56
57
Case Study:
Program to Approximate Solar Collecting Area Size
58
59
60
61
Method:
examine the program output and determine program part generating incorrect results focus on the statements and try to determine the fault
OR
Use Debugger programs Debug without debugger
GIT Computer Engineering Department
62
In sentinel-controlled loops, an extra repetition is more dangerous. In counting loops, the initial and final values of counter should be correct and the loop repetition condition should be right. Ex: the following loop body executes n + 1 times instead of n times. for (i=0; i <= n; ++i) sum += i;
63
Wrong!!
while (x=1) ..
True
while (x==1) ..
65