Line # 1

advertisement
Line #
1 var grade = parseInt( prompt( "Enter a grade", "" ) );
2 var count = 0;
// initialize counter
3 var sum = 0;
// initialize accumulator
4 var highest = 0;
// initialize highest accumulator
// to lowest possible value
5 var lowest = 100; // initialize lowest accumulator
//to highest possible value
6 while ( grade != -1 )
// loop test -- if true, enter loop body
{
7
count++;
8
sum += grade;
9
if ( grade > highest )
highest = grade;
10
if ( grade < lowest )
11
lowest = grade;
12
13
grade = parseInt( prompt( "Enter another grade "
+ "( -1 to finish ):", "" ) );
14
while ( isNaN( grade ) || grade < -1 || grade > 100 )
grade = parseInt( prompt( "Bad entry -- TRY AGAIN "
+ "( -1 to 100 ):", "" ) );
15
}
16 var average = sum / count;
17 average = Math.round( average * 10 ) / 10;
Fill in the table on the next page with a TRACE of the operation of the program.
Assume the user enters the following: 85, 70, 95, 75, done, -1
A solution is shown on the last page – no peeking until you have completed the exercise!
Line #
grade
count
sum
highest
lowest
average
Solution:
Line #
grade
count
sum
highest
lowest
average
1
85
2
0
3
0
4
0
5
100
6
7
1
8
85
9
10
85
11
12
85
13
70
14
6
7
2
8
155
9
11
12
70
13
95
14
6
7
3
8
250
9
10
95
11
13
75
14
6
7
4
8
325
9
11
13
NaN
14
15
–1
14
6
16
81.25
17
81.3
Note: each underlined line number indicates a change in the statement sequence as a result of the
action of a control structure.
Download