Sie sind auf Seite 1von 125

CIT 05107

Be able to design and implement computer program Sub-enabling outcomes


Ability to discuss the comment statements Ability to identify Variables, data types, identifiers, character set, keywords and constants Ability to identify assignment statements Ability to develop simple program with Pascal

Introduction Programming languages overview Creating a Program Plan & Flow Problem Definition Table, Input Process Output Chart, Algorithm, Flow chart, Pseudo Codes, Processes, Decisions, Loops Program Development (Writing Codes) Procedural concepts, Variables and types, Constants, Assignments (statements), Keywords, Operators, Comments

Fundamental

concepts of object oriented

programming Classes, Objects, Encapsulation, Inheritance, Abstraction , Polymorphism Program structure Program Head, Program Block, Subroutines, Procedures, Functions, Parameters Passing Program Testing & Debugging Syntax errors, logical errors, Run time errors, Data Validation

Books, PowerPoint Handouts and presentations, Projector, Computer, Speakers, Audio CDs, white boards, marker pens and Internet Resources Reference books Includes: Introduction to Programming Manual Rumbaugh, James, Michael Blaha, William Premerlani, Frederick Eddy, William Lorensen. ObjectOriented Modeling and Design, Prentice Hall. ISBN 0136298419 Algorithm Design by Eva Tardos, ISBN: 0321372913 Van Yoy, Peter and Haridi, Seif (2004). Concepts, Techniques, and Models of Computer Programming; MIT Press, ISBN 0-262-22069-5.

Continuous assessment Assignment Quiz End of semester exams

20% 5% 15% 60%

Computer programs are collections of instructions that tell a computer how to do things, interact with the computer hardware and process data. The first programmable computers required the programmers to write explicit instructions to directly manipulate the hardware of the computer So, what is a programming language? A programming language is an artificial language designed to communicate instructions to a machine , particularly a computer. Programming languages can be used to create programs that control the behavior of a machine and/or to express algorithms precisely. Computer languages are used to tell the computer what to do, you instruct it.

We

Low level programming language

have two categories of programming language,

Low level programming is closer to the language of computer which is divided into two categories

High level programming language

High level programming language is Consists of symbolic instructions more meaningful to human being Language

Machine language Assembly language

There are four Levels of Programming languages. These are also called Generations of Programming Languages. These are:
a)First Generation Language (1GL) -Machine Language b)Second Generation Language (2GL)-Assembly Language c) Third Generation Language(3GL) -High level Language d) Fourth Generation Language (4GL) -Very High Level Language

A first-generation (machine language) programming language is a machine-level programming language Machine Language is the only Language that is directly understood by the computer. It does not needs any translator program. We also call it machine code and it is written as strings of 1's (one) and 0's (zero0. This is binary system. When this sequence of codes is fed to the computer it recognizes the codes and converts it in to electrical signals needed to run it. Advantages It runs very fast because no translation program is needed for the CPU. Disadvantages a) It is very difficult to program in machine Language. You have to know the details of hardware to write program. b) Then programmer has to remember a lot of code to write a program which results in program errors. c) It is difficult to debug the program.
1)

2) Second-generation programming language(low level language) is an assembly language. An assembly language is a low-level programming language for a computer, microcontroller, or other programmable device, in which each statement corresponds to a single machine code instruction. Each assembly language is specific to a particular computer architecture, in contrast to most highlevel programming languages, which are generally portable across multiple systems Assembly languages have the following properties: To run on a computer it must be converted into a machine readable form, a process called assembly. The language is specific to a particular processor family and environment

Consists of abbreviations called mnemonics which are close to the human being language (English) e.g for multiply action MUL,Addition ADD, Subtraction SUB, Division DIV Source program written in Assembly Language must be translated into machine language code for the computer to understand. This is done by the program called ASSEMBLER.

Advantages a) It is to understand and saves a lot of time and efforts of programmer. b) It is easier to correct errors and modify program instructions Disadvantages It is machine dependent language. A program written for one computer might not run in other computer with different hardware configuration.

Assembly

Assembler

Machine codes

3) A third-generation programming language (3GL)(High level programming) is a refinement of a second-generation programming language. The second generation of programming languages brought logical structure to software. The third generation brought refinements to make the languages more programmer-friendly. This includes features like improved support for aggregate data types, and expressing concepts in a way that favors' the programmer, not the computer Most popular general-purpose languages today, such as C, C++, C#, Java, BASIC and Delphi, are also third-generation languages. Most 3GLs support structured programming.

4) A fourth-generation programming language (very high level language) (1970s-1990) (abbreviated 4GL) is a programming language or programming environment designed with a specific purpose in mind, such as the development of commercial business software.

Advantage of low level language: It runs very fast because no translation program is needed for CPU Disadvantage It is very difficult to program in machine language. It is difficult to debug the program The program has to remember a lot of code to write program.

Example:
169 1 160 0 153 0 128 153 0 129 153 130 153 0 131 200 208 241 96 this code output character A 1000 times

Advantage of assembly language It is simple to understand and saves a lot of time and efforts of programmer It is easy to correct error and modify program instructions Disadvantage It is machine dependant language. A program written for one computer might not run in other computer with different hard ware configuration Example: for multiply action MUL,Addition ADD, Subtraction SUB, Division DIV

Programming, also known as software development, is a sixstep procedure for creating that list of instructions. Only one of those steps consists of typing (keying) statements into a computer. Those steps are as follows; 1. Program specification: The programs objectives, outputs, inputs, and processing requirements are determined. 2. Program design: A solution is created using programming techniques such as top-down program design, pseudo code, flowcharts, and logic structures. 3. Program code: The program is written or coded using a programming language.

4. Program test: The program is tested or debugged by looking for syntax and logic errors. 5. Program documentation: Documentation is an ongoing process throughout the programming process. This phase focuses on formalizing the written description and processes used in the program. 6. Program maintenance: Completed programs are periodically reviewed to evaluate their accuracy, efficiency, standardization, and ease of use. Changes are made to the programs code as needed.

Program specification is also called program definition or program analysis. It requires that the programmeror the end user specify five items: (1) the programs objectives, (2) the desired output, (3) the input data required, (4) the processing requirements, and (5) the documentation.

After program specification, a program design phase is started. Here the programmer plans a solution, preferably using structured programming techniques. These techniques consist of flowcharts and logic structures. Flowcharts These graphically present the detailed sequence of steps needed to solve a programming problem. This figure presents several of the standard flowcharting symbols. Flowchart expresses all the logic for just one module A computer does more than arithmetic. It also makes comparisons whether something is greater than or less than, equal to or not equal to.

Step 3: Program Code Writing the program is called coding. Here the software developer uses the logic he developed in the program design step to actually write the program. That is, he writes out using pencil and paper or typing on a computer keyboard the letters, numbers, and symbols that make up the program. This is the program code that instructs the computer what to do.

Debugging refers to the process of testing and then eliminating errors It means running the program on a computer and then fixing the parts that do not work.

Documentation consists of written descriptions and procedures about a program and how to use it. It is not something done just at the end of the programming process. Program documentation is carried on throughout all the programming steps. This documentation is typically within the program itself and in printed documents. In this step, all the prior documentation is reviewed, finalized, and distributed. Documentation is important for people who may be involved with the program in the future.

T he final step is program maintenance. As much as 75 percent of the total lifetime cost for an application program is for maintenance. This activity is so commonplace that a special job title, maintenance programmer, exists. The purpose of program maintenance is to ensure that current programs are operating error free, efficiently, and effectively. Activities in this area fall into two categories: operations and changing needs.

Is a program that reads a high level program and it translate a program line by line and carry out the commands.
Interpreter

Source codes

The interpreter reads the source codes.

and the result appears on the screen

Is a program that reads high-level program and translate it all at once before executing any of the command. In this case the high level program is called the source code and translated program is called objective code or the executable.

You're probably thinking "you don't say" (or something less kind), but there really is a valid point in there. You see, there are fundamental similarities between all programming languages, so as a beginner it's really not so important which language you begin with; the important thing is to just get some experience with programming. So, you're really free to choose a language, up to a point. Just be aware that there's no "wrong" language to start with.

It combine various pieces of code and data together to form a single executable that can be loaded in a memory.

Program

loading is process of copying a program from secondary storage(permanent storage device such as hard disk) into main memory so its ready to run. Loader load the program into memory when the executable file is run Turing is pseudo-code compiler

Programming editors, also known as source code editors, are text editors that are specifically designed for programmers or developers for writing the source code of an application or a program. Notepad++ is a popular and widely-used editor loaded with features to make the users' programming more productive, including syntax and brace highlighting for many languages, search and replace using regular expressions, macro recording, and playback

Virtually all structured programs share a similar overall structure: Statements to establish the start of the program Variable declaration Program statements (blocks of code) The following is a simple example of a program written in several different programming languages. We call this the "Hello World" example since all the program does is print "Hello World" on the computer screen.

"C" #include <stdio.h> void main() { printf("Hello World"); }

C++ #include <iostream> int main() { cout << "Hello World"; return 0; }

Pascal program helloworld (output); begin writeln('Hello World'); end.

Java public class helloworld { public static void main (String args []) { System.out.println ("Hello World"); }}

Chapter two

The

goal of this chapter is to teach you to think like a computer scientist The single most important skill for a computer scientist is problem solving. They think creative about a solutions and express a solution clearly and accurately

1) 2) 3) 4)

5)

Understand and isolate the problem Brainstorm for ideas to solve problem Design a solution that might work Test your solution to see if it will work Assess whether the solution is good enough to do it

The point in here is a) Clarify expectation what user expect to see. What user want to see. b) Identify the inputs and outputs of the program What user will input and what them get after input the data. C) Identify limitation. Who is going to use that program and security measure.

Once you have identified the needs of the customer, create a design document to describe the program specifications. The document should give a fairly complete description while maintaining a high-level view of the project. Identify the goals and challenges of the program. For problematic aspects, consider creating an Input Process Output chart (IPO, see below).
Process 1. Get input from user via command line 2. Calculate using the formula C = 5/9 * (F32) 3. Output data to user via command line output Degree C

Input Degree F

Architects create model and draw up blueprint before a building built. The designing of a solution can be created using diagram, algorithms and other models. The main purposes of creating a design that can be viewed by others is to communicate the solution

Tools used to design stages are:


Algorithm.

Input Process Output (IPO) Chart

a. b.

c.
d.

Write the step by step process to be followed for the program with pseudo code (an English version of the program steps). Here are some simple example steps for a program: Ask for input from the user Check the user input for valid data Process the data for the user Provide output to the user A sequence of instructions is called an algorithm. Algorithms are a fundamental part of computing. If you study computing for many years you will study algorithms of frequently used processes.

There are two commonly used tools to help to document program logic (the algorithm). These are flowcharts and Pseudocode. We will use both methods here. Generally, flowcharts work well for small problems but Pseudocode is used for larger problems. Some of the common symbols used in flowcharts are shown below: With flowcharting, essential steps of an algorithm are shown using the shapes below. The flow of data between steps is indicated by arrows, or flowlines.

flowchart is a type of diagram that represents an algorithm or process, showing the steps as boxes of various kinds, and their order by connecting these with arrows. This diagrammatic representation can give a step-bystep solution to a given problem.

For

example, a flowchart to compute the interest on a loan is shown below:

Another example of a flowchart is shown below. In this case, the program computes the sum, average and product of three numbers:

A structured language is a programming language that follows a methodology where the logic of a program is a structure composed of similar sub-structures in a limited number of ways. There are 3 major element structured programming(control structure) Sequence Selection/Condition/Decision Repetition/Iteration/looping

Sequential programming can also be called linear programming is a series of process that follows a certain order. Or is step by step programming process. Example: when we were finding area of square as shown above in previous examples

Decision making is one of the most important concepts of computer programming. Programs should be able to make logical (true/false) decisions based on the condition they are in; every program has one or few problem/s to solve; depending on the nature of the problems, important decisions have to be made in order to solve those particular problems.

In decision we use mathematical symbols to compare to results, those symbols are shown below.

NOTATION <= != !> !< ! YES OR Y NO OR N

MEANING Less than or equal Not equal Not greater than Not less than Not Yes No

TRUE OR T
FALSE OR F

True
False

Example: Consider the case when we are asked to write a program where users are asked to give ratings on each article; we want to output different messages depending on the ratings given. Messages are as follow: 1 is bad, 2 is average and 3 is good

Input rate

yes

Is rate==1

no Is rate==2 no Is rate==3

Is bad

yes Is averag e

yes

no

Is good

Not required

Performing the same set of a number of terms OVER AND OVER until a stopping condition occurs. The loop structure is used in a flowchart to indicate where a program or person should repeat multiple steps until a certain condition is present. NOTE: Failure to provide a STOP condition will cause the process to go into an INFINITE LOOP.

Draw the flowchart performs the task 10 times as X counts from 0 to 10

In drawing flowchart all necessary components requirements should be listed out in logical order. Flowchart should be neat and easy to follow. Only one flow line should out from process symbol Only one flow line should enter in decision symbol, but two or three flow lines, one for each possible answer should leave the decision symbol. Ensure that the flow chart has logical start and finish. It is useful to test the validity of the flowchart through it with a simple test data.

Question 1: Design a flowchart which asks the user to input the radius of a circle. The user will be asked to choose between diameter, circumference and area. The result will be calculated and then displayed. QUESTION 2: Create a flowchart: Consider the case that you are asked to program a university marking system which identifies students grade on response to user input. Here is how grades should be grouped: 40+ E, 50-59 D , 60-69 C , 70-79 B , 80+ A Question 3: Design a flowchart which asks the user to input a number. The multiplication table of that number will be displayed

Communication: flowchart are better way of communicating the logic of system to all concerned. Effective analysis: with the help of flowchart, the problem can be analyzed in more effective way. Proper documentation: Efficient coding: flowchart act as guide or blueprint during the system analysis and program development phase. Proper debugging: the flow chart help in debugging process. Efficient maintenance:

Complex logic: sometimes, the program logic is quite complicated, in that case flowchart become complex and clumsy. Alternation and modification: if alternation are required the flowchart may require redrawing completely. Reproduction: as the flowchart symbol cannot be type , reproduction of flowchart becomes a problem.

Pseudocode

is an artificial and informal language that helps programmers develop algorithms. Pseudocode is a "text-based" detail (algorithmic) design tool. The rules of Pseudocode are reasonably straightforward. All statements showing "dependency" are to be indented. These include while, do, for, if, switch. Examples below will illustrate this notion.

Examples 1: If student's grade is greater than or equal to 60 Print "passed" else Print "failed"

Example 2: How to find average Set total to zero Set grade counter to one While grade counter is less than or equal to ten Input the next grade Add the grade into the total Set the class average to the total divided by ten Print the class average.

Coding(design

solution): Now it is time to actually begin coding your algorithm into a program. In general, each statement in the algorithm requires one line of programming code. You will frequently run and test your program at intervals. The more often you test small pieces of your code, the less troubleshooting you will need to do. Breaking your program down to testable pieces is called unit testing.

Software

Testing -- While you code you will run tests on your program, but at the end others may run the program through a rigorous series of software tests. These tests are designed to give one last pass to your program to be sure it is safe and secure for the public. Software testers sometimes use special software designed to expose the flaws in your program. If problems occur in your program during this phase, you will be coding and testing until all is satisfactory.

CHAPTER THREE

There are two popular approach to writing computer programs: procedural programs and object oriented program Procedural programming involves Any programming language in which the programmer specifies an explicit sequences of steps to follow to produce a result (an algorithm). We call it top down program Object oriented programming is an extension of procedural programming which involves both creating objects and application that use those objects, object often interrelate with other objects , and once created objects can be reused over an over again.

Example of procedural language class myexample { public static void main (String args []) { int age; double salary; String middle_initial;

age = 21; salary = 29521.12; middle_initial = "K"; System.out.println ("I am " + age + " years old "); System.out.println ("I make " + salary + " per year"); System.out.println ("My middle initial is " + middle_initial); } }

class Bicycle { int cadence = 0; int speed = 0; int gear = 1; void changeCadence(int newValue) { cadence = newValue; } void changeGear(int newValue) { gear = newValue; } void speedUp(int increment) { speed = speed + increment; } void applyBrakes(int decrement) { speed = speed - decrement; }

void printStates() { System.out.println("cadence:" + cadence + " speed:" + speed + " gear:" + gear); }}

class BicycleDemo { public static void main(String[] args) { // Create two different // Bicycle objects Bicycle bike1 = new Bicycle(); Bicycle bike2 = new Bicycle(); // Invoke methods on // those objects bike1.changeCadence(50); bike1.speedUp(10); bike1.changeGear(2); bike1.printStates(); bike2.changeCadence(50); bike2.speedUp(10); bike2.changeGear(2); bike2.changeCadence(40); bike2.speedUp(10); bike2.changeGear(3); bike2.printStates(); }}

There are three basic elements of procedural programming; Sequence order of which instruction are executed is sequence of programming

Selection if / else conditional statements and other forms of the second element. Iteration the use of the loops and other forms of repetitive sets of instructions forms.

Variables

are names given to blocks of the computer's memory. The names are used to store values in these blocks of memory. Variables can hold values which are either numbers, strings or Boolean. We already know what numbers are. Strings are made up of letters. Boolean variables can have one of two values, either True or False. You must always declare a variable before you use it. We use the var statement to do this. You must also choose what type of variable it is.

The

programmer assigns the names to variables, known as identifiers. An Identifier must be unique within a scope of the program. Variables have a data type, that indicates the kind of value they can store.

The data type indicates the attributes of the variable, such as the range of values that can be stored and the operators that can be used to manipulate the variable. Example of different data types in paschal programming

Byte Word ShortInt Integer LongInt Real Char String Boolean

0 to 255 0 to 65535 -128 to 127 -32768 to 32767 -4228250000 to 4228249000 floating point values 1 character up to 255 characters true or false

Here is an example of how to declare an integer variable named i:

program Variables; var i: Integer; begin end.

To assign a value to a variable we use :=. program Variables; var i: Integer; begin i := 5; end.

You can create 2 or more variables of the same type if you separate their names with commas. You can also create variables of a different type without the need for another var statement. program Variables; var i, j: Integer; s: String; begin end.

When you assign a value to a string variable, you must put it between single quotes. Boolean variables can only be assigned the values True and False.

program Variables; var i: Integer; s: String; b: Boolean; begin i := -3; s := 'Hello'; b := True; end.

Printing variables on the screen is just as easy. If you want to print variables and text with the same Writeln then seperate them with commas.

program Variables; var i: Integer; s: String; begin i := 24; s := 'Hello'; Writeln(i); Writeln(s,' world'); end.

You can read vales from the keyboard into variables using Readln and ReadKey. ReadKey is from the crt unit and only reads 1 character. You will see that ReadKey works differently to Readln program Variables; uses crt; var i: Integer; s: String; c: Char; begin Readln(i); Readln(s); c := ReadKey; Writeln( I is , i , s is , s, c is , c ); Readln; end.

The Writeln command prints words on the screen. program Hello; begin Writeln('Hello world'); end. You will see that the "Hello world" is between single quotes. This is because it is what is called a string. All strings must be like this. The semi-colon at the end of the line is a statement separator. You must always remember to put it at the end of the line.

The Readln command will now be used to wait for the user to press enter before ending the program. program Hello;

begin Write('Hello world'); Readln; end.


You must now save your program as hello.pas.

Writeln is just like Write except that it moves the cursor onto the next line after it has printed the words. Here is a program that will print "Hello" and then "world" on the next line: program Hello;

begin Writeln('Hello'); Write('world'); Readln; end.


If you want to skip a line then just use Writeln by itself without any brackets.

The commands that are built into your Pascal compiler are very basic and we will need a few more. Units can be included in a program to give you access to more commands. The crt unit is one of the most useful. The ClrScr command in the crt unit clears the screen. Here is how you use it: program Hello; uses crt; begin ClrScr; Write('Hello world'); Readln; end.

Comments are things that are used to explain what parts of a program do. Comments are ignored by the compiler and are only there for the people who use the source code. Comments must be put between curly brackets. You should always have a comment at the top of your program to say what it does as well as comments for any code that is difficult to understand. Here is an example of how to comment the program we just made: {This program will clear the screen, print "Hello world" and wait for the user to press enter.} program Hello; uses crt; begin ClrScr;{Clears the screen} Write('Hello world');{Prints "Hello world"} Readln;{Waits for the user to press enter} end.

Variables can be used in calculations. For example you could assign the value to a variable and then add the number 1 to it. Here is a table of the operators that can be used:
Operator + * / div Meaning addition subtraction multiplication Floating point divide Integer divide

mod

Remainder of integer division

The following example shows a few calculations that can be done: program Variables; var Num1, Num2, Ans: Integer; begin Ans := 1 + 1; Num1 := 5; Ans := Num1 + 3; Num2 := 2; Ans := Num1 - Num2; Ans := Ans * Num1; end.

Program addition; Uses Crt; Var Num1, num2, answ: integer; Begin Writeln(enter two numbers); Readln(num1); Readln(num2); Answ:= num1 +num2; Writeln( sum of , num1, and , num2 , is , answ) Readln; end.

SQR(Real Variable) Explanation: SQR returns the square of the real variable that is passed to it, pretty simple really. Example: x := SQR(y); This finds the square of y and puts the result in x.

SQRT Syntax: SQRT(Real Variable) Explanation: SQRT returns the square root of the real variable that is passed to it, pretty simple really.Example: x := SQRT(y); This finds the square root of y and puts the result in x.

SINSyntax: SIN(Real variable) Explantation: SIN returns the sin of the number that is passed to it. Unfortunately this is in radians(stupid radians). 2*pi radians is equal to 360 degrees, so to convert from degrees to radians it is degrees/180 * pi, and from radians to degrees it is radians/pi * 180. It is a bit of a hassle but nevermind. Example: x := SIN(y); This finds the sin of y(radians) and puts the value in x.

Strings hold characters. Characters include the letters of the alphabet as well as special characters and even numbers. It is important to understand that integer numbers and string numbers are different things. You can add strings together as well. All that happens is it joins the 2 strings. If you add the strings '1' and '1' you will get '11' and not 2.

program Variables;
var s: String; begin s := '1' + '1'; end.

example: Program math; Const pi:=3.142857; Var x,y,z: real; Begin Writeln(enter angle in degree); Readln(x); y:=(x * pi)/ 180; z:=cos (y); Writeln( cosine of angle , x , is , z); Readln; end.

Constants are like variables except that their values can't change. You assign a value to a constant when you create it. const is used instead of var when declaring a constant. Constants are used for values that do not change such as the value of pi. program Variables; const pi: Real = 3.14; var c, d: Real; begin d := 5; c := pi * d; end.

You can access a specific character in a string if you put the number of the position of that character in square brackets behind a string. program Strings; var s: String; c: Char; begin s := 'Hello'; c := s[1];{c = 'H'} Writeln ( the first character from word hello is , c); Readln; end.

You can get the length of a string using the Length command. program Strings; var s: String; l: Integer; begin s := 'Hello'; l := Length(s);{l = 5} Writeln( the length of the string is , I ); Readln; end.

To find the position of a string within a string use the Pos command. Parameters: 1: String to find 2: String to look in program Strings; var s: String; p: Integer; begin s := 'Hello world'; p := Pos('world',s); Writeln(p); Readln; end.

The Str command converts an integer to a string. program Convert; var s: String; i: Integer; begin i := 123; Str(i,s); Writeln( s now is , s); Readln; end.

Round will round off a real number to the nearest integer. program Convert; var i: Integer; begin i := Round(3.14); Writeln(i); Readln; end.

The UpCase command changes a character from a lowercase letter to and uppercase letter. program Convert; var c: Char; begin c := 'a'; c := UpCase(c); Writeln(c); readln; end.

Are words which has certain meaning in a compiler. Example of keywords are var, type, const, uses 'Type' declares any variable structures 'Const' declares any constant values to use throughout your program. These are anything which is always the same, such as the number of days in the week. Alternatively if you use a set value throughout your program, it is a good idea to make this a constant value so that it can easily be changed if you later decide to do so. The 'Uses' keyword allows your program to use extra commands. These extra commands are stored together in what is called a module or library. These modules have names such as CRT, or GRAPH. Each modules contains several extra commands.

eg. uses crt, graph; {This means pascal allows you to uses the extra commands in the crt and graph modules} const InchesInFoot = 12; {These are some constants you might use} DaysInWeek = 7; e = 2.1718281828; type {Type definitions go here - don't worry about these yet} var (*variables are declared here*) begin end.

Is a selection statement which follow the condition defined within the program. if then if then else program Decisions; var i: Integer; begin Writeln('Enter a number'); Readln(i); if i > 5 then Writeln('Greater than 5'); readln; end. The above example only tells you if the number is greater than 5. If you want it to tell you that it is not greater than 5 then we use else. When you use else you must not put a semi-colon on the end of the command before it.

program Decisions; var i: Integer; begin Writeln('Enter a number'); Readln(i); if i > 5 then Writeln('Greater than 5') else Writeln('Not greater than 5'); end. If the condition is True then the then part is chosen but if it is False then the else part is chosen. This is because the conditions such as i > 5 is a Boolean equation. You can even assign the result of a Boolean equation to a Boolean variable.

If you want to use more than 1 condition then you must put each condition in brackets. To join the conditions you can use either AND or OR. If you use AND then both conditions must be true but if you use OR then only 1 or both of the conditions must be true. program Decisions; var i: Integer; begin Writeln('Enter a number'); Readln(i); if (i > 1) and (i < 100) then Writeln('The number is between 1 and 100'); end.

program Decisions; var i: Integer; begin Writeln('Enter a number'); Readln(i); if i > 0 then begin Writeln('You entered ',i); Writeln('It is a positive number'); end; end.

You can also use if statements inside other if statements. program Decisions; var i: Integer; begin Writeln('Enter a number'); Readln(i); if i > 0 then Writeln('Positive') else if i < 0 then Writeln('Negative') else Writeln('Zero'); end.

You might have noticed that sometimes the if statement may get a little cumbersome to use. ie: if i = 0 then ... else if i = 1 then ... else if i = 2 then And so on. This is really cumbersome and annoying (you have to type the same thing over and over). So what you want to use is the case statement.

program Decisions; uses crt; var Choice: Char; begin Writeln('Which on of these do you like?'); Writeln('a - Apple:'); Writeln('b - Banana:'); Writeln('c - Carrot:'); Choice := ReadKey; case Choice of 'a': Writeln('You like apples'); 'b': Writeln('You like bananas'); 'c': Writeln('You like carrots'); else Writeln('You made an invalid choice'); end; end.

Loops are used when you want to repeat code a lot of times. For example, if you wanted to print "Hello" on the screen 10 times you would need 10 Writeln commands. You could do the same thing by putting 1 Writeln command inside a loop which repeats itself 10 times. There are 3 types of loops which are the for loop, while loop and repeat until loop.

The for loop uses a loop counter variable, which it adds 1 to each time, to loop from a first number to a last number. program Loops; var i: Integer; begin for i := 1 to 10 do Writeln('Hello'); end. If you want to have more than 1 command inside a loop then you must put them between a begin and an end.

program Loops; var i: Integer; begin for i := 1 to 10 do begin Writeln('Hello'); Writeln('This is loop ',i); end; end.

The while loop repeats while a condition is true. The condition is tested at the top of the loop and not at any time while the loop is running as the name suggests. A while loop does not need a loop variable but if you want to use one then you must initialize its value before entering the loop. program Loops; var i: Integer; begin i := 0; while i <= 10 do begin i := i + 1; Writeln('Hello'); end; end.

The repeat until loop is like the while loop except that it tests the condition at the bottom of the loop. It also doesn't have to have a begin and an end if it has more than one command inside it. program Loops; var i: Integer; begin i := 0; repeat i := i + 1; Writeln('Hello'); until i = 10; end. If you want to use more than one condition for either the while or repeat loops then you have to put the conditions between brackets.

Arrays are variables that are made up of many variables of the same data type but have only one name. Here is a visual representation of an array with 5 elements:

1 value 1 2 value 2 3 value 3 4 value 4 5 value 5 Arrays are declared in almost the same way as normal variables are declared except that you have to say how many elements you want in the array. program Arrays; var a: array[1..5] of Integer; begin end.

We access each of the elements using the number of the elements behind it in square brackets. program Arrays; var a: array[1..5] of Integer;

begin a[1] := 12; a[2] := 23; a[3] := 34; a[4] := 45; a[5] := 56; end.

It is a lot easier when you use a loop to access the values in an array. Here is an example of reading in 5 values into an array: program Arrays; var a: array[ ] of Integer; i: Integer; begin for i := 1 to 5 do Readln(a[i]); end.

How can you access element of an array by using for loop Example Program well; Var i: integer; A: array [1..5] of an integer; Begin A[1]:=12; A[2]:=45; A[3]:=62; A[4]:=85; A[5]:=39; for i:=1 to 5 do Writeln(A[i]); Readln; End.

You will sometimes want to sort the values in an array in a certain order. To do this you can use a bubble sort. A bubble sort is only one of many ways to sort an array. With a bubble sort the biggest numbers are moved to the end of the array. You will need 2 loops. One to go through each number and another to point to the other number that is being compared. If the number is greater then it is swapped with the other one. You will need to use a temporary variable to store values while you are swapping them.

program Arrays; var a: array[1..5] of Integer; i, j, tmp: Integer; begin a[1] := 23; a[2] := 45; a[3] := 12; a[4] := 56; a[5] := 34; for i := 1 to 4 do for j := i + 1 to 5 do if a[i] > a[j] then begin tmp := a[i]; a[i] := a[j]; a[j] := tmp; end; for i := 1 to 5 do writeln(i,': ',a[i]); end.

Procedures are sub-programs that can be called from the main part of the program. Procedures are declared outside of the main program body using the procedure keyword. Procedures must also be given a unique name. Procedures have their own begin and end. Here is an example of how to make a procedure called Hello that prints "Hello" on the scree To use a procedure we must call it by using its name in the main body. Procedures must always be above where they are called from. Here is an example of a procedure that calls another procedure.

program Procedures; procedure Hello; begin Writeln('Hello'); end; begin Hello; end.

Procedures can have parameters just like the other commands we have been using. Each parameter is given a name and type and is then used just like any other variable. If you want to use more than one parameter then they must be separated with semi-colons. program Procedures; procedure Print(s: String; i: Integer); begin Writeln(s); Writeln(i); end; begin Print('Hello',3); end.

Functions are like procedures except they return a value. The function keyword is used instead of procedure when declaring a function. To say what data type the return value must be you must use a colon and the name of the type after the function's name. Assigning the value of a function to a variable make the variable equal to the return value, To set the return value just make the name of the function equal to the value you want to return.

program Functions; var Answer: Integer; function Add(i, j:Integer): Integer; begin Add := i + j; end; begin Answer := Add(1,2); Writeln(Answer); end.

program Procedures; procedure GetName; var Name: String; begin Writeln('What is your name?'); Readln(Name); if Name = '' then Exit; Writeln('Your name is ',Name); end; begin GetName; end.

Types

of parameters Value parameter Reference parameter(variable)

Das könnte Ihnen auch gefallen