Day 4

This is the day 4 page for computer programming course 101, an introductions to computer programming. Day 4 introduces the concept of statements.

Below are the topics and course materials we are learning today.

Statements

Statements define the algorithmic logic of your programs. Simple statements like assignments and procedure calls can combine to form loops, conditional statements, and other structured statements. Multiple statements within a block are separated by semicolons.

Simple Statements

A simple statement doesn't contain any other statements. Simple statements include assignments, calls to procedures and functions.

An assignment statement has the form:
Variable := Expression;
Where variable is any variable reference such as we previously discussed. The expression part is any type compatible expression. The := symbol is sometimes called the assignment operator. An assignment statement replaces the current value of variable with the value of expression. For example:
I := 3;
Assigns the value 3 to the variable I. The variable reference on the left side of the assignment can appear in the expression on the right. For example:
I := I + 1;
Increments the value of I. Other assignment statements might look like:
X := Y + Z;
Done := (I >= 1) and (I < 100);
Purple := Mix(Blue, Red);
I := Sqr(J) - I * K;
SomeText[I + 1] := Chr(I);

Procedure and Function Call Statements

A procedure call consists of the name of a procedure, followed by an argument list if required. Here are some examples of procedure or function calls.
WriteLn('Hello World!');
PrintHeading;
Transpose(X, Y, Z);
Find(FirstName, LastName);
CalculateRoute(Location);
Sqrt(X);
Notice in statements that are purely calls to procedures or functions there is no assignment operator. The difference between a function and a procedure is that a function may return a result. If omit an assignment operator, the result of a function is discarded. We will discuss procedures and functions in more detail in our next daily session.

Compound Statements

A compound statement is a sequence of other (simple or structured) statements to be executed in the order in which they are written. The compound statement is bracketed by the reserved words begin and end, and its constituent statements are separated by semicolons. For example:
begin
  T := X;
  X := Y;
  Y := Z;
  Z := T;
end;
Compound statements are essential in contexts where syntax rules requires a single statement. In addition to program, function, and procedure blocks, they occur within other structured statements, such as conditionals or loops. For example:
begin
  I := Length(S);
  while I > 0 do
  begin
     WriteLn(S[I]);
     I := I - 1;
  end;
end;
You can write a compound statement that contains only a single constituent statement, but begin and end sometimes serve to disambiguate and to improve readability. You can also use an empty compound statement to create a block that does nothing:
if Condition then
begin
end;

Flow Control Statements

Most all computer languages offer various kinds of statements to control the flow of your programs. These flow control statement have different uses, and different condition types, but all are used to divert the flow of statements between on or more other statements.

If Statements

The if statement is probably the most common flow control statement computer programmers use. It is used to divert the flow to a statement in the event a condition is True, and optionally to another statement if the condition is False. There two form of the if statement take the form of:
if Expression then StatementOne;
and
if Expression then StatementOne else StatementTwo;
Note that the ; semicolon appears at the end of if statement and not at the end of either StatementOne or StatementTwo. In practice the if statement might look something like:
if FileExists(FileName) then
  FileRead(FileName)
else
  WriteLn('Could not open file ', FileName);
The expression between the if and then keywords must resolve to a boolean, therefore we can surmise that FileExists is a function that returns either True or False.

If statements, like all other conditional statements, can be nested. When nesting if statements they may take the following form:
if Total > 0 then
  if Total > AccountBalance then
    WriteLn('Total exceeds account balance. Purchase declined.')
  else
  begin
    Order := ProcessCurrentTransaction;
    WriteLn('You order number is ', Order);
  end
else
  WriteLn('You have nothing in your shopping cart');
Again note the placements of the ; semicolon symbols in the example above.

Case Statements

The case statement may provide a readable alternative to deeply nested if conditionals. A case statement has the form of:
case Expression of
  Label1: Statement1;  
  Label2: Statement2;  
  Label3: Statement2;  
  else Statement4;
end;
The expression in a case statement must resolve to an ordinal or Char type, and the matching labels must be of the same type as the expression. Here is an example of how a case statement might be used in your programs:
case CurrentKey of
  KeyLeft: PlayerMoveLeft;
  KeyRight: PlayerMoveRight;
  KeySpace: PlayerFire;
  KeyEnter: ToggleChat;
  KeyTilda:
    begin
      GamePause;
      ShowConsole;
      PrintInfo;
    end;
  else 
    LogKeyPress('No action is mapped to ', CurrentKey);
end;

Looping Statements

Looping statements allow you to execute a sequence of statements repeatedly, using a control condition to determine when the execution stops. Pascal has three kinds of looping statements, repeat , while statements, and for statements.

All looping statements allow for special procedures to prematurely either stop or restart a loop. These procedures are Break, terminates the statement in which it occurs, and Continue to restart a executing the at the next iteration of the loop.

Repeat Statements

The syntax of a repeat statement is:
repeat Statement until Expression;
Expression must resolve to a Boolean value, and again note the placement of the semicolon. The repeat statement executes its sequence of constituent statements continually, testing expression after each iteration. When expression returns True, the repeat statement terminates. The sequence is always executed at least once because expression is not evaluated until after the first iteration.

Here is an example of a repeat statement:
repeat
  WriteLn('Enter a value from (1..100):');
  ReadLn(I);
until (I >= 1) and (I <= 100);
Notice how several statements can appear between the repeat and until keywords without the need for a begin and end. If you have multiple statements between begin and end you must to use ; semicolons to separate them.

While Statements

A while statement is similar to a repeat statement, except that the control condition is evaluated before the first execution of the statement sequence. Hence, if the condition is False, the statement sequence is never executed.

The syntax of a while statement is:
while Expression do Statement;
Again expression must resolve to a boolean value and statement can be a compound statement. The while statement executes its constituent statement repeatedly, testing expression before each iteration. As long as expression returns True, execution continues.

Here is an example of a while statement:
while Time < Alarm do
begin
  CheckMessages;
  Sleep(10);
end;
Note that if a compound statement follows do, then it must be contained in a begin end block.

For Statements

A for statement, unlike a repeat or while statement, requires you to specify explicitly the number of iterations you want the loop to go through. The syntax of a for statement is:

for Counter := StartValue to FinalValue do Statement;
or
for Counter := FinalValue downto StartValue do Statement;
Counter must be a local is a local variable of an ordinal type. StartValue and FinalValue must match the type of Counter. The for statement assigned the first value to the counter and either increments or decrements the counter until it matches the second value. For purposes of controlling execution of the loop, the expressions StartValue and FinalValue are evaluated only once, before the loop begins.

Here is an example of a for statement:
for I := 1 To Length(Text) do
  Text[I] := UpCase(Text[I]);

Homework

This day your homework is to modify the following number guess program to meet these requirements:
program NumberGuess;

var
  Number, Guess: Integer;
begin
  Number := Random(99) + 1;
  WriteLn('My number is between 1 and 100');
  repeat
    WriteLn('Guess what my number is:');
    ReadLn(Guess);
  until ;
  WriteLn('You guessed it! My number was ', Number);
end.
  • The program must tell the user if their guess is lower or higher than the computer's number
  • The repeat block must end when the number and the guess match
  • The program must count the number of guesses the user made and print that number before the program ends
  • The source code file name must be course101-day004.pas

See also