Movatterモバイル変換


[0]ホーム

URL:


Jump to content
WikibooksThe Free Textbook Project
Search

Pascal Programming/Beginning

From Wikibooks, open books for an open world
<Pascal Programming

In this chapter you will learn:

  • How a Pascal source code file is structured
  • Basic terminology

Programs

[edit |edit source]

All your programming tasks require one source code file that is called in Pascal aprogram.Aprogram source code file is translated by the compiler into an executable application which you can run.Let’s look at a minimalprogram source code file:

programnop;begin{ intentionally empty }end.
  1. The first lineprogramnop; indicates that this file is a Pascal source code file for a program.
  2. Thebegin andend mark a frame. We will explain this in detail as we move on.
  3. { intentionally empty } is acomment. Comments will be ignored by the compiler, thus do not contribute in any way how the executable program looks or behaves.
  4. And the final dot. after the finalend informs the compiler about the program source code file’s end.
NoteIf you feel overwhelmed by the pace of this book, the WikibookProgramming Basics might be more suitable for you.

Compilation

[edit |edit source]

In order to start your program you need to compile it.

First, copy the program shown above. We advise you to actually type out the examples and not to copy and paste code.Name the filenop.pas.nop is the program’s name, and the filename extension.pas helps you to identify thesource code file.

Once you are finished, tell the compiler you have chosen to compile the program:

If you are using theFPC, type into a consolefpc followed by a (relative or absolute) file name path to the source code file:
FPC Input:
fpcnop.pas
Result:
Target OS: Linux for x86-64Compiling nop.pasLinking nop4 lines compiled, 0.1 sec
If there no typing errors, successful compilation looks like this (some data may differ). In the current directory there will be a new file callednop. This is the executable program you can start.


If you are using theGPC, type into a consolegpc followed by a (relative or absolute) file name path to the source code file:
GPC Input:
gpcnop.pas
Result:
If there are no typing mistakes,gpc will not report any errors, but there will be a new file (by default) calleda.out.


Finally, you can then execute the program by one of the methods yourOS provides.For example on a console you simply type out the file name of the executable file:./nop (where./ refers to the current working directory in Unix-like environments)As this program does (intentionally) nothing, you will not notice any (notable) changes.After all, the program’s namenop is short forno operation.

NotePrograms need to be compiled for every single platform.Platform refers toOS,OS version, and the utilized microprocessor architecture and make. Only if all of these metrics match, you can copy an executable file to a different computer and run it there, too. Otherwise it may fail. ModernOSs can prevent you from running non-compatible programs (to some degree of precision).

The computer speaks

[edit |edit source]

Congratulations to your first Pascal program!To be fair, though, the program is not of much use, right?As a small step forward, let’s make the computer speak (metaphorically) and introduce itself to the world:

programhelloWorld(output);beginwriteLn('Hello world!');end.

Program header

[edit |edit source]

The first difference you will notice is in the first line.Not only the program name changed, but there is(output).This is a programparameter.In fact, it is a list.Here, it only contains one item, but the general form is(a, b, c, d, e, ) and so on.A program parameter designates an external entity theOS needs to supply the program with, so it can run as expected.We will go into detail later on, but for now we need to know there are twospecial program parameters:input andoutput.These parameters symbolize the default means of interacting with theOS.Usually, if you run a program on a console,output is the console’s display.

Writing to the console

[edit |edit source]

The next difference iswriteLn('Hello world!').This is a statement.The statement is a routine invocation.The routine is calledwriteLn.WriteLn has (optional) parameters.The parameters are, again, a comma-separated list surrounded by parentheses.

Routines

[edit |edit source]

Routines are reusable pieces of code that can be used over and over again.The routinewriteLn, short forwrite line, writes all supplied parameters to the destination followed by a “newline character” (some magic that will move the cursor to the next line).Here, however, the destination is invisible.That is, because it is optional it can be left out.If it is left out, the destination becomesoutput, so our console output.If wewant toname the destination explicitly, we have to writewriteLn(output, 'Hello world!').WriteLn(output, 'Hello world!') andwriteLn('Hello world!') areidentical.The missing optional parameter will be inserted automatically, but it relieves the programmer from typing it out.

In order to use a routine, we write its name, as a statement, followed by the list of parameters.We did that in line 2 above.

NoteRoutines need to be defined before they can be used.

The routinewriteLn, however, is defined as an integral part of the Pascal language.In one of the following chapters we will learn to define ourown routines.

String literals

[edit |edit source]

The parameter'Hello world!' is a so-called string literal.Literal means, your program will take this sequence of charactersas it is, not interpret it in any way, and pass it to the routine.Astring literal is delimited by typewriter (straight) apostrophes.

Reserved words

[edit |edit source]

In contrast to that, the wordsprogram,begin andend (and many more you see in a bold face in the code examples) are so-calledreserved words.They convey special meaning as regards to how to interpret and construct the executable program.You are only allowed to write them at particular places.

NoteNevertheless, youcan write thestring literal'program'. The string delimiters “disable” interpretation.

Behavior

[edit |edit source]
Now, that we know what the source code contains, create a new filehelloWorld.pas, copy the source code (by typing it manually), compile and run it:

Code:

programhelloWorld(output);beginwriteLn('Hello world!');end.

Output:

Hello world!
The program will printHello world!,without the straight quotation marks, on an individual line to the console. Isn’t that great?
“Help! I only see the terminal window opening and closing again!”
In this case, try this program
programhelloWorld(input,output);beginwriteLn('Hello world!');readLn();end.
The changed lines are highlighted. The extrareadLn() will make your program stall, so the program is not considereddone. After you hit↵ Enter the terminal window should close again.

This type of program, by the way, is an example of a class of “Hello world” programs.They serve the purpose for demonstrating minimal requirements a source code file in any programming language needs to fulfill.For more examples seeHello world in the WikiBook “Computer Programming” (and appreciate Pascal’s simplicity compared to other programming languages).

Comments

[edit |edit source]

We already saw the option to writecomments.The purpose of comments is to serve the programmer as a reminder.

Comment syntax

[edit |edit source]

Pascal defines curly braces as comment delimiting characters:{ comment } (spaces are for visual guidance and have no significance).The left braceopens orstarts a comment, and the right bracecloses a comment.

Note“Inside” a comment you cannot use the comment closing character as part of your text. Thefirst occurrence of the proper closing character(s)will be the end of the comment.

However, when Pascal was developed not all computer systems had curly braces on their keyboards.Therefore the bigramms (a pair of letters) using parentheses and asterisks was made legal, too:(* comment *).

Such comments are calledblock comments.They can span multiple lines.Delphi introduced yet another style of comment, line comments.They start with two slashes// and comprise everything until the end of the current line.

Delphi, theFPC as well asGPC support all three styles of comments.

Helpful comments

[edit |edit source]

There is an “art” of writinggood comments.

Caution
Comments should not repeat what can be deduced from the source code itself.
programhelloWorld(output);begin{ This is where the program begins }writeLn('Hello world!');end.(* This is where the program ends. *)
Comments should explain information that is not apparent:
programnop;begin{ intentionally empty }end.


When writing a comment, stick toone natural language.In the chapters to come you will read many “good” comments (unless they clearly demonstrate something like below).

Terminology

[edit |edit source]

Familiarize with the following terminology (that means the terms on the right printed as comments):

programdemo(input,output);// program header// ───────────────────────────────────┐const// ────────────────────┐              │answer=42;// constant definition ┝ const-section│// ────────────────────┘              │type// ────────────────────┐              │employee=record// ─┐                  │              │number:integer;//  │                  │              │firstName:string;//  ┝ type definition  │              │lastName:string;//  │                  ┝ type-section │end;// ─┘                  │              │//                     │              │employeeReference=^employee;// another type def.   │              │// ────────────────────┘              ┝ block//                                    │var// ────────────────────┐              │boss:employeeReference;// variable declaration┝ var-section  │// ────────────────────┘              │//                                    │begin// ────────────────────┐              │boss:=nil;// statement           │              │writeLn('No boss yet.');// another statement   ┝ sequence     │readLn();// another statement   │              │end.// ────────────────────┘              │// ───────────────────────────────────┘

Note, how every constant and type definition, as well as every variable declaration all go into dedicatedsections.The reserved wordsconst,type, andvar serve as headings.

Asequence is also called acompound statement.Thecombination of definitions, declarations and a sequence is called ablock.Definitions and declarations are optional, but a sequence is required.The sequence may be empty, as we already demonstrated above, but this is usually not the case.

Do not worry, the difference betweendefinition anddeclaration will be explained later.For now you should know and recognizesections andblocks.

Tasks

[edit |edit source]
Can a comment contain a comment? Try and write a test program to find it out! Mix various comment delimiters and see what happens if you mix them up.
Yes/no. While you canbegin another comment inside a comment, the terminating character(s) will mark the end of a comment in general. The following situations do not cause a problem:
programcommentDemo;begin{ (* Hello { { { }(* (* { (* Foo }{ (* Bar *)

The first comment-ending character(s) demarcatethe end of the entire comment, regardless whether it started with{ or(*. That means, here the compiler will complain:

{ start (* again? }*)

Line comments are immune to this, since they do not have an explicit end delimiter. This will compile without errors:

// *) } { (*end.
Yes/no. While you canbegin another comment inside a comment, the terminating character(s) will mark the end of a comment in general. The following situations do not cause a problem:
programcommentDemo;begin{ (* Hello { { { }(* (* { (* Foo }{ (* Bar *)

The first comment-ending character(s) demarcatethe end of the entire comment, regardless whether it started with{ or(*. That means, here the compiler will complain:

{ start (* again? }*)

Line comments are immune to this, since they do not have an explicit end delimiter. This will compile without errors:

// *) } { (*end.


What doeswriteLn (note the lack of a parameter list) do?
WriteLn without any supplied parameters prints an empty line to the default destination, i. e.output.
WriteLn without any supplied parameters prints an empty line to the default destination, i. e.output.


Write aprogram that shows this (or similar):
     ####     ####   ######## ########  ##     #####     ##  ##       #       ##  ##      ILY      ##   ##   sweetie   ##    ###         ###      ###     ###        ### ###          ###           #
An acceptable implementation could look like this:
programvalentine(output);beginwriteLn('     ####     ####');writeLn('   ######## ########');writeLn('  ##     #####     ##');writeLn('  ##       #       ##');writeLn('  ##      ILY      ##');writeLn('   ##   sweetie   ##');writeLn('    ###         ###');writeLn('      ###     ###');writeLn('        ### ###');writeLn('          ###');writeLn('           #');end.

Note, the program parameter list (first line) only listsoutput.Beware, while the exact number of spaces do not matter in your code, they do matter in string literals.

Wikipedia has more onASCII art.
An acceptable implementation could look like this:
programvalentine(output);beginwriteLn('     ####     ####');writeLn('   ######## ########');writeLn('  ##     #####     ##');writeLn('  ##       #       ##');writeLn('  ##      ILY      ##');writeLn('   ##   sweetie   ##');writeLn('    ###         ###');writeLn('      ###     ###');writeLn('        ### ###');writeLn('          ###');writeLn('           #');end.

Note, the program parameter list (first line) only listsoutput.Beware, while the exact number of spaces do not matter in your code, they do matter in string literals.

Wikipedia has more onASCII art.
Next Page: Variables and Constants | Previous Page: Getting started
Home: Pascal Programming
Retrieved from "https://en.wikibooks.org/w/index.php?title=Pascal_Programming/Beginning&oldid=4096991"
Category:

[8]ページ先頭

©2009-2025 Movatter.jp