Pascal: Roots of a Quadratic Equation

program ex26;
var   a, b, c, discriminant, re, im: double;
        x : char;
begin
  writeln ('Enter coefficients of a quadratic equation, a, b & c:');
  read (a, b, c);
  if (a = 0) and (b = 0)
    then writeln ('Equation is degenerate')
  else if a = 0
    then writeln ('The only root is ', -c/b)
  else if c = 0 
    then writeln ('The roots are ', -b/a, ' and ', 0)
  else
    begin
      re := -b / (2 * a);
      discriminant := sqr (b) - 4 * a * c;
      im := sqrt (abs (discriminant)) / (2 * a);
      if discriminant >= 0
        then writeln ('The roots are ', re + im, ' and ', re - im)
        else writeln ('The roots are complex: ', re, '+I*', im, ' and ', re, '-I*', im)
      end;
  readln (x);
end.

There are a number of conditions in this problem which can be dealt with by nested if statements: 

This gives us four conditions. The quantity b2-4ac is called the discriminant. If the discriminant is > 0 there are two real roots; if it is < 0 there are two complex roots - this gives rise to a further if statement.

(Example taken from Programming in Pascal by Peter Grogono)

Back to questions