How to get the number of items in an enumerated type in Pascal? - pascal

program
Enumeration;
uses
crt;
type
beverage = (coffee, tea, milk, water, coke, limejuice);
var
drink:beverage;
begin`enter code here`
writeln('Which drink do you want?');
writeln('You have ', *** , ' choices');
readkey;
end.
What should i use in '***' here to get the number of elements in the beverage enumerated type in output ?
I used sizeof(), but it gives the byte value of type.
I'm using lazarus, fyi.

Succ(Ord(High(beverage))) should give you the number of defined beverages.

You can use ORD and HIGH-LOW function:
ord(high(beverage)) - ord(low(beverage)) + 1
codes:
program
Enumeration;
uses
crt;
type
beverage = (coffee, tea, milk, water, coke, limejuice);
var
drink:beverage;
begin`enter code here`
writeln('Which drink do you want?');
writeln('You have ', ord(high(beverage))-ord(low(beverage))+1 , ' choices');
readkey;
end.
result:
Which drink do you want?
You have 6 choices

Related

What can make the output of a simple ada program indent, when not told to?

I am currently doing the Ada tutorial from learn.adacore.com, and I am now at the second example: reading and outputting an integer. Since copy-pasting is for people who don't want to learn the syntax, I manually typed out most of the code (Some of it was generated by gnat-gps, but I'm now using vim).
I compiled and ran the program, and surprisingly, the second line of output is indented by roughly one tab. Why?
Here's the code:
With Ada.Text_IO;
Use Ada.Text_IO;
With Ada.Integer_Text_IO;
use Ada.Integer_Text_IO;
procedure Main is
N : Integer;
begin
-- Insert code here.
Put("Enter an integer value: ");
Get(N);
if N>0 then
Put (N);
Put_Line(" is a positive number");
end if;
end Main;
(how do I get syntax highlighting?)
Here is a sample of the output (the first 1 being input):
Enter an integer value: 1
1 is a positive number
The Put procedure from Ada.Integer_Text_IO uses a default field width padded with spaces.
The specification for that procedure is defined in the Ada Language Reference Manual as:
procedure Put(Item : in Num;
Width : in Field := Default_Width;
Base : in Number_Base := Default_Base);
The Width and Base parameters are given default values. Your call to Put only supplied a value for the formal parameter Item. To eliminate the left padding simply specify a desired width. I suggest you use Ada named notation for the call as in
Put(Item => N, Width => 1);

Why does syntax error appear after running code?

presently learning how to code in pascal and vba. Assisting my daughter who is preparing for examinations next year. I am stuck on a problem concerning her present assignment. After running the code the following errors were received:
main.pas(1,2) Fatal: Syntax error, "BEGIN" expected but "identifier N" found
Fatal: Compilation aborted
Tried fixing the code, but as i said I have just started learning to code.
n: integer; (*n is ID number for each candidate*)
DV: integer; (*DV is the number of district votes available*)
VR: integer; (*VR is the number of votes received by the candidate in
the district*)
x: integer;
y: integer;
Divide: integer;
found: Boolean;
n: array[1..10] of integer; (*n is an array of 10 integers*)
Names: array[1…10] of string = (‘Richards’, ‘Gumbs’, ‘Carty’,
‘Fleming’, ‘Jones’, ‘Amorowat’, ‘De la cruz’, ‘Walker’,
‘Brooks’, ‘Baker’);
DV: array[1…10] of integer = (‘200’, ‘900’, ‘700’, ‘100’, ‘80’, ‘15’,
‘6, ‘20’, ‘50’, ‘1’);
VR: array[1…10] of integer = (‘50’, ‘700’, ‘600’, ‘20’, ‘30’, ‘2’,
‘6, ‘3’, ‘30’, ‘2’);
For x := 1 to 10 do
Begin
Repeat
Found:=false;
writeln('Enter Candidate ID Number: ’);
readln(n);
For y:= 1 to 10 do
if n = n[y] then
Found = true;
writeln(‘Name of Candidate is’ Names: array[1] ‘.’);
readln;
writeln(‘Number of votes available in the District is’
DV: array[1] ‘.’);
readln;
writeln(‘Number of votes received by the Candidate in the
District is’ VR: array[1] ‘.’);
readln;
Endif;
For y:= 1 to 10 do
if n = n[y] then
Divide:= (DV: array[1] DIV VR: array[1]);
Result:= Divide;
writeln(‘The percentage of votes received by’ Names:
array[1] ‘is’ Result ‘.’);
readln;
if Result:>= 0.20 then
writeln(‘The candidate,’ Names: array[1] ‘is to receive a
refund.’);
readln;
Elseif
writeln(‘The candidate,’ Names: array[1] ‘will not receive
a refund.’);
readln;
Endif;
Endif;
End;
The expected result is to choose a candidate by his ID number which would lead to his name, the number of vote available in a district and the number of votes the candidate obtained being displayed. it would then result in a calculation between the two vote counts (division) and if the percentage is greater than 20% he would receive a refund, if less than 20% he would not receive a refund. either result should be displayed.
I'm afraid that you q, as it currently stands, isn't really suited to SO
because SO is really about specific (single) programming problems, not
incrementally debugging source code (see Sertac's comment), nor providing
online tutorials, which I think you probably need at this point. And I feel
rather uncomfortable about posting this as an answer, because it isn't one
in the normal SO sense. However it seems to me that you could use a few pointers:
Unless you absolutely have to use the online compiler, download
and use a free online one like Free Pascal, which is well supported, uses
standard Pascal syntax, and I'm sure there are basic first-time tutorials
available. See here to download Lazarus, which is an excellent IDE for Free Pascal (which is included
in the install) and here for an introductory tutorial.
Secondly, there are structural and syntactic elements of your source-code
which are definitely not standard Pascal, in particular endif and elseif.
Another example is that in standard Pascal, you have to surround a string (like your
Richards, etc) with single-quotes ', not precede the string by a back-quote. This is very possibly the cause of your "illegal character" error
For a decent Free Pascal introductory
tutorial see here and this youtube tutorial, both found by googling
"free pascal" introductory tutorial.
Fourthly, your online compiler ought to be complaining about the endif abd elseifs, the incorrectly string formatting and the fact that several of your variables are duplicated (DV and VR used as the names of an integer variable and an array, for example as in Pascal, identifiers within the same 'scope' need to have unique names (the fact that I should explain what 'scope' means is a sign that what the q needs is a tutorial).

Not sure when to use ':' or '='

I am getting this error when compiling my code: "cars2.pp(3,8) Fatal: Syntax error, "=" expected but ":" found"
Here's my code:
program vehInfo;
type
wheels: array [1 .. 6] of integer;
purchaseYear: array [1919 .. 2051] of integer;
style = (sports, SUV, minivan, motorcycle, sedan, exotic);
pwrSrc = (electric, hybrid, gas, diesel);
vehicle = record
wheel : wheels;
buyDate : purchaseYear;
styles : style;
source : pwrSrc;
end;
var
myVehicle: vehicle;
listOfCars: file of vehicle;
begin
assign(listOfCars, 'hwkcarsfile.txt');
reset(listOfCars);
read(listOfCars, myVehicle);
writeln('wheel type: ' , myVehicle.wheel);
writeln('year purchased: ' , myVehicle.buyDate);
writeln('style: ' , myVehicle.styles);
writeln('power source: ' , myVehicle.source)
close(listOfCars);
end.
I am new to Pascal, any help would be appreciated, thank you.
It is quite simple: type uses =, while variable declarations use :.
So:
type
wheels = 1..6; // not an array, but a subrange type!
purchaseYear = 1919..2051; // not an array, but a subrange type!
style = (sports, SUV, minivan, motorcycle, sedan, exotic);
pwrSrc = (electric, hybrid, gas, diesel);
vehicle = record
wheel: wheels; { a field of a record is a variable }
buyDate: purchaseYear;
styles: style;
source: pwrSrc;
end;
...
var
myVehicle: vehicle;
listOfCars: file of vehicle;
Subrange types are ordinal types (in this case, both are integers), but within the given range. Any value outside the range is illegal. You don't want to have arrays of numbers, you only want the number of wheels and the year (a number too) the vehicle was purchased. You don't need 133 different dates, do you?

why am i getting 22 / 3 itprog~1.pas Fatal: Syntax error, ; expected but ELSE found

PROGRAM approvedapplicants(input,output);
uses crt;
var
applcntname,housingcomm,clarendon_court,providence_gardens,
sangre_grande_villas:string;
slry,spcslry:integer;
c_qual_sal,s_qual_sal,p_qual_sal,qualifying_salary:integer;
BEGIN
writeln('enter applicant name, salary, spouce salary');
readln(applcntname,slry,spcslry);
writeln('enter housing community');
readln(housingcomm);
BEGIN
qualifying_salary:=0;
IF(housingcomm=clarendon_court)
then
qualifying_salary:=$12500;
writeln('you have selected clarendon court!');
readln(c_qual_sal) ;
end if ;
else if(housingcomm=sangre_grande_villas)then
qualifying_salary:=$9500;
writeln('you have selected sangre grande villas!');
readln(s_qual_sal);
end if ;
else(housingcomm=providence_gardens)then;
qualifying_salary:=$7500;
writeln('you have selected providence gardens!');
readln(p_qual_sal);
end if;
END.
Ordinarily, on SO, we don't post answers to homework/coursework, but your code is so far wide of the mark that I think it's ok to make an exception in this case.
Try compiling and running this program, which I think does pretty much what I think you are intending, then I'll explain a few things about it:
program approvedapplicants(input,output);
uses crt;
var
ApplicantName,
HousingCommunity,
ClarendonCourt,
ProvidenceGardens,
SangreGrandVillas :string;
Salary,
SpouseSalary,
QualifyingSalary : Integer;
CQualSal,
PQualSal,
SQualSal : Integer;
slry,spcslry:integer;
begin
ClarendonCourt := 'Clarendon Court';
ProvidenceGardens := 'Providence Gardens';
SangreGrandVillas := 'Sangre Grand Villas';
QualifyingSalary := 0;
writeln('enter applicant name');
readln(ApplicantName);
writeln('enter salary');
readln(Salary);
writeln('enter spouse salary');
readln(SpouseSalary);
writeln('enter housing community');
readln(HousingCommunity);
if (HousingCommunity = ClarendonCourt) then begin
QualifyingSalary := $12500;
writeln('you have selected clarendon court!');
readln(CQualSal);
end
else
if(HousingCommunity = SangreGrandVillas)then begin
QualifyingSalary := $9500;
writeln('you have selected sangre grande villas!');
readln(SQualSal);
end
else
if HousingCommunity = ProvidenceGardens then begin
QualifyingSalary :=$7500;
writeln('you have selected providence gardens!');
readln(CQualSal);
end;
end.
Firstly, notice how much easier it is to read and follow its logic. This is mainly
because of
The use of a layout (including indented blocks) which reflects the logical
structure of the code.
The use of consistent, lower case for keywords like program, begin, end, etc.
Keywords are usually the least interesting contents of source code, and it is distracting
to have them SHOUTing at you.
The avoidance of arbitrarily dropping characters from variable names (like the "i"
and second "a" of "applicant". In the days of interpreted code running on slow machines there was
argubably some justification for this, but not any more imo. Likewise, the avoidance
of underscores in variable names - admittedly this is more of a personal preference, but
why have you used them everywhere except the applicant's name?
Secondly, you still have quite a bit of work to do.
Having 3 different variables for the salary (?) numbers you prompt the user
for, one for each of the 3 communities, is probably a bad idea unless you will
subsequently want to work with all 3 figures at the same time. Also, you haven't provided text prompts to tell the user what information to enter for the readln(c_qual_sal) etc statements. It wasn't obvious to me what you intend, so I have not tried to guess.
The way you echo the user's choice of community is just creating you a maintenance
headache (what if you want to add more communities later?). It would be better
to have a variable which you set to whichever of the community names matches
what the user has entered.
You have 3 statements to execute for each community, which are duplicated for
each community. The only one you actually need is the QualifyingSalary one -
the others can execute regardless of the inputted community.

How can i know if a variable is a number or a letter with Pascal?

I'm trying to make a (very) little code to determine whether a given variable x is a number or a letter. It has to be done by hand without things like type(x) -assuming there is such thing in Pascal-.
My plan was to verify that x is not a number one by one, then i wrote this:
(*let ischar be a boolean and let x be a letter or a number.*)
for i:=0 to 9 do
begin
if (x=i) then
ischar = false;
end;
if ischar then
write('x is a number!');
else
write('x is a letter');
I was hoping that the test "x=i" would return false if x is a letter, but here i don't even get to compile because of the following error: "Got char, expected long int". It seems that i can't compare x and i, i knew that but i tought that under that circumstances if would return false.
Is there another way to do this 'by hand'?
It's generally not possible to directly compare variables of different types. The compilation error suggests x is declared as a char, while i is a longint.
The available options may depend on what Pascal compiler you use.
My only experience is with the Borland (later CodeGear and Embarcadero) products "Turbo Pascal" and "Delphi".
Those compilers have the ord function which gives the numeric value of an ordinal type.
In the case of a char, the ord function should give you the ASCII code of the character, which you can test to see if it's in the code range of '0'..'9'.
You don't need the for loop. This should work:
if (ord(x)<48) or (ord(x)>57) then ischar:=true else ischar:=false;
Edit: Here's the Free Pascal documentation for the ord function:
http://www.freepascal.org/docs-html/rtl/system/ord.html

Resources