Exercises: Variables, Types, and Expressions

Part A: Conceptual Questions

A1. Explain in your own words why Pascal requires you to declare variables before using them. Give an example of a bug this prevents.

A2. What three things does a type determine about a variable?

A3. Explain the difference between a variable and a constant. When should you use each?

A4. Why does Pascal use := for assignment instead of =? What advantage does this provide over languages like C or Python?

A5. What is the difference between strong typing and weak typing? Give an example of a statement that would compile in a weakly typed language but cause a compile error in Pascal.

A6. Explain why (age >= 18) and (age <= 65) requires parentheses around the comparisons. What would happen without them?

A7. In your own words, explain the threshold concept: "strong typing as safety net." Why is the type system a feature rather than a limitation?


Part B: Tracing and Prediction

For each code fragment, predict the output without running the code. Then verify by compiling and running.

B1.

var
  x: Integer;
  y: Real;
begin
  x := 7;
  y := x / 2;
  WriteLn(x);
  WriteLn(y:0:2);
end.

B2.

var
  a, b, c: Integer;
begin
  a := 10;
  b := 3;
  c := a div b;
  WriteLn(c);
  WriteLn(a mod b);
  WriteLn(a / b:0:4);
end.

B3.

var
  ch: Char;
begin
  ch := 'G';
  WriteLn(Ord(ch));
  WriteLn(Chr(Ord(ch) + 1));
  WriteLn(Ord(ch) - Ord('A'));
end.

B4.

var
  p, q: Boolean;
begin
  p := True;
  q := False;
  WriteLn(p and q);
  WriteLn(p or q);
  WriteLn(not p);
  WriteLn(p xor q);
end.

B5.

var
  s: String;
begin
  s := 'Pascal';
  WriteLn(Length(s));
  WriteLn(s[1]);
  WriteLn(s[Length(s)]);
  WriteLn(s[3]);
end.

B6.

var
  x: Real;
begin
  x := 7.5;
  WriteLn(Trunc(x));
  WriteLn(Round(x));
  x := 8.5;
  WriteLn(Round(x));
end.

Part C: Programming Exercises

C1. Variable Declaration Practice Write a program that declares variables for a person's first name (String), last name (String), age (Integer), height in meters (Real), and whether they are a student (Boolean). Assign sample values and display them in a neatly formatted output.

C2. Temperature Converter Write a program that stores a temperature in Fahrenheit as a Real variable, converts it to Celsius using the formula C = (F - 32) * 5 / 9, and displays both values formatted to one decimal place. Use named constants for 32, 5, and 9.

C3. Circle Calculator Write a program that declares a constant PI and a variable radius of type Real. Calculate and display the circumference (2 * PI * radius) and area (PI * radius * radius) formatted to two decimal places.

C4. Change Calculator Write a program that takes a total cost in cents as an Integer (e.g., 437 for $4.37) and calculates the number of dollars, quarters, dimes, nickels, and pennies needed to make that amount. Use div and mod extensively. Display the results.

C5. Character Explorer Write a program that declares a Char variable, assigns it a letter, and displays: - The character itself - Its ASCII code (using Ord) - The next character in the alphabet (using Chr and Ord) - Whether it is uppercase (ASCII 65–90) or lowercase (ASCII 97–122), using Boolean expressions

C6. Boolean Logic Truth Table Write a program that declares two Boolean variables p and q, assigns them True and False respectively, and prints a formatted truth table showing the results of p and q, p or q, not p, not q, and p xor q.

C7. String Information Write a program that declares a String variable with a sentence, then displays: - The full string - Its length - The first character - The last character - The first character's ASCII value

C8. Type Conversion Showcase Write a program using the SysUtils unit that demonstrates all six major conversion functions: - Trunc and Round (Real to Integer) - Ord and Chr (Char to Integer and back) - StrToInt and IntToStr (String to Integer and back)

For each, display the original value, the converted value, and a label explaining the conversion.

C9. Swap Two Variables Write a program that declares two Integer variables a and b, assigns them values, and swaps their values using a third temporary variable. Display the values before and after the swap.

C10. Operator Precedence Explorer Write a program that evaluates the following expressions and displays each result: - 2 + 3 * 4 (what is the result? why?) - (2 + 3) * 4 (compare with parentheses) - 10 - 4 - 2 (left to right) - 10 div 3 mod 2 (left to right) - 15 mod 4 + 2 * 3 (mixed precedence)

Include a comment for each explaining the evaluation order.


Part D: Debugging Exercises

Each program below contains one or more bugs. Find and fix them.

D1.

program Bug1;
var
  x: Integer;
begin
  x = 10;
  WriteLn(x);
end.

D2.

program Bug2;
var
  average: Integer;
begin
  average := 85 / 3;
  WriteLn(average);
end.

D3.

program Bug3;
var
  name: String;
  age: Integer;
begin
  name := 'Alice';
  age := 25;
  WriteLn('Name: ' + name + ', Age: ' + age);
end.

D4.

program Bug4;
var
  grade: Char;
begin
  grade := 'AB';
  WriteLn('Your grade is: ', grade);
end.

D5.

program Bug5;
var
  x, y: Integer;
begin
  x := 10;
  y := 0;
  if x > 5 and y > 0 then
    WriteLn('Both conditions met');
end.

D6.

program Bug6;
var
  total: Integer;
  price: Real;
begin
  price := 29.99;
  total := price;
  WriteLn('Total: ', total);
end.

Part E: Challenge Exercises

E1. Binary Digits Write a program that takes an integer between 0 and 255 (stored in a Byte variable) and displays its 8-bit binary representation. Use div and mod with the number 2 to extract each bit. (Hint: the leftmost bit is found by n div 128, then subtract and continue.)

E2. Roman Numeral Ones Write a program that takes an integer between 1 and 10 (stored in an Integer variable) and displays its value in Roman numerals. Use a series of if statements or build the string character by character. (We haven't covered if formally yet, but you saw it in examples — give it a try.)

E3. Precision Tester Write a program that demonstrates floating-point imprecision: - Compute 0.1 + 0.2 and compare it with 0.3 using = - Display both values to 20 decimal places - Compute the difference between 0.1 + 0.2 and 0.3 - Suggest (in a comment) how you would compare floating-point numbers for "close enough" equality

E4. Overflow Explorer Write a program that demonstrates integer overflow: - Declare a Byte variable and set it to 255 - Add 1 and display the result (without range checking) - Then add the {$R+} directive and observe what happens - Explain in a comment why this behavior matters for safety-critical software

E5. ASCII Art Table Write a program that displays a formatted table of ASCII characters from 32 (space) to 126 (~). For each, show the decimal code, the character, and whether it is a digit, uppercase letter, lowercase letter, or other symbol. Use Ord and Chr functions and Boolean expressions. (Hint: you will need a for loop — peek ahead to Chapter 5 if needed, or write it out manually for a small range like 65–90.)


Part M: Mixed Practice (Chapters 2–3)

M1. Modify your Hello World program from Chapter 2 to use a const for your name and a var for a greeting message. Build the greeting by concatenating the constant with a welcome string.

M2. Write a program that uses WriteLn with format specifiers to display a table of the first 5 powers of 2 (2^1 through 2^5). Use Integer variables and the * operator (Pascal does not have a built-in exponent operator for integers).

M3. Create a program that declares constants for a restaurant bill: MEAL_COST (Real), TAX_RATE (Real), and TIP_PERCENT (Real). Calculate the tax, tip (on pre-tax amount), and total. Display everything formatted as a receipt using WriteLn with alignment.

M4. Write a program that stores a time duration in total seconds (as a LongInt) and converts it to hours, minutes, and remaining seconds. Display the result in HH:MM:SS format. Use div and mod.

M5. Extend the PennyWise project checkpoint to include a second expense. Declare a second set of variables (expenseAmount2, expenseCategory2, etc.), assign different values, and display both expenses. Also compute and display the total of both expense amounts.