I am a beginner and using pascal. I don't know how to code the output. I am expecting the output to be the result of the function - output

I am a beginner and using pascal and i am trying this problem that i attach. What should i do next? I am trying to make this program work by showing the "ayam" Function. But i don't know how to code the rest.
function ayam(a, b:integer) :
integer;
var
m: integer;
begin
readln(a) ;
readln(b) ;
readln(m) ;
begin
if (b=0) then
ayam:= 1 else
ayam:= a * ayam(a, b-1) mod m;
end;
writeln(ayam);
end;

The first thing I should say is that when a question is to do with coursework, as is obviously the case here, there is an unwritten convention that we do not write an answer which simply does your programming task for you. So in the following, I have not commented on whether the code inside your ayam function actually correctly implements what is required - that is for you to do.
Secondly, you did not say which Pascal implementation you are using. I have written the code of this answer in Lazarus, the IDE for FreePascal (aka FPC), which is the best of the freeware Pascal implementations currently available.
The first thing to do with your code is to re-format it the way it should be formatted,
using indentation of statements to reflect the structure of the steps you are
trying to code. Basically, your eye should be able to follow the code structure
as easily as possible. This gives something like this:
function ayam(a, b:integer) : integer;
var
m: integer;
begin
readln(a) ;
readln(b) ;
readln(m) ;
begin
if (b=0) then
ayam:= 1
else
ayam:= a * ayam(a, b-1) mod m;
end;
writeln(ayam);
end;
With that change made, it is pretty obvious that there is something wrong with
the logic of your code, because a and b are declared as input variables to
the ayam function but your code actually reads in their values via the
readln statements inside the function. This is what made me think that you think
you have done all that's necessary to write your program. In fact, you have not. What you are missing
is some code which sets up the input parameters a and b (and m, see below) in some way and then
invokes your ayam function to calculate its value and then does something with
the result. At the moment, your code simply defines ayam but takes no steps
to use it. So, to get your ayam function to do anything, you need to write a complete
Pascal program that uses it. Something like this:
program ayamprogram;
{ the following declares some variables for the program to use }
var
varA,
varB,
varM,
varResult : Integer;
{ next, we define the ayam function }
function ayam(a, b, m:integer) : integer;
begin
begin
if (b=0) then
ayam:= 1
else
ayam:= a * ayam(a, b-1, m) mod m;
end;
end;
{ now we write the code of the program, which reads in the values to be
used by ayam, then invokes ("calls") ayam to calculate its value and
assign its value to the varResult variable and then outputs the calculated
result using the writeln statement
}
begin
{ this is the code of the program }
readln(varA);
readln(varB);
readln(varM);
varResult := ayam(varA, varB, varM);
writeln('function ayam evaluates to ', varResult);
readln; { this causes the program to pause so you can see the result of the writeln statement }
end. { end of program }
Note that I have used different variable names for the variables which are supplied to ayam, varA, varB, varM, from the variable names used inside ayam to avoid confusion between them.
Note also that as it is bad practice to read user input inside an executing function, the value to be used for M is read in before ayam is called and is supplied to ayam as a third parameter.
A point you need to consider regarding the expression
ayam:= a * ayam(a, b-1, m) mod m
is whether the mod m should operate on the value of ayam(a, b-1, m) or on the entire expression including the a * as well; if so, parentheses can enforce the evaluation order you need, by writing
ayam:= (a * ayam(a, b-1, m)) mod m

Related

How to define variable in function Pascal

function F(x:real) : real;
begin
F := a*power(x,2);
end;
Guys, I need help.I am using Lazarus with form and I want to make a function with variable 'a' there. Variable a is an input just like a:= StrToInt(Edit1.Text);
Then how to define a there?
You should make a be an argument to the function.
function F(a: Integer; x: real): real;
begin
F := a*power(x,2);
end;
Further, using power for integer exponents is expensive and not terribly accurate. Use direct multiplication, in this case you can make use of sqr.
function F(a: Integer; x: real): real;
begin
F := a*sqr(x);
end;
Now, when you call the function you can use StrToInt(Edit1.Text) to obtain the value of a, which you pass on to the function. Or indeed you can use some other means to obtain a.
All of this is to avoid your arithmetic functions requiring knowledge of your UI.

How to get this function to work in Oracle 11G - PL/SQL

I'm new with PL/SQL I have a assignment where I need to make a function. The assignment is as follows:
> "Create a function 'afdeling_van:'
> - this function accepts a medewerkernummer(employee number) as argument
> - give the afdelingnummer(department number) from the medewerkernummer(employee number) back"
So I need to create a function with a parameter that returns a number. After that I probably need to add some code to make it return a medewerker(employee) number back.
I got pretty stuck with this one as I am really new to PL/SQL. What I do have at the moment is this:
declare
procedure afdeling_van(p_persoon in medewerkers.mnr%type)--table name with column name
is
begin
select med.mnr
from medewerkers med;
where mnr = p_persoon;
end afdeling_van;
begin
afdeling_van(10);
end;
It's not working for me. I have tried different solutions. But as I lack experience and I cannot find the solution or information that I need on the web. I am trying it to ask here
one other thing. I think it's similair to my problem. In the previous assignment I made a procedure instead of a function. The procedure is as follows:
declare
v_medewerker varchar2(50) := ontsla_med();
procedure ontsla_med(p_medewerkers in medewerkers.naam%type)
is
begin
delete from medewerkers
where naam = p_medewerkers;
end ontsla_med;
begin
ontsla_med('');
dbms_output.put_line('Medewerker: ' || v_medewerker || 'verwijdert uit medewerker, inschrijven en uitvoeringen bestand.' );
exception
when no_data_found then
dbms_output.put_line('Medewerker bestaat niet/ is al verwijderd.');
end;
/
this works except for the last dbms_output.put_line. If I remove the output line, then it will work and with the output line, it won't.
I hope my question is not too vague.
Thanks in advance.
You need to create a function instead of a procedure, and you've got a semi-colon in the wrong place. Try something like:
declare
nReturned_value MEDEWERKERS.AFDELINGNUMMER%TYPE;
FUNCTION afdeling_van(p_persoon in medewerkers.mnr%type) --table name with column name
RETURN MEDEWERKERS.AFDELINGNUMMER%TYPE
is
nAFDELINGNUMMER MEDEWERKERS.AFDELINGNUMMER%TYPE;
begin
select med.AFDELINGNUMMER
INTO nAFDELINGNUMMER
from medewerkers med
where mnr = p_persoon;
RETURN nAFDELINGNUMMER ;
end afdeling_van;
begin
nReturned_value := afdeling_van(10);
DBMS_OUTPUT.PUT_LINE('nReturned_value = ' || nReturned_value);
end;
Edit
In your second example, I don't believe that the line v_medewerker varchar2(50) := ontsla_med(); will compile. ontsla_med is a procedure rather than a function, and because procedures don't return anything they can't be used in an assignment statement.
However, v_medewerker is only used in the DBMS_OUTPUT line which you say causes a problem - thus, it may be that the compiler is eliminating the variable because it's not used if the DBMS_OUTPUT line is removed, thus eliminating the problem. Try changing the declaration to v_medwerker varchar2(50) := 'Hello'; and see if that helps.

VHDL, using functions in for generate statement

VHDL, using functions in for generate statement
I have a component that should be instantiated about 8000 times, I used for-generate statement with the help of some constant values for reducing amount of code, but I had to declare a function for parametrization of component connections.
My function looks like this:
function dim1_calc (
cmp_index : integer;
prt_index : integer
) return integer is
variable updw : integer := 0;
variable shft_v : integer := 0;
variable result : integer := 0;
begin
if (cmp_index < max_up) then
updw := 1;
else
updw := 2;
end if;
case prt_index is
when 1 =>
shft_v := cnst_rom(updw)(1) + (i-1);
when 2 =>
shft_v := cnst_rom(updw)(2) + (i);
--
--
--
when 32 =>
shft_v := cnst_rom(updw)(32) + (i);
when others =>
shft_v := 0;
end case;
if (updw = 1) then
if (shft_v = min_up & ((prt_index mod 2) = 0)) then
result <= max_up;
elsif (shft_v = max_up & ((prt_index mod 2) = 1)) then
result <= min_up;
elsif (shft_v < max_up) then
result <= shft_v;
else
result <= shft_v - max_up;
end if;
else
--something like first condition statements...
--
--
end if;
return result;
end function;
and part of my code that uses this function plus some related part looks like this:
--these type definitions are in my package
type nx_bits_at is array (natural range <>) of std_logic_vector (bits-1 downto 0);
type mxn_bits_at is array (natural range <>) of nx_bits_at;
--
--
--
component pn_cmpn is
port(
clk : in std_logic;
bn_to_pn : in nx_bits_at(1 to row_wght);
pn_to_bn : out nx_bits_at(1 to row_wght)
);
end component;
--
--
--
signal v2c : mxn_bits_at(1 to bn_num)(1 to col_wght);
signal c2v : mxn_bits_at(1 to pn_num)(1 to row_wght);
--
--
--
gen_pn : for i in (1 to pn_num) generate
ins_pn : pn_cmpn port map (
clk => clk,
bn_to_pn(1) => b2p (dim1_calc(i, 1)) (dim2_calc(i, 1)),
bn_to_pn(2) => b2p (dim1_calc(i, 2)) (dim2_calc(i, 2)),
.
.
.
bn_to_pn(32) => b2p (dim1_calc(i, 32)) (dim2_calc(i, 32)),
pn_to_bn => p2b (i)
);
end generate;
I know that using too many sequential statements together is not appropriate in general, and I'm avoiding them as much as possible, but in this case I assumed that this function won't synthesize into some real hardware, and synthesizer just calculates the output value and will put it in corresponding instantiations of that component. Am I right? or this way of coding leads to extra hardware compared to just 8000 instantiations.
PS1: Initially I used "0 to..." for defining ranges of the 2nd and 3rd dimension of my arrays, but because of confusion that were made in dimension calculation function based on for-generate statement parameter, I replaced them with "1 to...". Is that an OK! coding style or should I avoid it?
PS2: Is there a way that port mapping part in above code combines into something like this:
(I know this is strongly wrong, it's just a clarification of what I want)
gen_pn : for i in (1 to pn_num) generate
ins_pn : pn_cmpn port map (
clk => clk,
gen_bn_to_pn : for j in (1 to 32) generate
bn_to_pn(j) => b2p (dim1_calc(i, j)) (dim2_calc(i, j)),
end generate;
pn_to_bn => p2b (i)
);
end generate;
Let me give another example
Assume that I have a component instantiation like this:
ins_test : test_comp port map (
clk => clk,
test_port(1) => test_sig(2)
test_port(2) => test_sig(3)
test_port(3) => test_sig(4)
);
Is there a way that I can use for generate here? something like:
ins_test : test_comp port map (
clk => clk,
gen_pn : for i in (1 to 3) generate
test_port(i) => test_sig(i+1)
end generate;
);
PS3: Is it possible to call a function inside another function in VHDL?
Functions are usable this way. If you encounter problems, I am sure they will regard details in the design or design tools, rather than the basic approach.
One potential issue is that the function refers to some external "things" such as max_up, i, cnst_rom whose declarations are not part of the function nor parameters to it. This makes it an "impure function" which - because it refers to external state or even modifies it - has restrictions on calling it (because the external state may change, results may depend on order of evaluation etc).
If you can make it pure, do so. I have a feeling that max_up, cnst_rom are constants : if they aren't used elsewhere, declare them local to the function. And i probably ought to be a parameter.
If this is not possible, make the external declarations constants, and preferably wrap them and the function together in a package.
This will just generate the values you need in a small, comprehensible, maintainable form, and not an infinite volume of hardware. I have used a complex nest of functions performing floating point arithmetic then fiddly range reduction and integer rounding to initialise a lookup table, so fundamentally the approach does work.
Potential pitfall:
Some design tools have trouble with perfectly valid VHDL, if its use is slightly unorthodox. Synplicity cannot synthesise some forms of function (which DO generate hardware) though has no trouble with the equivalent procedure returning the result through an OUT parameter!. XST is considerably better.
XST parsing my lookup table init has an absurd slowdown, quadratic in the number of function calls. But only if you are using the old VHDL parser (the default for Spartan-3). Spartan-6 uses the new parser and works fine ( under a second instead of half an hour!) as do Modelsim and Isim. (haven't tried Synplicity on that project)
Some tools object to unorthodox things in port maps : you may get away with function calls there; or you may have to workaround tool bugs by initialising constants with the calls, and using those constants in the port maps.
And your supplementary questions:
PS1) The correct coding style for an array range is ... whatever makes your intent clear.
If you find yourself mentally offsetting by 1 and getting confused or even making errors, STOP! and improve the design.
Some good array indexing styles:
type colour is (red, green, blue);
subtype brightness is natural range 0 to 255;
hue : array (colour) of brightness;
gamma : array (brightness) of brightness;
-- here 0 is a legitimate value
channel : array (1 to 99) of frequency;
PS2) I think you're asking if you can nest generate statements. Yes.
Details may be awkward and difficult, but yes.
PS3) Yes of course! You can even declare functions local to others; eliminating the possibility they will be accidentally called somewhere they make no sense. They (impure functions) can access the execution scope of the outer function (or process), simplifying parameter lists.
Q1 - in this case I assumed that this function won't synthesize into some ...
It depends on which synthesizer you're using. See this relevant question and comments below.
Q2 - PS1: Initially I used "0 to..." for defining ranges of the ...
Surely it's OK. And please allow we to post a suggestion on coding style here. (from this book)
When defining the loop parameter specification, either use a type (or subtype) definition, or use predefined object attributes (e.g., PredefinedObject'range, PredefinedObject'length - 1 downto 0). Avoid using discrete range (e.g., 1 to 4).
This rule makes the code more reusable and flexible for maintenance.
Q3 - PS2: Is there a way that port mapping part in above code combines into ...
I think this is why you asked the 4th question. So refer to the next answer:).
Q4 - Is it possible to call a function inside another function in VHDL?
Though I can't find some official reference to this, the answer is yes.
PS: Coding rules are defined by the synthesizer tools. So the best way to find an answer is to try it yourself.

Datatype Verification

I'm just starting out with Object Pascal for my computer studies so this is probably an easy question for many of you here. I'm trying to build a verification system for a Sum and Average Calculator so that answers which are not integers cannot be accepted but also don't crash the software. I've been trying for hours to get a solution for this and whilst it's in its current state, if I input an integer it would interpret it as a noninteger, whilst if I input a noninteger the program just crashes. Is there anyway around this?
The coding currently looks like this:
Program SumAverageCalculator;
{$APPTYPE CONSOLE}
uses
SysUtils;
Const
NumberOfIntegers = 3;
Var
NumberOne, NumberTwo, NumberThree: integer;
Sum: integer;
Average: real;
Begin
Writeln ('=======================================');
Write ('What is your first number? '); readln(NumberOne);
If NumberOne-sqr(0) <> 1 then
Begin
Write ('Please write an integer only. What is your first number? '); readln(NumberOne);
End
Else
Begin
Write ('Great, that is an Integer! ');
End;
Write ('And the second number? '); readln(NumberTwo);
If NumberTwo-sqr(0) <> 1 then
Begin
Write ('Please write an integer only. What is your second number? '); readln(NumberOne);
End
Else
Begin
Write ('Great, that is an Integer! ');
End;
Write ('And the third number? '); readln(NumberThree);
If NumberThree-sqr(0) <> 1 then
Begin
Write ('Please write an integer only. What is your third number? '); readln(NumberOne);
End
Else
Begin
Write ('Great, that is an Integer! ');
End;
Sum := NumberOne + NumberTwo + NumberThree;
Average := Sum/NumberOfIntegers;
Writeln;
Writeln ('=======================================');
Writeln ('The number of given integers was ', NumberOfIntegers);
Writeln ('Your first number was ', NumberOne);
Writeln ('Your second number was ', NumberTwo);
Writeln ('Your third number was ', NumberThree);
Writeln ('=======================================');
Writeln ('The Sum of your numbers is ', Sum);
Writeln ('The Average of your numbers is ', Average: 1:2);
Writeln ('=======================================');
Readln;
End.
Thank you for any help given. :)
This is really because you passed an integer variable to the readln call, and it really wants to put an integer there. If it can't (the input is not an integer), it will crash. A solution is to first read the input in the most general form possible, that is, a string, check that it is an integer, and then convert it to one.
Of course, you don't have to do all that yourself. The sysutils unit has some helpful functions, and among them the TryStrToInt function, which does what it says: it will try to convert a string input to an integer, and will let you (the developer) know if it fails instead of crashing and burning.
uses
SysUtils;
Var
Input: String;
IsInteger: Boolean;
Value: Integer;
begin
Write('Enter an integer: ');
ReadLn(Input); // will work, user input can always be represented by a string
IsInteger := TryStrToInt(Input, Value);
if IsInteger then
begin
// Do stuff with "Value" which contains the input integer
end
else
begin
WriteLn('Sorry, that''s not an integer.');
end;
end.
Of course, if you're going to be doing this often, it may make sense to implement a helper function that acts like readln but does the checking itself and prints out an error without crashing (perhaps the program could keep asking for the integer until the user complies, or perhaps it should gracefully terminate). For instance, some of the code above could be wrapped up in a utility function readint.
Once you come across exceptions, you'll find a more general way to handle failures in your program and respond to them properly to avoid your program crashing on the slightest user error, however at this point this is probably what you are looking for.
If you are wondering what the out thing means in the TryStrToInt function, it's similar to var, but it basically means "I am going to be filling out this value, but I won't try to read it" (a write-only parameter) unlike var which means "I am going to fill out this value, but I might try to read it before" (a read-write parameter). So an out parameter need not be initialized before being used (so in a way, an out parameter is a "second return value", which makes sense in this case since the TryStrToInt function needs to return two things: whether the input was an integer, and what that integer was, but functions can only have one "standard" return value).

Pascal. Specify to use a variable instead of function with the same name>

I'm writing long digit arythmetics. This is a function for adding to longint long binary digits. I need to output the sum inside the function, to debug it. How could I do it, without creating new variables?
function add(var s1,s2:bindata;shift:longint):bindata;
var l,i:longint;
o:boolean;
begin
writeln(s1.len,' - ',s2.len);
o:=false;
l:=max(s1.len,s2.len);
add.len:=0;
for i:=1 to l do begin
if o then Begin
if s1.data[i+shift] then Begin
if (s2.data[i]) then add.data[i+shift]:=true
Else add.data[i+shift]:=false;
End
else if s2.data[i] then add.data[i+shift]:=false
else Begin
add.data[i+shift]:=true;
o:=false;
End;
End
Else Begin
if s1.data[i+shift] then Begin
if s2.data[i] then
Begin
add.data[i+shift]:=false;
o:=true;
End
Else add.data[i+shift]:=true;
End
else if s2.data[i] then add.data[i+shift]:=true
else add.data[i+shift]:=false;
End;
output(add); //Can I output a variable?
end;
add.len:=l;
if o then Begin
inc(add.len);
add.data[add.len]:=true;
End;
end;
You are accumulating the result of the function within the function result variable, which is generally fine, but uses an outdated style, and leads to exactly the problem you're facing here. You're trying to report an intermediate value of the function result, and to do that, you're trying to reference the name of the function, add. When you do that, though, the compiler interprets it as an attempt to report the function itself, rather than the expected return value of this particular invocation of the function. You'll get the address of the function, if output is defined to accept function addresses; otherwise, you'll get a compiler error.
If your compiler offers a certain common language extension, then you should use the implicit Result variable to refer to the intermediate return value instead of continuing to refer to it by the function name. Since Result is declared implicitly, you wouldn't have to create any other variables. The compiler automatically recognizes Result and uses it as an alias for the function's return value. Simply find every place you write add within the function and replace it with Result. For example:
if o then begin
Inc(Result.len);
Result.data[Result.len] := True;
end;
Turbo Pascal, Free Pascal, GNU Pascal, and Delphi all support the implicit Result variable, but if you've managed to get stuck with a compiler that doesn't offer that extension, then you have no choice but to declare another variable. You could name it Result, and then implement your function with one additional line at the end, like so:
function add(var s1, s2: bindata; shift: longint): bindata;
var
l, i: longint;
o: boolean;
Result: bindata;
begin
{
Previous function body goes here, but with
`add` replaced by `Result`
}
{ Finally, append this line to copy Result into the
function's return value immediately before returning. }
add := Result;
end;