Czech version
logolink

< Back to the list of lessons

Conditions - Branching of Program

AlgortimyContent of the lesson:

  • What Is a Condition
  • IF THEN (ELSE) Command Syntax in Pascal
  • Simple Conditions
  • Complex Conditions, Operators AND and OR
  • Example of Advanced Mathematical Formula

What Is a Condition

In a real life we often encounter conditions – deciding on the basis on some experience; for example:

  • If it is raining, I will take an umbrella.
  • I can only walk across the road when the light is green.
  • I can only walk across the road when the traffic light is green and there is no car around.

In general: When a condition is valid, then ..., otherwise ... Conditions may be of different levels of complexity and quantity – and this complicates the whole system of conditions. But then the whole system can provide solutions even for relatively complex situations.

IF THEN (ELSE) Command Syntax in Pascal

In Pascal (as in many other programming languages) exists the command IF-THEN (ELSE). The syntax of this command should be:

Basic syntax of the IF-THEN command in Pascal
IF (condition) THEN command

If we also want to specify what should happen if the condition is not valid, the command IF-THEN includes the part ELSE which is executed if the condition is not valid.

Syntax of the IF-THEN (ELSE) command in Pascal
IF (condition) THEN command-1 ELSE command-2

Simple Conditions

Take a look at the following simple example:

IF-THEN in Pascal
 Program IsNumberGreaterThanFive;
 var a:integer;
 begin
  readln(a);
  IF (a>5) THEN writeln('a is greater than 5');
  readln;
 end.

If we want to have more exact information we use the complete IF-THEN-ELSE commands:

IF-THEN-ELSE in Pascal
 Program IsNumberGreaterOrLowerThanFive;
 var a:integer;
 begin
  readln(a);
  IF (a>5) THEN
    writeln('a is greater than 5')
  ELSE
    writeln('a is not greater than 5');
  readln;
 end.

If we want to be even more precise and evaluate both inequality and equality, we have to nest another IF-THEN in one of the branches of IF-THEN-ELSE:

Nested IF-THEN in Pascal
 Program IsNumberGreaterLowerThanFiveOfEqual;
 var a:integer;
 begin
  readln(a);
  IF (a>5) THEN
    writeln('a is greater than 5')
  ELSE
    IF (a<5) THEN
      writeln('a is lower than 5')
    ELSE
      writeln('a is equal to 5');
  readln;
 end.

In this example you can notice a Pascal syntax specialty that the semicolon is not written at the end of the line before ELSE.

Complex Conditions, Operators AND and OR

If a more complex condition is needed, it can be put together from more conditions using the operators AND and OR.

AND Operator

The operator AND is a parallel to the conjunction "and". If we put together several conditions using AND, then the resultant condition is valid ONLY if EACH condition is valid. In everyday life we use this operator in the following consideration: "When it's raining AND I am out THEN I open my umbrella." or "When it is raining on me AND I have my umbrella THEN I open it." (IF (it`s raining on me) AND (I have got my umbrella) THEN (I open it)).

An example using the AND operator
 Program Operator_AND;
 var a,b:integer;
 begin
  readln(a);
  readln(b);
  IF ((a<0) AND (b<0)) THEN
    writeln('Numbers a and b are both negative')
  ELSE
    writeln('Numbers a and b are not both negative');
 end.

Note that the whole condition ((a <0) AND (b <0)) is closed in the brackets - usually it is not necessary, but in some programming languages it is required to close any complex condition in the brackets, that is why it is good way to get used to this syntax.

OR Operator

The operator OR is parallel to the conjunction "or". If we put together several conditions using OR, then the resultant condition is valid when AT LEAST ONE of the conditions is valid (and it is not valid only if none of the conditions is valid). In everyday life we use this operator in the following considerations, for example: "When I am hungry or I like tasty meals, I take something delicious." or "When I want to be a good student or I am bored, I learn something." (IF (I want to be a good student) OR (I`m bored) THEN (I learn)).

An example using the OR operator
 Program Operator_OR;
 var a,b:integer;
 begin
  readln(a);
  readln(b);
  IF ((a>0) OR (b>0)) THEN
    writeln('At least one of the numbers a and b is greater than zero.')
  ELSE
    writeln('Both numbers a and b are smaller than or equal to zero.');
 end.

You can see the results of AND and OR operators, 1 means true, 0 means false.

aba AND ba OR b
1111
1001
0100
0000

Example of Advanced Mathematical Formula

In previous lessons we solved the calculation of simple formulas. Some of them already looked quite complicated. Try to write a program for calculating a simple quotient of two numbers a and b.

Sample: Calculation of the quotient of two arbitrarily given numbers a and b.

A quotient of two numbers in Pascal
 Program Quotient_A_a_B;
 var a,b:integer;
 begin
 writeln('Enter number a:');
 readln(a);
 writeln('Enter number b:');
 readln(b);
 if (b=0) then
  writeln('Division by zero is not defined, the quotient cannot be computed.')
 else
  writeln('The quotient of the two given numbers is ',a/b)
 readln;
 end.

As we know from Math, division by zero is not an allowed operation. If we forget this fact, the program crashes when it tries to divide by zero (which is an unacceptable status). We can see that without the condition IF-THEN it is not possible to handle a simple quotient of any two numbers correctly.

We can complicate the task slightly by the requirement that the previous programme should store the quotient of a / b in a variable c. The following solution is the first thing that comes to our minds:

A quotient of two numbers in Pascal
 Program Podil_A_a_B;
 var a,b:integer;
     c:real;
 begin
 writeln('Enter number a:');
 readln(a);
 writeln('Enter number b:');
 readln(b);
 if (b=0) then
  writeln('Division by zero is not defined, the quotient cannot be computed.')
 else
  c:=a/b;
  writeln('The quotient of the two given numbers is ',c)
 readln;
 end.

Does our program actually work reliably and well? To verify this try to enter zero as a value of b. What can we see? Surprisingly, the fact that the program provides us the result! Why? The reason is that in case that b is zero, the program prints that division by zero is not a defined operation, but at the same time it displays the text "Quotient ..." and prints a value.

Why does the program write "Quotient ..."? It is because of the fact that IF and ELSE statements are linked to only one following command and then the program continues evaluating the rest of source code.

If the IF is valid c: = a / b is not carried out, because it is an ELSE instruction. Nevertheless, the command (writeln ...) is always executed, because it is the second command after ELSE and thus it is not affected by the IF-THEN-ELSE command. If you want to carry out more than one command in IF or ELSE, you have to close them between "begin" and "end" commands so that the program knows which commands belong to IF and ELSE parts. The correct solution is displayed below this text:

A quotient of two numbers in Pascal
 Program Podil_A_a_B;
 var a,b:integer;
     c:real;
 begin
 writeln('Enter number a:');
 readln(a);
 writeln('Enter number b:');
 readln(b);
 if (b=0) then
  writeln('Division by zero is not defined, the quotient cannot be computed.')
 else
  begin
    c:=a/b;
    writeln('The quotient of the two given numbers is ',c);
  end;
 readln;
 end.

Just one question remains to be answered. "Why did the program write anything as the c variable, when we had not assigned anything into it?" The reason is that once the program creates a variable it automatically assigns a value into it (usually an ABSOLUTELY ACCIDENTAL whole number so you cannot rely on variables which were assigned automatically by the program).

Individual Task

Write a program to count the formula X = (A+B) / (C/D). The user assigns the variables A, B, C and D.

Individual Task

Write a program to calculate square root from the given value A.

Questions

  1. How can you branch a program?
  2. What is the right syntax of IF and ELSE conditions? Show more samples.
  3. Is it possible to write more commands after the ELSE command to be executed?
  4. Do the IF or ELSE commands contain any specialty in syntax?
webdesign, xhtml, css, php - Mgr. Michal Mikláš