Convert if statement to case of in pascal? - pascal

Im using pascal, can u convert this code statement to case of ? In pascal ?
This my program on pascal, if statement to case of.
Thankyou very much
TYPE
MHS = record
nama1,nama2:string;
ipk1,ipk2:longint;
nim1,nim2:integer;
end;
var
DataMhs : MHS;
Begin
clrscr;
write('Masukan Nama Mahasiswa 1 : ');
readln(DataMhs.nama1);
write('Masukan NIM Mahasiswa 1 : ');
readln(DataMhs.nim1);
write('Masukan IPK Mahasiswa 1 : ');
readln(DataMhs.ipk1);
write('Masukan Nama Mahasiswa 2 : ');
readln(DataMhs.nama2);
write('Masukan NIM Mahasiswa 2 : ');
readln(DataMhs.nim2);
write('Masukan IPK Mahasiswa 2 : ');
readln(DataMhs.ipk2);
if DataMhs.ipk1 > DataMhs.ipk2 then
write('IPK ',DataMhs.nama1,'Lebih besar')
else if DataMhs.ipk2 > DataMhs.ipk1 then
write('IPK ',DataMhs.nama2,'Lebih besar')
else
write('IPK ',DataMhs.nama1,' dengan ',DataMhs.ipk2,' SAMA');
readln;
end.
I dont know how to convert it, please help. Haha

If you want to make you code better looking, then you can use that -->
with DataMhs do
begin
if ipk1 > ipk2 then write('IPK ',DataMhs.nama1,'Lebih besar');
else if ipk1 < ipk2 then write('IPK ',DataMhs.nama2,'Lebih besar');
else write('IPK ',DataMhs.nama1,' dengan ',DataMhs.ipk2,' SAMA');
end;
But I do not think that the case
is useful for that. Because case is used for known values such as:
case a of
1: Writeln(' Some code here') ;
2: Writeln(' Some code here') ;
3: Writeln(' Some code here') ;
4: Writeln(' Some code here') ;
else Writeln(' That is used for other values. ');
end;
Case cannot be used for that kind of problem.

I suspect that what you have in mind might be something like the following:
type
TCompareResult = (cmpLeftGreater, cmpRightGreater, cmpEqual);
case CompareInts(DataMhs.ipk1, DataMhs.ipk2) of
cmpLeftGreater:
write('IPK ', DataMhs.nama1, 'Lebih besar');
cmpRightGreater:
write('IPK ', DataMhs.nama2, 'Lebih besar');
else {cmpEqual}
write('IPK ', DataMhs.nama1, ' dengan ', DataMhs.ipk2, ' SAMA');
end;
However, you still need to implement this CompareInts function, and it will still need to use the same conditional structure you already have in your original code:
function CompareInts(left, right: Integer): TCompareResult;
begin
if left > right then
Result := cmpLeftGreater
else if right > left then
Result := cmpRightGreater
else
Result := cmpEqual;
end;
Thus, the function doesn't really gain you much.

Related

Program in pascal [duplicate]

This question already has answers here:
What is that the Error of Illegal assignment and how to correct it?
(2 answers)
Closed last month.
Just started to learn the Pascal programming language, I wrote an assignment that was given at the university, here is my assignment:
Build a program that will perform the following actions:
retrieve data of N elements (brand, name, atomic weight, density)
find the average density value
finding the three elements with the lowest atomic mass
writing the inputs and outputs to the text file "elements.txt"
wrote code for it, in theory everything should work, but it gives out some strange errors, if I have standard errors, I apologize for them.
program MINERALY_;
uses Crt;
const NMAX=200;
type MINERAL=record
NAZOV:string;
HUST:real;
ATOM:real;
ZNACKA:real;
end;
MINERALY=array[1..NMAX] of MINERAL;
var N,i,C,D:integer;
V:real;
MI:MINERALY;
S:string;
SUB:text;
PTVRD,CTVRD:real;
MINATOM:real;
begin
ClrScr;
Writeln('Program pre nacitanie mineralov a vypocet hodnot ich jednotlivych
vlastnosti.');
Writeln('===============================================================================');
{Vynulovanie hodnot}
CTVRD:=0;
PTVRD:=0;
MINATOM:=0;
{Nacitanie poctu mineralov}
Writeln;
Write('Zadajte pocet nacitavanych mineralov (Maximalne 200): ');
repeat
Readln(S);
Val(S,D,C);
if (C<>0) or (D<=0) or (D>200) then
begin
Writeln;
Writeln('Zadali ste nespravny pocet, alebo ste zadali nespravne znaky !');
Writeln('Hodnota moze byt od 1-200');
Write('Zadajte pocet mineralov este raz: ');
end;
N:=D;
until(N>0) and (N<=200) and (C=0);
{nacitavanie udajov, zistovanie max. a min. hodnot atd.}
for i:=1 to N do
begin
Writeln;
Write('Zadajte Znacku: ');
Readln(MI[i].ZNACKA);
Writeln;
Write('Zadajte nazov: ');
Readln(MI[i].NAZOV);
Write('Zadajte hustotu (musi byt vacsia ako 0): ');
repeat
Readln(S);
Val(S,V,C);
if (C<>0) or (V<0) then
begin
Writeln;
Writeln('Zadali ste nespravnu hodnotu, alebo ste zadali nespravne znaky !');
Write('Zadajte hustotu este raz (musi byt vacsia ako 0): ');
end;
until (V>0) and (C=0);
MI[i].HUST:=V;
CTVRD:=CTVRD+MI[i].HUST;
Write('Zadajte atómovou hmotnosťou (musi byt vacsia ako 0): ');
repeat
Readln(S);
Val(S,V,C);
if (C<>0) or (V<0) then
begin
Writeln;
Writeln('Zadali ste nespravnu hodnotu, alebo ste zadali nespravne znaky !');
Write('Zadajte atómovou hmotnosťou este raz (musi byt vascia ako 0): ');
end;
until (V>0) and (C=0);
MI[i].ATOM:=V;
if (i=1) then MINATOM:=MI[i].ATOM;
if (MI[i].ATOM<MINATOM) then MINATOM:=MI[i].ATOM;
PTVRD:=CTVRD/N;
Writeln;
Writeln('Vypocitane hodnoty: ');
Writeln('===================================');
Writeln;
Writeln('Priemerna tvrdost mineralov: ',PTVRD:2:2);
Writeln('Najnizsia hustota: ',MINATOM:2:2);
Assign(SUB,'mineral.txt');
Rewrite(SUB);
Writeln(SUB,'Nacitane mineraly: ');
Writeln(SUB,'===================================');
Writeln(SUB,'');
for i:=1 to N do
begin
Writeln(SUB,i,'. mineral: ');
Writeln(SUB,'Nazov: ',MI[i].NAZOV);
Writeln(SUB,'Znacka: ',MI[i].ZNACKA);
Writeln(SUB,'Tvrdost: ',MI[i].HUST:2:2);
Writeln(SUB,'Hustota: ',MI[i].ATOM:2:2);
Writeln(SUB,'');
end;
Writeln(SUB,'===================================');
Writeln(SUB,'Vypocitane hodnoty: ');
Writeln(SUB,'===================================');
Writeln(SUB,'');
Writeln(SUB,'Priemerna tvrdost mineralov: ',PTVRD:2:2);
Writeln(SUB,'Najnizsia hustota: ',MINATOM:2:2);
Close(SUB);
Writeln;
Writeln;
Writeln('Pre ukoncenie programu stlacte ENTER !');
Readln;
end.
Here are the errors this code gives me:
Compiling main.pas
main.pas(109,14) Error: Illegal assignment to for-loop variable "i"
main.pas(132,4) Fatal: Syntax error, ";" expected but "." found
Fatal: Compilation aborted
Error: /usr/bin/ppcx64 returned an error exitcode
Error: Illegal assignment to for-loop variable "i"
is when you are trying to change the value of i while the loop is still working.
since you didn't end; the loop you canno't change the value of i you can use another variable, j for example, unless your first for-loop is over and you forgot the end; key

So I need to sort alphabeticlly structure data in pascal, I improvised a sorting method, but has an error idk how to fix

sorting system and the main problem starts from the "Until" function. I would like to hear someones opinion about what I did wrong, and if there is an easier solution, I will appreciate if u told me about it.
The idea of the problem is: you have n number of people, and u need do introduce each one from the keyboard. Then, I need to sort them alphabeticlly
uses crt;
type Data = record
day : 1..31;
month : 1..12;
year : integer;
end;
Persoana = record
Name : string;
BirthDate : Data;
end;
ListaPersoane = array [1..50] of Persoana;
var x : ListaPersoane;
n:1..50;
i,z,j,l,a,v:integer;
y, k : longint;
aux : string;
begin
writeln('Program created on: 13/10/2020;');
writeln('give the number of people (max. 50):');
readln(n);
for i:=1 to n do begin
ClrScr;
writeln('Insert the name of person ', i, ': '); readln(x[i].Name);
writeln('Insert the date o birth:'); writeln('day:'); readln(x[i].BirthDate.day);
writeln('month:'); readln(x[i].BirthDate.month);
writeln('year:'); readln(x[i].BirthDate.year);
ClrScr;
end;
writeln('_______________________');
for i:=1 to n do begin
writeln(i, ') ', x[i].Name, ' ', x[i].BirthDate.day, '/', x[i].BirthDate.month, '/', x[i].BirthDate.year, ';');
writeln('_______________________');
end;
writeln();
repeat
k:=0;
for i:=1 to n do begin
j:=1;
repeat
Inc(j);
until (x[i].Name[j]>x[i].Name[j]) or (x[i].Name[j]<x[i].Name[j]);
if(x[i].Name[j]>x[i+1].Name[j]) then begin
aux:=x[i].Name;
x[i].Name:=x[i+1].Name;
x[i+1].Name:=aux;
z:=x[i].BirthDate.day;
x[i].BirthDate.day:=x[i+1].BirthDate.day;
x[i+1].BirthDate.day:=z;
l:=x[i].BirthDate.month;
x[i].BirthDate.month:=x[i+1].BirthDate.month;
x[i+1].BirthDate.month:=l;
a:=x[i].BirthDate.year;
x[i].BirthDate.year:=x[i+1].BirthDate.year;
x[i+1].BirthDate.year:=a;
Inc(k);
end;
end;
until (k=0);
writeln('_______________________');
for i:=1 to n do begin
writeln(i, ') ', x[i].Name, ' ', x[i].BirthDate.day, '/', x[i].BirthDate.month, '/', x[i].BirthDate.year, ';');
writeln('_______________________');
end;
writeln();
end.
I would expect that PascalABC can compare two strings and return which one is "smaller" or "bigger", without looping through the characters.
But to draw your attention to (at least) three issues in your sorting code, consider this code of yours:
j := 1;
repeat
Inc(j);
until (x[i].Name[j] > x[i].Name[j]) or (x[i].Name[j] < x[i].Name[j]);
Issue 1:
You initialize j := 1 before the loop. Then before you use j to index a character, you increment it. Thus you never attempt to compare the first character.
Issue 2:
Your repeat loop doesn't take into consideration that names have a limited, and often different length.
Issue 3:
Will either of these conditions, on the until row, ever be true:
(x[i].Name[j] > x[i].Name[j])
or this:
(x[i].Name[j] < x[i].Name[j])
In the subsequent code you correctly compare a character in x[i] with x[i+1]
I leave the correction of these errors for you, yourself, to correct. Consult with your tutor if needed.
You have a repeat .. until which terminates when k=0. You start with k assigned 0, then never change k. Perhaps your repeat is terminating because you don’t change k in the loop.

Read / write different Records data from / to Untyped files in Pascal?

I've a programming project in my college.
Using a File type for storing data is allowed, and I did exactly like this one: pascal-programming
And, here's what I achieved so far:
I tried to write the Records data into Untyped files instead and it worked
I want to override a function with dynamic parameter (e.g: I can switch which Record I want to process, in this case there's 2 different "Records").
Open(var f: File; var data)
data = represent can receive "anything". cmiiw
The reason why I did this, I don't think it's a good idea to recreate the same function over and over, e.g: when using 3 or more different "Records"
I also encountered a problem that the files can't store or backup the actual binary files to the temporary "Records" variable, it always give the 0 values.
go to my github source code
my solution here doesn't provide any generic related procedures (check the last sentences):
program test_untyped;
{ A crude database recording }
uses crt;
type
Temployee = record
name : string[20];
address : string[40];
phone : string[15];
age : byte;
salary : longint;
end;
arr_employee = array[1..100] of Temployee;
var
F : File;
c : char;
// r : Temployee;
r, realR : arr_employee;
s : string;
i, j, n : integer;
procedure fRead;
begin
seek(F, 0);
i := 0;
repeat
clrscr;
inc(i);
writeln('increment: ', i); readln;
writeln('File position : ',filepos(F));
blockRead(F, r[i], sizeOf(Temployee));
writeln('Name = ', r[i].name); { Input data }
writeln('Address = ', r[i].address);
writeln('Phone = ', r[i].phone);
writeln('Age = ', r[i].age);
writeln('Salary = ', r[i].salary);
write('Show data again (Y/N) ?');
repeat
c:=upcase(readkey); { Ask user : Input again or not }
until c in ['Y','N'];
writeln(c);
// realR[i] := r[i]; // backup, to show later
until c='N';
end; // end fRead
procedure fWrite;
begin
seek(F, filesize(F));
repeat
clrscr;
inc(i);
writeln('berapa nilai i: ', i);
writeln('File position : ',filepos(F));
write('Name = '); readln(r[i].name); { Input data }
write('Address = '); readln(r[i].address);
write('Phone = '); readln(r[i].phone);
write('Age = '); readln(r[i].age);
write('Salary = '); readln(r[i].salary);
blockWrite(F, r[i], sizeOf(Temployee)); { Write data to file }
write('Input data again (Y/N) ?');
repeat
c:=upcase(readkey); { Ask user : Input again or not }
until c in ['Y','N'];
writeln(c);
until c='N';
end;
// procedure fDelete;
// var
// nama: string;
// delElement: integer;
// tempR: Temployee;
// begin
// seek(F, 0);
// write('search your data by name: '); readln(nama);
// while not eof(F) do
// begin
// writeln('file position: ', filePos(F));
// blockRead(F, tempR, sizeOf(Temployee));
// if (nama = tempR.name) then
// begin
// delElement := filePos(F);
// end else
// begin
// // seek(F, )
// blockWrite(F, tempR, sizeOf(Temployee));
// end;
// end;
// end; // end fDelete
procedure fDisplay;
begin
writeln('nilai i saat ini: ', i); readln;
for j := 1 to i do
begin
clrscr;
writeln('Name = ', r[j].name); { Input data }
writeln('Address = ', r[j].address);
writeln('Phone = ', r[j].phone);
writeln('Age = ', r[j].age);
writeln('Salary = ', r[j].salary);
readln;
end;
end;
begin
clrscr;
// write('Input file name to record databases : '); readln(s);
s := 'coba1.dat';
assign(F,s); { Associate it }
{$I-}
reset(F, sizeOf(Temployee)); { First, open it }
{$I+}
n:=IOResult;
if n<>0 then { If it's doesn't exist then }
begin
{$I-}
rewrite(F, sizeOf(Temployee)); { Create it }
{$I+}
n:=IOResult;
if n<>0 then
begin
writeln('Error creating file !'); halt;
end;
end
else
begin { If it exists then }
n:=filesize(F); { Calculate total record }
// seek(F,n); { Move file pointer PAST the last record }
end;
fileMode := 2;
reset(F, sizeOf(Temployee));
fRead;
fWrite;
// fDelete;
fDisplay;
close(F);
end.
I'm wondering is the Pascal can be any good to use a generic programming? at least for this semester using Pascal in my college XD
Thank you and Best Regards,
EDIT:
Pascal still doesn't support Generic Programming 'till the day I posted this question. So sad, really.
You might wanna consider read this references instead.
I don't understand the main issue here, but would suggest using a typed file instead of an untyped one.
An untyped file is much harder to maintain, and provides (in my eyes) no benefits.
Consider the code:
type
Temployee = record
name : string[20];
address : string[40];
phone : string[15];
age : byte;
salary : longint;
end;
VAR
fEmployee : File Of Temployee;
Employees : ARRAY[0..100] Of Temployee;
Employee : Temployee;
PROCEDURE OpenEmployeeFile(CONST TheFileName:AnsiString);
BEGIN
AssignFile(fEmployee,TheFileName);
IF FileExistsUTF8(TheFileName) { *Converted from FileExists* }
THEN Reset(fEmployee)
ELSE Rewrite(fEmployee);
END;
PROCEDURE CloseEmployeeFile;
BEGIN
Close(fEmployee);
END;
FUNCTION ReadEmployee(Position:WORD): Temployee;
BEGIN
Seek(fEmployee,Position);
Read(fEmployee,Result);
END;
PROCEDURE WriteEmployee(CONST Employee:Temployee; Position:WORD);
BEGIN
Seek(fEmployee,Position);
Write(fEmployee,Employee);
END;
Error handling not implemented.
Code samples as a guideline, not complete.
It provides a basic skeleton for opening and closing the employee-file, as well as reading and writing at specific positions (specific records) in the file.
Open file.
Write all the records you want.
Close file.
Or.
Open file.
Read all the records you want.
Close file.

how to get a variable out of a procedure in the right way in PASCAL?

I'm following an internet course on the basics of programming. After making a diagram I convert it to code, right now this is PASCAL language.
I'm having a problem with procedures and can't find an answer, nor in the course, nor with some google-ing.
I want to get a variavble back form a procedure. Right now iIhave a working piece of code but I think this is not the good way of working. Here's an extract of the code:
program WELKEWAGEN;
// declare your variables here
var T, N, KM, vari, prijsDW, prijsBW, jrenGEBR, taksDW, taksBW, prijsB, verbrBW, prijsD, verbrDW : real;
procedure OPHALEN(para : string);
begin
repeat
writeln('geef de ', para , ' op');
readln(vari);
until (vari > 0);
end;
begin
//this is the main program but there is more code ofcourse
OPHALEN('prijs benzinewagen');
prijsBW := vari;
//...
end.
Now the internet course says I should program it like this:
begin
//...
prijsBW := OPHALEN('prijs benzinewagen');
//...
end.
But this is not working.
I get following errors:
WELKEWAGEN.pas(24,14) Error: Incompatible types: got "untyped" expected "Real"
WELKEWAGEN.pas(50) Fatal: There were 1 errors compiling module, stopping
pas(24,14) is this line: prijsBW := OPHALEN('prijs benzinewagen');
Procedures don't return values, so the syntax
prijsBW := OPHALEN('prijs benzinewagen');
is invalid.
If you want to return a value, you need to define a function instead:
function OPHALEN(para : string): Real;
var
Res: Real;
begin
Res := 0;
repeat
writeln('geef de ', para , ' op');
readln(Res);
until (Res > 0);
OPHALEN := Res;
end;
Note that the (bad) global variables you're using mean you don't have to return anything at all, because a procedure can access and change that global variable directly (but you have no way of knowing when the procedure is finished):
procedure OPHALEN(para : string);
begin
vari := 0;
repeat
writeln('geef de ', para , ' op');
readln(vari);
until (vari > 0);
end;
Modern Pascal dialects (such as Delphi and FreePascal) allow a cleaner syntax for the return value of functions by using an automatically declared function result variable of the proper type for you, named Result (because that's what it is - the result of the function):
function OPHALEN(para : string): Real;
begin
Result := 0;
repeat
writeln('geef de ', para , ' op');
readln(Result);
until (Result > 0);
end;
If you need to return multiple values, you can use var parameters, which allow them to be changed inside the function.
procedure OPHALEN(para: string; var RetVal: Real);
begin
RetVal := 0;
repeat
writeln('geef de ', para , ' op');
readln(RetVal);
until (RetVal > 0);
end;
Your original code (and the examples I've provided above) all fail to allow the user to cancel, BTW. There should be some way to exit the loop for the user; otherwise, your code just endlessly loops, writing para to the screen and then waiting for input. This has a tendency to annoy users.

Pascal comparison error

I have a problem with my very simple Pascal code. (I just started to learn Pascal.)
So it's about an age comparison code then rest can be seen through the code.
program Test;
uses crt;
var
age : real;
Begin
writeln('Enter your age: ');
readln(age);
if age>18 then
if age<100 then
Begin
clrscr;
textcolor(lightgreen);
writeln('Access Granted');
end
else
if age<18 then
Begin
clrscr;
textcolor(lightred);
writeln('ACCESS DENIED');
writeln('Reason:You are way to young');
end
else
Begin
clrscr;
textcolor(lightred);
writeln('ACCESS DENIED');
writeln('Reason:You are way to old');
end;
readln;
end.
When I enter a value below 18 as the age, I expect the program to respond:
ACCESS DENIED
Reason:You are way to young
but I don't get any output. Why?
Sometimes text indentation helps you to see the issue. Here's your code with indentation added:
program Test;
uses crt;
var
age : real;
Begin
writeln('Enter your age: ');
readln(age);
if age>18 then
if age<100 then
Begin
clrscr;
textcolor(lightgreen);
writeln('Access Granted');
end
else
if age<18 then
Begin
clrscr;
textcolor(lightred);
writeln('ACCESS DENIED');
writeln('Reason:You are way to young');
end
else
Begin
clrscr;
textcolor(lightred);
writeln('ACCESS DENIED');
writeln('Reason:You are way to old');
end;
readln;
end.
And to make the implemented logic more obvious, I will now represent the nested ifs without the code that they execute:
if age>18 then
if age<100 then
... // Access Granted
else
if age<18 then
... // You are way too young
else
... // You are way too old
;
It is easy to see now that the branch marked as You are way too young is never reached. It is supposed to be executed when age is less than 18, but that if statement is nested into another if which will call it only when age is greater than 18. So, age should first qualify as greater than 18, then less than 18 in order for that branch to execute – you can see now why you do not get the expected result!
The intended logic could possibly be implemented this way:
if age>18 then
if age<100 then
... // Access Granted
else // i.e. "if age >= 100"
... // You are way too old
else // now this "else" belongs to the first "if"
... // You are way too young
;
I believe you should be able to fill in the missing code blocks correctly.
Just one last note: you might want to change age>18 to age>=18, so that 18 proper does not qualify as "too young".

Resources