Pascal: Temperature Conversion

program ex11;

var a, tconverted: real;
      f, scale: char;
begin
  writeln ('Enter a number for temperature conversion ');
  readln (a);
  writeln ('Enter c to convert from C to F or f to convert from F to C');
  readln (f);
  if f in ['c', 'C'] then 
    begin
      tconverted := a * 9 / 5 + 32;
      scale:='F';
    end
  else
    if f in ['f', 'F'] then
      begin
        tconverted:= (a - 32) * 5 / 9;
        scale:='C';
      end;
  writeln ('Converted temperature is: ', tconverted: 8:2, ' degrees ', scale);
  readln;
end.

We get a single number from the user. This is a temperature in either degrees C or F. We ask the user to enter the type of temperature on the input number, 'c' or 'f'. In case the user enters 'C' or 'F' we use the in ['c', 'C'] construction (we could use f='c' or f='f'). If the user enters 'f' then the output scale is C, if 'c' then 'F'. We use the scale variable to output the correct letter in the output statement. 

Note the absence of a ';' after the end before the else - if..then..else is continuous so should have no semi-colon before else.

Back to questions