Pascal program exercise - pascal

I am at the beginning with my studies and would like to ask a question regarding a function in pascal. The aim is to calculate the Fahrenheit value in Celsius. The formula is as follows: C = [5 * (F - 32)] / 9.
The user should put in his value and it should result in the correct number.
My program is so far:
Program Temperaturerrechnung (input, output);
var
C: real;
F: real;
begin
writeln('Insert Fahrenheit', F);
readln(F);
C:= (5 * (F - 32)) / 9
writeln('The temperature is C: ', C)
end
When compiling, it tells me that F has not identified.

You have a few problems there:
writeln('Insert Fahrenheit', F);
The F variable is not initialized here, that means you have never assigned it a value. In this case I believe you don't want it in the output at all:
writeln('Insert Fahrenheit');
Also, you are missing ; after C:= (5 * (F - 32)) / 9.

Related

My program won't print out correct math numbers

I'm coding a little program but it won't print out the right math answer, it just stays at 993.
The Code:
program _Gul_;
uses crt;
var a: integer;
var b: integer;
begin
writeln('1000 - 7?');
a := 1000;
b := a - 7;
while a > 0 do
begin
writeln (a - 7, ' - 7?');
delay(120);
a := a - 7;
writeln (b)
if a = 6 then
break;
end;
writeln('я гуль')
end
I don't quite know why it is not working. I defined "b" and made a command that prints it out and the output is just:
You never update the value in b. In point of fact, b is not necessary to your program at all. Your printing strategy is also more complicated than it needs to be. Print a minus 7, then do the subtraction and print it. This prevents the program telling you the rest of 6 - 7 is 6.
program _Gul_;
uses
crt;
var
a: integer;
begin
a := 1000;
while a > 0 do
begin
writeln (a, ' - 7?');
delay(120);
a := a - 7;
writeln (a);
if a = 6 then
break;
end;
writeln('я гуль')
end.

Newton-Raphson method (square root) in Pascal, recursion

I want to implement this square root method in Pascal using recursion. However, I have some problems understanding how to transfer iterative method into recursive method:
Program NewtonRaphsonRecursive(output);
{$mode objFPC}
function newton_raphson_rec(a: real; p: real; eps: real; max_i: integer) : real;
var
x: real;
i: integer;
begin
x := a / 2.0;
i := 0;
if abs(x - a / x) < eps then
begin
result := x;
end
else
begin
x := (x + a / x) / 2.0;
i := i + 1;
result := newton_raphson_rec(x, p, eps, max_i);
end;
end;
var
sqroot: real;
begin
sqroot := newton_raphson_rec(25, 0.001, 0.000001, 100);
writeln(sqroot);
end.
The code: https://onlinegdb.com/OvDBfHzLf
If you look at the start of the Newton-Raphson iterative solution in the other question, you will see that the first calculation (x := num / 2.0) is merely a first guess of the solution. You must remove that line in your recursive solution and enter a best guess into the function parameter.
function newton_raphson_recurse(num: real; new_guess: real; eps: real; max_i: integer) : real;
begin
Dec(max_i); // Decrement counter
new_guess := (new_guess + num / new_guess) / 2.0;
if (Abs(new_guess - num) < eps) or (max_i < 1)
then Result := new_guess
else Result := newton_raphson_recurse(num,new_guess,eps,max_I);
end;
...
sqroot := newton_raphson_recurse(9, 9/2.0, 0.0000001, 10);
Note how the new_guess is reused during the recursion with a more accurate value each time.
As always when testing a routine, single stepping into the program is a very good skill to learn when debugging.
Recursion operates on the same basic principles as imperative iteration. You have a starting state, an exit condition that causes termination of recursion/iteration, and an update that updates the state to converge on that exit condition.
Consider a simple example: summing a range.
function SumImperative(s, e : integer) : integer;
var
current : integer;
result : integer;
begin
current := s;
result := 0;
while current <= e do
begin
result := result + current;
current := current + 1
end;
SumImperative := result;
end;
Our function sets an initial state, the while current <= e do sets an exit condition, and current := current + 1 updates the state.
Now, recursively...
function SumRecursive(s, e : integer) : integer;
begin
if s > e then
SumRecursive := 0
else
SumRecursive := s + SumRecursive(s + 1, e)
end;
Here we set our initial state with the fucntion arguments. Our exit condition is s being greater than e. If that happens, the function returns 0 and there is no more recursion. If that codnition isn't met, we add s to the result of calling the fucntion again, but this time we update the state so that we're looking for s + 1 and e.
This looks like:
SumRecursive(1, 4)
1 + SumRecursive(2, 4)
1 + (2 + SumRecursive(3, 4))
1 + (2 + (3 + SumRecursive(4, 4)))
1 + (2 + (3 + (4 + SumRecursive(5, 4))))
1 + (2 + (3 + (4 + 0)))
1 + (2 + (3 + 4))
1 + (2 + 7)
1 + 9
10

Implement x^(e) in Extended Pascal, without using exponentiation operators

Part of a Pascal ISO 10206 program I am building, requires me to implement a function to exponentiate a real number (x) to Eulers number (e), without using any exponentiation functions already included in Pascal(**,pow,exp...).
I have been trying different algorithms for hours but I cant figure out how to do it without using the already included exponentiation functions.
Any help would be appreciated. Any mathematical algorithm of some sort etc... Thanks in advance.
As others have said, it doesn't make sense not to use Exp() or a function based upon it. But if you really must use something else, and don't want to get too technical/mathematical, then the following should work (the real algorithm is far more complicated and requires much more knowledge of math).
The program uses a combination of the first N terms of Taylor series for the fraction of X and binary exponentiation for the integer part of X. It is probably not very fast, but pretty accurate, even for larger exponents. For comparison, I also display Exp(X). If your Pascal has a Double or Extended type, use those instead of Real.
program SimplePower;
{ Required for Delphi, you can omit it in other Pascals: }
{$APPTYPE CONSOLE}
{ Returns approximate value of e^X using sum of first N terms of Taylor series.
Works fine with X values between 0 and 1.0 and N ~ 30. }
function Exponential(N: Integer; X: Real): Real;
var
I: Integer;
begin
Result := 1.0;
for I := N - 1 downto 1 do
Result := 1.0 + X * Result / I;
end;
{ Binary exponentiation of Base by integer Exponent. }
function IntegerExp(Base: Real; Exponent: Integer): Real;
begin
Result := 1.0;
while Exponent > 0 do
begin
if Odd(Exponent) then
Result := Result * Base;
Base := Base * Base;
Exponent := Exponent shr 1;
end;
end;
{ Combines IntegerExp function for integral part with
Exponential function for fractional part. }
function MyExp(N: Integer; X: Real): Real;
const
E = 2.7182818284590452353602874713527; { from Google: "e euler" }
var
Factor: Real;
Fraction: Real;
begin
Fraction := Exponential(N, Frac(X));
Factor := IntegerExp(E, Trunc(X));
Result := Factor * Fraction;
end;
{ Simple demo: }
const
N = 30;
X = 73.4567890242421234;
begin
Writeln('MyExp(', N, ', ', X:22:18, ') = ', MyExp(N, X):22:18);
Writeln('Exp(', X:22:18, ') = ', Exp(X):22:18);
end.
Ref:
Taylor series for exponentiation
Binary exponentiation
I did not do anything for negative exponents, but just know that Exp(-x) = 1/Exp(x). You could amend MyExpwith that knowledge.
I used the solution pointed out by #RudyVelthuis in some other post, but modified it a bit. It is based upon that x^0.5 = sqrt(x), which we can use to our advantage. Ill leave the Pascal ISO 10206 code I used attached. Thank you all for your help, specially Rudy.
function MyPow(base,power,precision:real):real;
begin
if (power<0) then MyPow:=1/MyPow(base,-power,precision)
else if (power>=10) then MyPow:=sqr(MyPow(base,power/2,precision/2))
else if (power>=1) then MyPow:=base*MyPow(base,power-1,precision)
else if (precision>=1) then MyPow:=sqrt(base)
else MyPow:=sqrt(MyPow(base,power*2,precision*2));
end;

How do i compare 3 numbers in Pascal?

i'm a newbie
and I need how to compare 3 numbers in Pascal.
Here is what I tried so far
BEGIN
max:=A;
IF B>A THEN max:= B;
IF C>B THEN max:= C;
END;
but when I choose, for example, A = 5 , B=2 , C=4, the output is 4, but it should be 5. Where is the problem?
I want at the end writeln('The Large Number is ',max);
You could do this (you should be comparing with max)
BEGIN
max:=A;
IF B>max THEN max:= B;
IF C>max THEN max:= C;
END;
You must compare with max instead of A or B.
Changing your code in a easy way:
BEGIN
max := A;
IF B > max
THEN
max := B;
IF C > max
THEN
max := C;
END;
Or, in a somewhat recent Pascal, like Delphi or Free Pascal, using the max function from the MATH unit.
result:=max(a,max(b,c));
Using the Max Function of Pascal
PROGRAM MaxProgram;
USES math;
VAR
num1,num2,num3,maxNum : INTEGER;
BEGIN
(* Receive the Values *)
WRITELN('Enter First Number');
READLN(num1);
WRITELN('Enter Second Number');
READLN(num2);
WRITELN('Enter Third Number');
READLN(num3);
(* Using the Max Function *)
maxNum := max(num1,max(num2,num3));
(* Display Result *)
writeln('The Highest number is ', MAXNUM);
END.

Obtaining the complex roots of a 2nd degree polynomial in pascal

I have to code a program in pascal that, given the three coefficients of a polynomial(ax²+bx+c), outputs its roots.
Here's what I have right now:
program poly;
type
polynomial = record
a, b, c : real;
end;
procedure readPolynomial (var p : polynomial);
begin
writeln ('Input 1st coefficient: ');
readln (p.a);
writeln ('Input 2nd coefficient: ');
readln (p.b);
writeln ('Input 3rd coefficient: ');
readln (p.c);
end;
function square (x : real) : real;
begin
square := x * x;
end;
procedure roots (p : polynomial; var rP, rN : real);
begin
rP := (-p.b + (sqrt((square(p.b)) - (4 * p.a * p.c)))) / (2 * p.a);
rN := (-p.b - (sqrt((square(p.b)) - (4 * p.a * p.c)))) / (2 * p.a);
writeln('The roots are: ', rP:0:3, ' y ' ,rN:0:3);
end;
var
myPolynomial : polynomial;
r1, r2 : real;
begin
writeln ('Enter the coefficients: ');
readPolynomial (myPolynomial);
roots (myPolynomial, r1, r2);
end.
It works fine for real roots but I don't know how to make it work with complex numbers.
I am assuming your coefficients are real numbers (they user can't enter complex numbers as coefficients). That would add a whole new level of complexity (no pun intended) to the problem.
You need to check the discriminant ((square(p.b)) - (4 * p.a * p.c)) to see if it's less than 0. Currently, your code just does, sqrt((square(p.b)) - (4 * p.a * p.c)) but you aren't checking if you are taking the square root of a negative number (which you can't do using the Pascal sqrt library function).
If the discriminant is negative, then you have a complex root and you can separate the real and imaginary parts as you wish in your program. It's basic quadratic formula.
For example:
procedure roots (p : polynomial; var rP, rN : real);
var disc: real;
begin
disc := square(p.b) - 4*p.a*p.c;
if disc >= 0 then begin
rP := (-p.b + sqrt(disc)) / (2 * p.a);
rN := (-p.b - sqrt(disc)) / (2 * p.a);
writeln('The roots are: ', rP:0:3, ' y ' ,rN:0:3);
end
else begin
// Roots are:
// -p.b/(2*p.a) + (sqrt(-disc)/(2*p.a))i
// -p.b/(2*p.a) - (sqrt(-disc)/(2*p.a))i
end
end;
Here you use the fact that sqrt(x) if x is negative would be, (sqrt(-x))i where i is sqrt(-1). Note that you could also split out the disc = 0 case to avoid repeating a double root.
Since your roots function prints out the results and your main program doesn't use the returned arguments rN and rP, it's not clear to me if you need to pass back the roots at all. But if want to pass the roots back as arguments (the way you have your function currently designed), I'll leave that as an exercise. You just have to decide on a representation for complex roots. One way is to use the Complex number type for the results (if your compiler library supports them), and when the results are real, the imaginary parts will just be zero. Alternatively, if you need to create your own, just make a type which is a record consisting of a real and imaginary part.
type complex = record
re: real;
im: real;
end;

Resources