Pascal Programming/Input and Output

From Wikibooks, open books for an open world
Jump to: navigation, search

Output[edit]

Before you learn more about Pascal it is important to know how to actually do something. For now, we will use console input and output. Here is an example of how output is done:

program output;
begin
  writeln(1);
  write('1')
end.

writeln() displays what ever is in the parentheses and prints a "new line character", making newly displayed characters start on the next line.

; is simply grammatical; it just separates the two statements.

write() displays what ever is in the parentheses without printing a "new line character".

Do note that characters and strings must be placed within single quotation marks. You may have noticed that write and writeln work for more than one type. You may also wonder how write(1) and write('1') could do the same thing yet, 1 and '1' be represented in completely different ways. Like wise, how 49 and '1' may be represented the same way yet, write(49) and write('1') don't do the same thing. The answer is that compiler always knows the type and thus how it's formatted.

Input[edit]

program input;
 
var
  c : int;
begin
  readln(c);
  read(c);
end.

readln() and read() place user input into the assigned variable. In this case, if the user entered a number then it would be stored in the variable c. readln() create a new line after the input is entered while read() would cause the cursor to remain on the same line instead.

Both readln and read can be useful when programming in the Windows environment. If a compiled application is executed outside of the command prompt, the application window would close immediately after performing its task. The following code can be used to keep the window open after finishing the programmed task:

program RemainOpen;
 
begin
  writeln('Hello, world!');
  readln;
end.

As you notice, the parentheses are not required when no parameters are present.