Control Structures: Conditional Statements in Pascal

July 21, 2024

Control Structures: Conditional Statements in Pascal

This post explores conditional statements in Pascal, including if-else and case statements. Readers will understand how to implement decision-making in their programs based on different conditions.

Understanding Conditional Statements

Conditional statements are essential programming constructs that allow the execution of certain parts of code based on specific conditions. In Pascal, the primary forms of conditional statements are the if statement and the case statement.

If-Else Statement

The if statement is used to execute a block of code if a specified condition is true. Optionally, an else clause can be added to execute a different block of code if the condition is false.

Syntax

if condition then
  statement1
else
  statement2;

Example

Here’s a simple example that checks whether a number is positive or negative:

program CheckNumber;
var
  number: Integer;
begin
  Write('Enter a number: ');
  ReadLn(number);
  if number > 0 then
    WriteLn('The number is positive.')
  else if number < 0 then
    WriteLn('The number is negative.')
  else
    WriteLn('The number is zero.');
end.

Nested If Statements

Pascal also allows for nested if statements, where an if statement is placed inside another if statement. This is useful for checking multiple conditions.

Example

The following example demonstrates a nested if statement:

program NestedIf;
var
  score: Integer;
begin
  Write('Enter your score: ');
  ReadLn(score);
  if score >= 90 then
    WriteLn('Grade: A')
  else
    if score >= 80 then
      WriteLn('Grade: B')
    else if score >= 70 then
      WriteLn('Grade: C')
    else
      WriteLn('Grade: D');
end.

Case Statement

The case statement is another form of conditional statement that is particularly useful when you need to choose between multiple options based on the value of a single variable.

Syntax

case variable of
  value1: statement1;
  value2: statement2;
  ...
  else statementN;
end;

Example

Here’s an example of a case statement that determines the day of the week based on a number:

program DayOfWeek;
var
  day: Integer;
begin
  Write('Enter a number (1-7): ');
  ReadLn(day);
  case day of
    1: WriteLn('Monday');
    2: WriteLn('Tuesday');
    3: WriteLn('Wednesday');
    4: WriteLn('Thursday');
    5: WriteLn('Friday');
    6: WriteLn('Saturday');
    7: WriteLn('Sunday');
  else
    WriteLn('Invalid day!');
  end;
end.

Conclusion

Conditional statements in Pascal, including if-else and case statements, are powerful tools for implementing decision-making in your programs. By mastering these constructs, you can create more dynamic and responsive applications. Practice using these statements in various scenarios to become proficient in handling conditions in your Pascal programs.