If-then-else statement doesn't work - Programmers Heaven

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

If-then-else statement doesn't work

Dr. KilljoyDr. Killjoy Posts: 13Member
I'm an absolute beginner at Pascal, and I decided to try to make a working If-then-else statement. The program is very small and basic, so it's pretty self-explanatory. I've checked several tutorials, but I still don't see what I could be doing wrong.

Basically, it asks the user what two plus two is, prompts for and answer, and then says whether the user is right or wrong. However, I seem to have done something wrong at ELSE. Here's the program, and the error given when I try to run it:

[img=http://img224.imageshack.us/img224/8016/badprogramkp2.png]

Thanks in advance to anyone who can help.

Comments

  • zibadianzibadian Posts: 6,349Member
    : I'm an absolute beginner at Pascal, and I decided to try to make a
    : working If-then-else statement. The program is very small and basic,
    : so it's pretty self-explanatory. I've checked several tutorials, but
    : I still don't see what I could be doing wrong.
    :
    : Basically, it asks the user what two plus two is, prompts for and
    : answer, and then says whether the user is right or wrong. However, I
    : seem to have done something wrong at ELSE. Here's the program, and
    : the error given when I try to run it:
    :
    : [img=http://img224.imageshack.us/img224/8016/badprogramkp2.png]
    :
    : Thanks in advance to anyone who can help.
    :
    This is a common beginners mistake. Many beginners think that all the statements between [b]then[/b] and [b]else[/b] are combined together when a condition is true:
    [code]
    if i = 4 then
    writeln(i);
    readln;
    else
    writeln('8');
    readln;
    [/code]
    This is far from the truth. In reality only 1 thing may be present between the [b]then[/b] and the [b]else[/b]. Also the if-then-else statement is seen as 1 complex statement, thus no semicolons (;) may be placed before the else. Here's an example of the same code, but correct Pascal:
    [code]
    if i = 4 then
    writeln(i) { <= Notice no ; }
    else
    writeln('8');
    readln;
    [/code]
    If you want to perform multiple statements between the [b]then[/b] and [b]else[/b], you need to combine them into a "block statement" using [b]begin[/b] and [b]end[/b]:
    [code]
    if i = 4 then
    begin
    writeln(i);
    readln(i); { <= Notice the ; because the next word is [b]end[/b] }
    end { <= Notice no ; } else begin
    writeln('8');
    readln;
    end;
    [/code]
  • Dr. KilljoyDr. Killjoy Posts: 13Member
    All right, thanks. Works perfectly now.
Sign In or Register to comment.