Search code examples
mathpascaloperator-precedence

Pascal - Order Of Operations


I have a simple yet irritating problem.
When I execute the code below and write 10 for 'a' I get 1010 as a result,
but I really don't know how, if i try solve this problem by myself.
In know the order of operations, but I'm kinda stuck, like I'd overlook something.

Please, give me a kick-start. I would be very grateful.

program task1 (input,output);

var
a, b, c : integer;

begin
    b := 0;
    c := 1;
    readln(a);
    while a > 0 do
    begin
        b := b + c * (a mod 2);
        a := a div 2;
        c := c * 10;
    end;
    writeln(b)
end.

Solution

  • Here is what the program calculates. The table has the assignment of b on a separate line, followed by the assignments of a and c on the same line:

     a     b      c
    10     0      1    Initialization
           0           10 mod 2 = 0
     5           10
          10            5 mod 2 = 1; 0 + 10 * 1 = 10
     2          100
          10            2 mod 2 = 0
     1         1000
        1010            1 mod 2 = 1; 10 + 1000 * 1 = 1010
     0        10000