You are on page 1of 25

DT211-2

Programming
Revision
Algorithms, Pseudocode Top-down
Refinement
with looping
Ref Deitel & Deitel

1
Pseudocode -Revision
Develop pseudocode algorithms for each of the following:
Input two numbers and determine and display which (if either) is
the larger of the two numbers.
Input the first number from the keyboard
Input the second number from the keyboard
if the first number is greater than the second number
Print firstNumber
else
if the second number is greater than the first number
Print secondNumber
Else
Print a message stating that the numbers are equal
endif
endif

2
Pseudocode -Revision
Obtain a series of positive numbers from the keyboard, and
determine and display the
sum of the numbers.
Assume that the user types the sentinel value -1 to indicate
“end of data entry.”
Use the while statement.
sum=0
Input a value from the keyboard
While the input value is not equal to -1
add the number to sum
input the next number
Print sum
3
Pseudocode for Powers of 2
Write pseudocode that keeps printing the multiples
(powers) of the integer 2, namely 2, 4, 8, 16, 32, 64,
and so on. The loop should not should not terminate
(i.e., you should create an infinite loop). Implement
this program and evaluate the outcome of execution.

4
Pseudocode for Powers of 2
Allow program to run infinitely
Output in form
n 2^n
1 2
2 4
3 8

5
Code for Powers of 2

6
Top-down Stepwise Refinement
• This typically consists of three phases of pseudoced
development.
• Top-
– a single statement that conveys the programs overall
function.
• First refinement-
– divides the top task into smaller tasks into the general order
that they must occur.
• Second refinement-
– This identifies storage and variables and their initialisation. It
defines the control structures for managing the processing
logic including the termination and timing of any outputs.
– More complex programs will require further refinements. 7
Top-down Stepwise Refinement
Example
Requirement spec: A class of students took a quiz.
The grades (int 0 to 100) are available for input on
an input stream terminated by a sentiner of -1.
Determine the average grade for the class.
Top Refinement:
Determine the class average for the quiz
Second Refinement
Initialize variables
Input, sum up and count the quiz grades
Calculate and print the class average

8
Top-down Stepwise Refinement Example
Third refinement:
Initialize total to zero
Initialize counter to zero

input the first grade (possibly the sentinel)


While the user has not as yet entered the sentinel
Add this grade into the running total
Add one to the grade counter
Input the next grade (possibly the sentinel)
endwhile
if the counter is not equal to zero
Set the average to the total divided by the counter
Print the average
else
Print “No grades were entered”
endif 9
Stepwise Refinement
Salesperson earnings
One large chemical company pays its salespeople on a
commission basis. The salespeople receive $200 per
week plus 9% of their gross sales for that week. For
example, a salesperson who sells $5000 worth of
chemicals in a week receives $200 plus 9% of
$5000, or a total of $650. Develop a program that
will input each salesperson’s gross sales for last
week and will calculate and display that
salesperson's earnings. Process one salesperson's
figures at a time.
10
Salesperson earnings
Sample I/O dialogue
Enter sales in dollars (-1 to end): 5000.00
Salary is: $650.00
Enter sales in dollars (-1 to end): 1234.56
Salary is: $311.11
Enter sales in dollars (-1 to end): 1088.89
Salary is: $298.00
Enter sales in dollars (-1 to end): -1

11
Salesperson earnings
Top-down refinement
2)Top:
For an arbitrary number of salespeople, determine
each salesperson’s earnings for the
last week
First refinement:
Input the salesperson’s sales for the week,
calculate and print the salesperson’s wages
for the week,
then process the next salesperson
12
Salesperson earnings
Top-down refinement
Second refinement:

input the first salesperson’s sales in dollars


while the sentinel value (-1) has not been entered for the sales
calculate the salesperson’s wages for the week
print the salesperson’s wages for the week
input the next salesperson’s sales in dollars
endWhile

13
Salesperson earnings code
#include <stdio.h>
#include <conio.h>
int main( void )
{
float sales; /* gross weekly sales */
float wage; /* commissioned earnings */

/* get first sales */


printf( "Enter sales in dollars (-1 to end): " );
scanf( "%f", &sales );

/* loop until sentinel value read from user */


while ( sales >= 0.0 ) {
wage = 200.0 + 0.09 * sales; /* calculate wage */
/* display salary */
printf( "Salary is: $%.2f\n\n", wage );
/* prompt for next sales */
printf( "Enter sales in dollars (-1 to end): " );
scanf( "%f", &sales );
} /* end while */
getch();
return 0; /* indicate successful termination */
14
Counter Controlled Looping with
for statement
The general format of the for statement is
• for ( expression1; expression2; expression3 )
statement

where expression1 initializes the loop-control variable,


expression2 is the loop-continuation condition, and
expression3 increments the control variable.
In most cases, the for statement can be represented with
an equivalent while statement as follows:
expression1;
while ( expression2 ) {
statement
expression3;
}
15
do while statement
In the while statement, the loop-continuation
condition is tested at the beginning of the loop
before the body of the loop is performed.
The do…while statement tests the loop-continuation
condition after the loop body is performed.
Therefore, the loop body will be executed at least
once.

16
do while statement
Use do…while statement to print the numbers from 1
to 10.
The control variable counter is preincremented in the
loop-continuation test.

17
for ( expression1; expression2; expression3 ) statement

The three expressions in the for statement are optional.


If expression2 is omitted, C assumes that the condition is
true, thus creating an infinite loop.
One may omit expression1 if the control variable is
initialized elsewhere in the program.
expression3 may be omitted if the increment is calculated
by statements in the body of the for statement or if no
increment is needed.

18
for ( expression1; expression2; expression3 ) statement

The increment expression in the for statement acts like a stand-


alone C statement at the end of the body of the for.

The expressions
counter = counter + 1
counter += 1
++counter
counter++

are all equivalent in the increment part of the for


statement.
preferred form is counter++ because the incrementing
occurs after the loop body is executed and seems more
natural.
19
Notes on for
for ( expression1; expression2; expression3 ) statement
The initialization, loop-continuation condition and
increment can contain arithmetic expressions. For
example, when x = 2 and y = 10, the statement
for ( j = x; j <= 4 * x * y; j += y / x )

is equivalent to the statement


for ( j = 2; j <= 80; j += 5 )

The “increment” may be negative (in which case it’s


really a decrement and the loop actually counts
downward).
If the loop-continuation condition is initially false, the
loop body does not execute. Instead, execution proceeds
with the statement following the for statement. 20
for Examples
for ( expression1; expression2; expression3 ) statement
The following examples show methods of varying the control
variable in a for statement.
– Vary the control variable from 1 to 100 in increments of 1.
for ( i = 1; i <= 100; i++ )
– Vary the control variable from 100 to 1 in increments of -1 (decrements of
1).
for ( i = 100; i >= 1; i-- )
– Vary the control variable from 7 to 77 in steps of 7.
for ( i = 7; i <= 77; i += 7 )
– Vary the control variable from 20 to 2 in steps of -2.
for ( i = 20; i >= 2; i -= 2 )
– Vary the control variable over the following sequence of values: 2, 5, 8,
11, 14, 17.
for ( j = 2; j <= 17; j += 3 )
– Vary the control variable over the following sequence of values: 44, 33,
22, 11, 0.
for ( j = 44; j >= 0; j -= 11 )
21
For Examples Factorial n, n!
The factorial of a positive integer n (written n! and
pronounced “n factorial”) is equal to the product of the
positive integers from 1 to n.
N! = 1x2x3x…..(n-1)xn
Develop a program that evaluates the factorials of the integers
from 1 to n and list them in tabular format.
n Factorial of n
1 1
2 2
3 6
4 24
5 120
22
For Examples Factorial n, n!
Top Print a table for factorial of the first n integers
First refinement:
Input n,
display table column header
for each number starting at 1 up to n,
calculate its factorial and display number and its
factorial
endFor

23
For Examples Factorial n, n!
Second refinement:
Declare variable n and counter x,
print k, tab, k!
for x=1 to n
calcualte k!
print k, k!
endFor

24
For Examples Factorial n, n!
Third refinement:
Declare variable n and counter k,
print n, tab, n!
for k=1 to n
/* calculate x!
for j=1 to k
factorialK=factorialK * k
/* factorialK *= factorialK
endfor
print k, factorialK!
endFor 25

You might also like