Search code examples
syntaxpascaltowers-of-hanoi

Why isn't this Pascal program working?


This program needs to solve the towers of hanoi problem, but for some reason it won't work, here's my code.

program haanoi ;

procedure Hanoi(n: integer; A, B, C: char);
    begin
    if n = 1 then
        writeln(A, '-->', C)

    else
                              <---- F
        hanoi(n-1, A, C, B);
        writeln(A, '-->',C);
        hanoi(n-1, B, A, C);
                              <--- G

    end ;
begin

Hanoi(4, 'A', 'B', 'C') ;
readln ;
end.

However when I add begin on the line F and end ; on the line G it works, why?


Solution

  • Your indentation is deceiving - your program is actually structured like this:

    program haanoi ;
    
    procedure Hanoi(n: integer; A, B, C: char);
    begin
        if n = 1 then
            writeln(A, '-->', C)
        else
            hanoi(n-1, A, C, B);
        writeln(A, '-->',C);
        hanoi(n-1, B, A, C);
    end;
    
    begin
    Hanoi(4, 'A', 'B', 'C');
    readln;
    end.
    

    I'm sure that you see where the problem is.

    If you want to include more than one line in a block you must delimit them with begin and end, which is why the program works when you do that.