Академический Документы
Профессиональный Документы
Культура Документы
Problem statement
Notice that
First refinement
Initialize variables
Input the ten quiz grades and count passes and failures
Print a summary of the exam results and decide if tuition
should be raised
Refine
Initialize variables
to
Initialize passes to zero
Initialize failures to zero
Initialize student counter to one
Notice that only the counters and totals are initialized
Refine
Input the ten quiz grades and count passes and failures
to
Refine
Print a summary of the exam results and decide if
tuition should be raised
to
C++ code
1
2
3
4
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
C++ code
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
// successful termination
Output
Pass=9 which is >8
satisfies the
condition to print
raise tuition
Passed=4which is <8
do not satisfies the
condition to print
raise tuition
{
statement block;
}
Initialization action
Is a boolean expression
Expreassion contains the final value of the control variable for
which the condition is true e.g. counter <= 10;
Loop continuation test evaluates to true or false
If true body of for is executed, else exit for loop
Notice that there is also a semi colon after loop condition test
Update
10
for keyword
for(varcounter=1;counter<=7;++counter)
11
12
initialization;
while ( loop Continuation Test)
{ statement
increment;}
for loop in previous example can be rewritten as while loop as
following
int counter = 1;
//initialization
While(counter<=10) //boolean expression to test the loop condition
{
cout<<counter<<endl; // print the value of counter
counter++;
//incriment counter
}
13
Example
Problem statement
Establish initial
value of control
variable
counter=1
counter=1
counter<=10
Determine if final
value of control
variable has
been reached
false
true
cout<<counter<<
endl;
Body of loop
(this may be many
statements)
counter++
Increment
the control
variable
14
C++ code
1
2
3
4
5
8
9
10
11
12
13
14
15
16
17
18
19
15
output
16
Example
Problem statement
17
Example
1
2
3
4
5
8
9
10
11
12
13
14
15
16
17
18
19
20
output
return 0;
// successful termination
;
this semi colon should be placed otherwise result would be wrong.
}Its//not
end
function
maintechnique as it makes it difficult to read the program
a good
programming
18
There may be several variables in the for structure that must be initialized
and updated (e.g. incremented or decrement)
example
for (int i = 0, j = 0; j + i <= 10; j++, i++)
cout << j + i << endl;
19
Example
Assume x = 2, y = 10
If x and y are not modified in loop body, the statement
20
Example program
Problem
statement
C++ code
1
2
3
4
10
11
15
16
17
18
19
20
21
22
22
C++ code
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
return 0;
23
Output
24