Pascal Programming/Boolean Expressions and Control Flow

From Wikibooks, open books for an open world
Jump to: navigation, search

Conditional Statements[edit]

If..Then..Else[edit]

The simplest control structure is the if..then..else statement.

if var1 = 0 then  
    writeln('var1 is 0!')  (*No semicolon before an 'Else' keyword*)
else if var1 = 1 then 
begin
    writeln('var1 is 1!');
    (*More code*)
end  (*No semicolon before an 'Else' keyword*)
else if var1 = 2 then 
begin
    writeln('var1 is 2!');
    (*More code*)
end  (*No semicolon before an 'Else' keyword*)
else 
begin
    writeln('var1 is not 0, 1, or 2!');
    (*More code*)
end;  (*Semicolon used to indicate the end of the If-then-else*)

Case[edit]

Case var1 of
  1 : writeln('var1 is 1!');
  2 : Begin
    writeln('var1 is 2!');
    (*More code*)
  End;
  Else writeln('var1 is neither 1 nor 2!'); (*'else' can be used instead of the 'otherwise' keyword*)
end;

Loops[edit]

For[edit]

For var1 := 0 to 12 do  (*For conditional with only one statement:*)
  writeln('var1 is ', var1);
 
For var2 := 12 downto 0 do Begin  (*For conditional with multiple statements:*)
  writeln('var2 is ', var2);
  (*More code*)
End;

While[edit]

While var1 = 0 do (*While the condition is True, perform the following code*)
  writeln('woo, an infinite loop!');
 
While var2 = 0 do Begin (*While-do with multiple statements:*)
  writeln('aww, no infinite loop!');
  var2 := 1;
End;

Repeat..Until[edit]

Repeat (*Repeat the following until the condition is True:*)
  writeln('var1 might be 0!');
  (*More code - Begin..End is not required between Repeat..Until*)
  (*Semicolon needed before the 'Until' keyword*)
Until var1 = 0;