I want to using case on if statement, can I use it? Because I always got error when i compile it ;w;
Error I got:
Tahun.pas(26,21) Fatal: Syntax error, ";" expected but "ELSE" found
Tahun.pas(0) Fatal: Compilation aborted
uses Crt;
var
sisa, bulan, tahun : integer;
begin
ClrScr;
writeln('masukkan tahun'); read(tahun);
sisa := tahun mod 4;
if sisa =0 then
writeln('masukkan bulan 1-12'), read(bulan);
case bulan of
1: write('31');
2: write('29');
3: write('31');
4: write('30');
5: write('31');
6: write('30');
7: write('31');
8: write('30');
9: write('31');
10: write('30');
11: write('31');
12: write('30');
else write('bulan tidak lebih dari 12');
end;
else
writeln('masukkan bulan 1-12'), read(bulan);
case bulan of
1: write('31');
2: write('28');
3: write('31');
4: write('30');
5: write('31');
6: write('30');
7: write('31');
8: write('30');
9: write('31');
10: write('30');
11: write('31');
12: write('30');
else write('bulan tidak lebih dari 12')
end;
readln;
readln;
end.
I hope you have read the links upon the pieces of advice given in the comments yesterday. So there are several possible answers to the question:
The 1st – to repair your code:
begin
writeln('masukkan tahun');
readln(tahun);
writeln('masukkan bulan 1-12');
readln(bulan);
case bulan of
1, 3, 5, 7, 8, 10, 12: writeln('31');
2: if tahun mod 4 = 0 then
writeln('29')
else
writeln('28');
4, 6, 9, 11: writeln('30');
else
write('bulan tidak lebih dari 12');
end;
readln;
end.
2nd – to optimize it:
const
DinM: array [boolean, 1 .. 12] of byte =
((31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31),
(31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31));
begin
writeln('masukkan tahun');
readln(tahun);
writeln('masukkan bulan 1-12');
readln(bulan);
writeln(DinM[tahun mod 4 = 0, bulan]);
readln;
end.
And 3rd:
Use predesigned functions: Delphi has a function DaysInAMonth
described here.
Lazarus has it as well.
Note
Remember that all these methods (including standard functions) will give an error calculating leap years as not all years that year mod 4 = 0
are leap. For example year 1700, 1800, 1900, 2100 etc. are not leap.