Meekanovich
Meekanovich

Reputation: 7

how to write reciprocal value of a number in pascal?

I'm having some problems with a program in pascal.

I need to enter a number and than I need the program to write an addition of reciprocal value of that number. It sholud be something like this : let's say the number is 5 (n=5) then I need my program to write 1/1 + 1/2 + 1/3 + 1/4 + 1/5 and a result of this addition , I need to use for,to,do in order to get a solution, so if someone could help me, I'd be really thankful. I tried something like this :

 program reciprocaladdition;
 var x : integer:
 begin
 writeln('enter number');
 readln(x);
 for x:=1 to x do writeln(1/x:0:2)
 readln
end.

but it doesnt give me whaat i need so if someone could help me id be thankful.

Upvotes: 0

Views: 219

Answers (1)

MartynA
MartynA

Reputation: 30715

Your has a couple of typos:

the colon after integer should be a semicolon; and

the writeln needs a semicolon after it because there is another statement (readln) after it.

Apart from that, it compiles and runs fine in Lazarus + FPC. In the corrected version below, I've added code to calculate and display the sum of the intermediate values.

program reciprocals;

var
  x : integer;
  Sum : Double;  //  a floating-point datatype

begin
  writeln('enter number');
  readln(x);

  Sum := 0;
  for x:=1 to x do begin
    writeln(1/x:0:2);
    Sum := Sum + 1/x;
  end;
  writeln('Sum: ', Sum:0:2);
 readln
end.           

This produces the output

enter number
3
1.00
0.50
0.33
Sum: 1.83

Does that do what you want it to? If not, please say why.

Upvotes: 1

Related Questions