The programs that you have written so far always do the same thing each time you run them. To get them to solve different problems, you need to modify them for each problem. Programs do not normally work that way. They ask the user for information and use that information to decide what to do.
To read information from the user, use one of the following functions.
Operation | Description |
---|---|
readInteger() | Read an integer from the user and produce it as the value of expression readInteger(). |
readReal() | Read a real number from the user and produce it as the value of expression readReal(). |
readString() | Read a string from the user and produce it as the value of expression readString(). (The string either ends at a space or newline, or is enclosed in quote marks.) |
readLine() | Read one line of text and produce it, as a string. |
readChar() | Read the next character from the user and produce it as the value of expression readChar(). The character might be a blank or a newline. |
readNonblankChar() | Read the next nonblank character (skipping over blanks, tabs and newlines) from the user and produce it as the value of expression readNonblankChar(). |
Before reading something, write a prompt so that the user knows that he or she is being asked a question. For example, let's write a simple program that reads an integer and tells you whether that integer is prime.
Package prime Define isPrime(n) = result | open If n < 2 then Let result = false. else Let k = 2. While k < n and (n `mod` k =/= 0) do Relet k = k + 1. %While open If k < n then Let result = false. else Let result = true. %If %If %Define Execute Display "What number shall I test? ". Let n = readInteger(). If isPrime(n) then Displayln $(n) ++ " is prime.". else Displayln $(n) ++ " is not prime.". %If %Execute %Package
When writing a prompt, do not insult the user or use profanities. Keep it straightforward.
Programs normally interact with a user. For simple text-based programs, that means reading information typed on the keyboard and writing information onto the console.