Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

Where is the error?

+5 votes
asked Dec 18, 2022 by X12 (210 points)

The result of my program differs from the result of the implementation in the paper, where is the error?​

I want to calculate this: -1+2-3+4-5+...+ or - N, in PASCAL language, so i write this program but the result is false, Although the method of implementation in the paper is correct.

So, for example, if I enter the number 4, the result is supposed to be 2, but it prints 10 for me, so where is the error? ​:

program x12;
   var J,I,N,Y,S:integer;
begin
readln(n);
Y:=0;
S:= N mod 2;
while i<= N do begin
              if S=1 then begin Y:=Y-I; 
                                I:=I+1
                     end
                     else begin Y:=Y+I; 
                                I:=I+1
                     end
               end;
write(Y)
end.

1 Answer

+1 vote
answered Dec 19, 2022 by Peter Minarik (86,240 points)
selected Dec 19, 2022 by X12
 
Best answer

Your program keeps adding the numbers, as you never change the sign (S).

After you've done your logic of adding or subtracting, you should change your sign. After this, your code should work.

I'll leave the implementation to you.

commented Dec 19, 2022 by X12 (210 points)
Thank you very much for your response to my question, I discovered my mistake and now the program gives the correct result. I forgot some things so the program writes like this now:

program x12;
   var j,i,n,y,s:integer;
begin
readln(n);
y:=0;
s:= n mod 2;
while i<= n do begin
              if s=1 then begin y:=y-i;
                                i:=i+1;
                                s:= i mod 2;
                     end
                     else begin y:=y+i;
                                i:=i+1;
                                s:= i mod 2;
                     end
               end;
write(y)
end.
commented Dec 20, 2022 by Peter Minarik (86,240 points)
I'm happy you managed to make your code work correctly now. :)

For reference, here's my implementation:

Program x12;
   Var n, sum, i: Integer;
Begin
    ReadLn(n);
    sum := 0;
    For i := 1 To n Do
    Begin
        If i Mod 2 = 0 Then
            sum := sum + i
        Else
            sum := sum - i;
    End;
    WriteLn(sum);
End.
commented Dec 21, 2022 by X12 (210 points)
This is great, your code is short and better, thank you very much for your help
Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.
...