Jump to content
xisto Community
Sign in to follow this  
pyost

Pascal For Beginners - Part Two Conditions and loops

Recommended Posts

This is the second part of my Pascal tutorial for beginners. Here is what the complete tutorial contains, and it might get expanded (some parts are not written yet):

Part One

Introduction

What do you need to start?

The program layout (organisation) and syntax

Variables

And what if there is an error?

"Hello World"

Input & Output

Examples

Swapping numbers

Reading and writing multiple variables

Part Two

Conditions

The IF condition

The CASE condition


Loops

The FOR loop

The WHILE loop

The REPEAT loop


Examples

Checking whether a number is positive or negative

Writing the first positive N numbers

Calculating the sum of positive numbers


Conditions

 

Conditions, as the name itself says, are parts of the code that take some condition into consideration. The easiest answer to the question "why?" would be "to make the program non-linear". Obviously, if you are creating a program, it has to do something useful, which usually means it would have to do various things. But how can you achieve that if you write line after line of code which always gets executed in the same why? That's where conditions come in handy - you can execute different parts of code depending on various things.

 

The IF condition

 

The IF condition is a piece of code that is highly likely to be used in every single application. It can also be displayed as IF - THEN - ELSE, because that is exactly how it works. The program gets a variable/condition, which can be either true or false. If it is TRUE, the program moves to "then". Otherwise, it moves to "else". The code is pretty much the same.

 

if (condition)   then doSomething   else doSomethingElse;

As already mentioned, condition can be both variable and condition. It might be a bit confusing because of the names, but the explanation will help a lot. If we want to use a variable, it must be of boolean type. This type can have only two values - true and false. Using it would look like this:

 

var   cond: boolean;begin   cond := true;   if (cond)	  then writeln('True')	 // This one get's executed	  else writeln('False');   cond := false;   if (cond)	  then writeln('True')	  else writeln('False');	 // This one get's executedend.

Simple as that. As for conditions, they also return true and false, but have a different form - two variables being compared. So, we could have:

a < b

a <= b

a > b

a >= b

a = b

 

In Pascal, the equal sign (=) isn't used for assigning values, but for comparing them. (Remember, := is for assigning)

 

var   a, b: integer;begin   a := 15;   b := 22;   if (a < b)	  then writeln('a < b')	 // This one get's executed	  else writeln('a >= b');end.

One thing to be careful are the commands after THEN and ELSE. You will notice that we don't have a semi-colon after the THEN line, but we do after the ELSE line. This is because semi-colon ends the whole IF condition, and not just a part of it. If you, however, didn't want the ELSE part, you could omit it and enter the semi-colon after THEN commands. This is a completely valid option. Furthermore, THEN and ELSE don't have to contain only one command - it can also be a block of commands, by using begin..end. Again, if you have both THEN and ELSE, there mustn't be a semi-colon after then begin..end

 

You can always combine several boolean variables and/or conditions in order to achieve a more complex level of the IF statement. However, we will deal with this in one of the following parts. This time I just wanted to explain how the system works.

 

The CASE condition

 

It might be a bit wrong to call CASE a condition, but it can be put in the same group as IF, since it allows the use of different command blocks for different values. Unlike IF, where we have either TRUE or FALSE, in CASE we choose a variable and then set commands for the values we choose. Alternatively, it could be replaced with a number of IF commands, where every one would be IF (variable == something) then ...;. Of course, instead of doing so, we can use case.

 

To start with, here are a few rules. Since each case must be limited, there has to be semi-colon at the end. A consequence of this is that we can't use a semi-colon the end the CASE condition, but have to use end;. Furthermore, besides the wanted number of cases, we can also have (but it is not obligatory) and ELSE case, which matches all the values we haven't mentioned. The following is the CASE syntax incorporate into an example

 

var   number: integer;begin   number := 3	  case number of   // number is a variable, case..of is the syntax		 1: writeln('Number one');		 2: writeln('Number two');		 3: writeln('Number three');   // this one gets executed		 else writeln('Not one nor two nor three');   number := 21	  case number of   // number is a variable, case..of is the syntax		 1: writeln('Number one');		 2: writeln('Number two');		 3: writeln('Number three');		 else writeln('Not one nor two nor three');   // this one gets executedend.

The variable doesn't have to be a number - it can be a string, a character, and even a boolean (though it doesn't make any sense to use CASE). And once again, you can use begin..end for groups of commands.

 

Loops

 

If you wanted to do the same thing several times in a row, copying it over and over again wouldn't be a good thing. What's more, what if you don't really know how many times that code should be run (if this number is entered by the user)? That's why you need Loops, another type of statements that is used "on a daily basis". Loops are statements that enclose a command or a block of commands and repeat them certain number of times. This number can either be defined in the code itself, or a variable can be used.

 

The FOR loop

 

I consider the FOR loop to be the simplest of those that will be explained in the part of the tutorial. It is because it can be replaced by both WHILE and REPEAT, which give more control. However, it is good to start with this one in order to understand how loops work.

 

The important thing about FOR is that it works with integer numbers. You have to have a variable which will serve as a counter, since the FOR loop takes a certain interval into consideration. A good "translation" of the loop would be "For each number in the interval [number_one, number_two] do a command/block of commands." Number_one must ALWAYS be assigned to a variable, because it will change after each "round". Number_two can either be a number or a variable containing a number. Number_one will change until it reaches number_two, when the loop will end. If number_one is smaller than number_two (so you want it to increment), you will use TO in the loop. Otherwise, you will use DOWNTO. Here is an example the writes out all the number from 5 to 10, and then from 10 to 5.

 

program forExample;var   counter: integer;begin   for counter := 5 to 10 do	  writeln(counter);   for counter := 10 downto 5 do	  writeln(counter);   readln;end.

As you can see, first we assign the starting number to a variable, which can then be used throughout the loop. The second number is followed by the reserved word DO, after which we enter the command(s) we want to be executed. If there are more commands, they must be enclosed in begin..end.

 

Using a non-integer number in the FOR loop will produce an error, and telling the program to go from 5 up to 3, or 3 down to 5, will cause the loop not to execute at all, because there are no numbers in the interval. (this might come in handy sooner or later).

 

The WHILE loop

 

The WHILE loop is somewhat connected to the IF condition. It runs a command/block of commands IF and AS LONG a certain condition is true. The syntax is WHILE condition DO. One important thing about the while loop is that you MUST, at some point, alter the variables so the condition becomes false. Otherwise, you would get an infite loop and would have to press CTRL+BREAK to stop the execution of the program. Here's an example with a FOR and a WHILE loop, both doing the same thing.

 

program whileExample;var   counter: integer;begin   for counter := 5 to 10 do	  writeln(counter);   counter := 5   while (counter <= 10) do	  begin		 writeln(counter);		 counter := counter + 1;	  end;   readln;end.

Before the WHILE loop, we had to assing a value to the counter variable in order to write the proper value on the first "round". Also, notice how we increment the counter every time. If we didn't do so, the condition would always be true.

 

The REPEAT loop

 

REPEAT is pretty much the same as WHILE, except it checks the condition at the end of the loop, and runs the loop as long as the condition returns FALSE. The syntax is REPEAT commands UNTIL condition. This "until" tells you that the loop will and as soon as condition becomes true. Furthermore, because of a starting and an ending word in its syntax (REPEAT/UNTIL), this loop doesn't need begin..end for multiple commands.

 

Unlike the WHILE loop, which might not get executed at all (if the condition is false at the beginning), the REPEAT loop will always run at least once. This is useful if you want to use the thing you read inside the loop in the condition. With WHILE, you wouldn't have a value on the first, because it would be read inside the loop. Because of this, we might not always be able to convert a FOR loop into a REPEAT one - when the interval in FOR is non-existent, and it doesn't run at all. And be careful not to create an infinite loop :)

 

Examples

 

Checking whether a number is positive or negative

 

The user enters a number (doesn't have to be an integer), and the program must check whether the number is positive or negative. If it is zero, a special message should be written.

 

program posNum;var   number: real;begin   readln(number);   if (number = 0)	  then writeln('The number is zero')	  else		 if (number > 0)			then writeln('The number is positive')			else writeln('The number is negative');   readln;end.

After reading the number, we first check whether it is zero. If it is, we write the appropriate message. If it is not, we start the other IF condition, which is inside the ELSE part. It just check if the number is positive or negative. You might wonder why there isn't a begin..end around the second IF condition. That's because IF is one command, and THEN and ELSE are just a part of it. The last readln is there to stop the window from closing immediately after writing the message.

 

Writing the first positive N numbers

 

The user enters a positive integer number N (N>0). Our task is to print out all the numbers from one to N.

 

program writeNums;var   counter: integer;   number: integer;begin   readln(number);   for counter := 1 to number do	  writeln(counter);   readln;end.

So, the user wants us to write all the numbers up to number? No problem, we will just write one by one for all number from 1 to number :ph34r: The code says it all.

 

Calculating the sum of positive numbers

 

The user starts entering positive (real) numbers, hitting enter after each one, and the program adds all those numbers to a sum. It should do so until the user enters a zero, and write the sum after that.

 

program sum;var   number: real;   sum: real;begin   sum := 0;   repeat	  readln(number);	  sum:=sum+number;   until (number = 0);   writeln(sum);   readln;end.

As already mentioned, it is always good to assign a start value to the variable, because we don't know what it contains in the beginning. After that, the program REPEATs reading numbers and adding them to the sum UNTIL it read a number which is zero. Even though we do add the zero to the sum after we read it, it doesn't bothers us much, does it? We could have used a WHILE loop, but that wouldn't suit us, because we wouldn't have had a number to check.

 

Loops and conditions are probably the two most important branches of programming, and it doesn't matter which language we are talking about. Without understanding these two and mastering them to a sufficiently high level, you cannot expect to make serious applications.

Share this post


Link to post
Share on other sites
how can i use if-then statements if the user will input a single name then display, and the other will input 2 names then displayPascal For Beginners - Part Two

program NewEstNow;uses crt;var name,nn,address,bday,day: string; e,x,m,p,r: string; u,v,j,y,z: integer; uu,vv,jj,jjj,yy,zz: integer; a,b,c,d,f,g: integer; h,I,k,l,and,o,q: integer; s,t,code,age,month: integer;Begin clrscr; write('Enter your complete name: ');{John Daryle V. Marangit} readln(name); u := length(name);{23} v := u - y; {23 - 14 + 2 = 11} j := pos('.',name); (*4*) jjj:= pos(' ',name); y := j + 2; z := j - 1; yy:= jjj + 2; zz:= jjj + 1; write('Enter your address: '); readln(address); a := length(address); b := pos(',',address); c := b + 2; d := a - (b+1); e := copy(address,c,d); f := pos(' ',e); g := f + 1; write('Enter your birthday: '); readln(bday); h := length(bday); I := pos(' ',bday); x := copy(bday,1,I-1); k := pos(',',bday); l := h - (k-1); m := copy(bday,k,l); and := h - (I-1); o := and - l; p := copy(bday,I+1,o-1); q := pos(' ',m); r := copy(m,q+1,4); val(p,s,code); val(r,t,code); age := 2009 - t; begin if(x='January') or (x='january') then month:=1; if(x='Febuary') or (x='febuary') then month:=2; if(x='March') or (x='march') then month:=3; if(x='April') or (x='april') then month:=4; if(x='May') or (x='may') then month:=5; if(x='June') or (x='june') then month:=6; if(x='July') or (x='july') then month:=7; if(x='August') or (x='august') then month:=8; if(x='September') or (x='september') then month:=9; if(x='October') or (x='october') then month:=10; if(x='November') or (x='november') then month:=11; if(x='December') or (x='december') then month:=12; end; begin; if ( s = 1 ) or ( s = 21 ) or ( s = 31 ) then day:='st'; if ( s = 2 ) or ( s = 22 ) then day:='nd'; if ( s = 3 ) or ( s = 23 ) then day:='rd'; if ( s = 4 ) or ( s = 14 ) or ( s = 24 ) then day:='th'; if ( s = 5 ) or ( s = 15 ) or ( s = 25 ) then day:='th'; if ( s = 6 ) or ( s = 16 ) or ( s = 26 ) then day:='th'; if ( s = 7 ) or ( s = 17 ) or ( s = 27 ) then day:='th'; if ( s = 8 ) or ( s = 18 ) or ( s = 28 ) then day:='th'; if ( s = 9 ) or ( s = 19 ) or ( s = 29 ) then day:='th'; if ( s = 10 ) or ( s = 20 ) or ( s = 30 ) then day:='th'; if ( s = 11 ) or ( s = 12 ) or ( s = 13 ) then day:='th'; end; if (t<0) then begin writeln(' '); writeln('Invalid!, in Year...'); readln; exit end; if (s>31) or (s<0) then begin writeln(' '); writeln('Invalid!, in Day...'); readln; exit end; begin writeln(''); writeln('Name: ', copy(name,y,v),', ',copy(name,1,1),'. ',copy(name,z,2)); writeln('Address: ', copy(address,1,B), ' ',copy(address,c,3),'. ',copy(e,g,3),'.'); writeln('Birthdate: ',s,'',day,' of ',month,'(',copy(bday,1,3),')',m,'.'); writeln('Age: ',age,' years young'); readln; end; begin writeln(''); writeln('Name: ', copy(name,y,v),', ',copy(name,1,1),'. ',copy(name,zz,1),'. ',copy(name,z,2)); writeln('Address: ', copy(address,1,B), ' ',copy(address,c,3),'. ',copy(e,g,3),'.'); writeln('Birthdate: ',s,'',day,' of ',month,'(',copy(bday,1,3),')',m,'.'); writeln('Age: ',age,' years young'); readln; exit end;End.

-reply by Daryle

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

×
×
  • Create New...

Important Information

Terms of Use | Privacy Policy | Guidelines | We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.