Here are the programs we wrote and discussed during tutorial #2 on October 17th.
greatest.pas
// compute the greatest of three integers uses math; var x, y, z: integer; greatest: integer; begin readln(x, y, z); // solution 1 if (x > y) and (x > z) then greatest := x else if y > z then greatest := y else greatest := z; // solution 2 greatest := x; if y > greatest then greatest := y; if z > greatest then greatest := z; // solution 3 greatest := max(max(x, y), z); writeln(greatest); end.
leap.pas
// Is a given year a leap year? var year: integer; leap: boolean; begin readln(year); // solution 1: a series of ifs if year mod 400 = 0 then leap := true else if year mod 100 = 0 then leap := false else if year mod 4 = 0 then leap := true else leap := false; // solution 2: a single line leap := (year mod 400 = 0) or ((year mod 4 = 0) and (year mod 100 <> 0)); writeln(leap); end.
day_of_year.pas
// Given a month and day, compute the day number within the calendar year. var days: array[1..12] of integer = (31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31); month, day: integer; leap: string; i, sum: integer; begin write('month and day? '); readln(month, day); write('leap year (yes/no)? '); readln(leap); if leap = 'yes' then days[2] := 29; sum := 0; for i := 1 to month - 1 do sum := sum + days[i]; writeln(sum + day); end.
tic_tac_toe.pas
// Allow two players to play Tic Tac Toe. // This implementation is incomplete: it doesn't check for wins/draws. uses crt; var board: array[1..3, 1..3] of integer; // 0 = empty, 1 = X, 2 = O player: integer = 1; symbols: array[0..2] of char = ('.', 'X', 'O'); // or, alternatively: // symbols: string = '.XO'; row, column: integer; begin for row := 1 to 3 do for column := 1 to 3 do board[row, column] := 0; repeat clrScr; // draw the board for row := 1 to 3 do begin for column := 1 to 3 do write(symbols[board[row, column]], ' '); writeln; writeln; end; repeat write('player ', symbols[player], ' enter row/column: '); readln(row, column); if board[row, column] <> 0 then writeln('You can''t go there'); until board[row, column] = 0; board[row, column] := player; player := 3 - player; until false; end.