Variables and Data Types in Pascal

July 20, 2024

Understanding Variables in Pascal

In programming, variables are essential as they allow us to store and manipulate data. In Pascal, a variable is a named storage location in memory that can hold a value. The value can change during the execution of a program, which is why we refer to it as a variable.

Declaring Variables

To declare a variable in Pascal, you need to specify its type and name. The syntax for declaring a variable is as follows:

var
  variableName: dataType;

Here, var is the keyword used to indicate the start of a variable declaration, variableName is the name you choose for your variable, and dataType is the type of data that the variable will hold.

Data Types in Pascal

Pascal supports several data types, which can be broadly categorized into the following:

  • Integer: Used for whole numbers.
  • Real: Used for floating-point numbers (numbers with decimals).
  • Char: Used for single characters.
  • String: Used for sequences of characters (text).
  • Boolean: Used for true/false values.

Examples of Variable Declaration

Let’s take a look at how to declare variables of different data types in Pascal:

var
  age: Integer;
  salary: Real;
  initial: Char;
  name: String;
  isEmployed: Boolean;

Assigning Values to Variables

Once you have declared a variable, you can assign a value to it using the assignment operator (:=). Here’s how you can do it:

age := 30;
salary := 50000.50;
initial := 'J';
name := 'John Doe';
isEmployed := True;

Working with Variables

After declaring and assigning values to variables, you can use them in your program. For instance, you can perform operations, display their values, or use them in conditional statements. Here’s a simple example:

begin
  WriteLn('Name: ', name);
  WriteLn('Age: ', age);
  if isEmployed then
    WriteLn(name, ' is employed.')
  else
    WriteLn(name, ' is not employed.');
end.

Conclusion

In this lesson, we explored the fundamentals of variables and data types in Pascal. Understanding how to declare variables, assign values, and work with different data types is crucial for any programming task. As you continue your journey in learning Pascal, practice these concepts by creating your own variables and manipulating them in your programs.