IBM SC34-5764-01 Server User Manual


 
Exercise - Writing an Internal and an External Subroutine
Write a program that plays a simulated coin toss game and produces the accumulated scores.
There should be four possible inputs:
v 'HEADS'
v 'TAILS'
v '' (Null—to quit the game)
v None of these three (incorrect response).
Write an internal subroutine without arguments to check for valid input. Send valid input to an external
subroutine that uses the RANDOM built-in function to generate random outcomes. Assume HEADS = 0
and TAILS = 1, and use RANDOM as follows:
RANDOM(0,1)
Compare the valid input with the value from RANDOM. If they are the same, the user wins one point; if
they are different, the computer wins one point. Return the result to the main program where results are
tallied.
ANSWER
/***************************** REXX ********************************/
/* This program plays a simulated coin toss game. */
/* The input can be heads, tails, or null ("") to quit the game. */
/* First an internal subroutine checks input for validity. */
/* An external subroutine uses the RANDOM built-in function to */
/* obtain a simulation of a throw of dice and compares the user */
/* input to the random outcome. The main program receives */
/* notification of who won the round. It maintains and produces */
/* scores after each round. */
/*******************************************************************/
PULL flip /* Gets "HEADS", "TAILS", or "" */
/* from input stream. */
computer = 0; user = 0 /* Initializes scores to zero */
CALL check /* Calls internal subroutine, check */
DO FOREVER
CALL throw /* Calls external subroutine, throw */
IF RESULT = 'machine' THEN /* The computer won */
computer = computer + 1 /* Increase the computer score */
ELSE /* The user won */
user = user + 1 /* Increase the user score */
SAY 'Computer score = ' computer ' Your score = ' user
PULL flip
CALL check /* Call internal subroutine, check */
END
EXIT
Figure 41. Possible Solution (Main Program)
Writing Subroutines and Functions
Chapter 6. Writing Subroutines and Functions 67