Table of Contents

Introduction

Basics of Programming

Variables

Input and Output

Boolean Expressions and Branching

Loops

Functions and Procedures

Files

Arrays

HOME

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Chapter 4

Input and Output

Output

As we have seen in previous chapters, Pascal allows programs to send output to the screen. This is done with the "Writeln" and "Write" statements. This section will cover both statements in greater detail.

Writeln prints output on the screen then moves the cursor to the next line. Writeln prints both immediate data, and data contained in variables. It also allows the programmer to specify how the ouput will be displayed. Take the folowing for example.

 Writeln('Hello World':20);

 

As you may have guessed, this statement prints the phrase "Hello World" on the screen. The colon and the number following it specify how many character spaces should be alloted on the screen. This example sets aside twenty spaces on the screen for the phrase. Since the phrase "Hello World" only takes up eleven spaces, it leaves nine blank spaces to the left of the phrase.

Pascal also makes it possible to mix variables with immediate data in the same statement. For example:

  x := 365
  Writeln('There are ',x,' days in a year');

The Writeln statement mixes two strings with a variable. Notice that each part of the output is separated by a comma. This tells the compiler that there is still more data to be printed on the screen.

The "Write" statement does the same thing as the Writeln statement except that it doesn't move the cursor to the next line. This means that the next output statement will write to the same line as the previous statement.

Input

For a program to be useful it must take input from a user. Pascal provides the "Read" and "Readln" statements for this purpose.

The following program shows how Readln is used for input.


Program InputExample(input, output);

Var
  MyInteger : integer;
  MyString : string;


Begin
  {first prompt the user for input}
  Writeln('Enter an integer ');  

  {now get the input}
  Readln(MyInteger);             

  Writeln('Enter a string ');

  {now get the string}
  Readln(MyString);   

   
  {now show the user what was entered}

  Writeln ('You entered: ', MyInteger);
  
  Writeln ('You entered: ', MyString);

End.


This program asks the user for an integer and a string. It then displays them on the screen. Notice that before the "Readln" statements there is a Writeln statement that asks the user for input. This is called a prompt. It is very important to include a prompt every time a program gets input.