GATE / CS ARCHIVE

GATE CSE 1995 / QUESTION 18

Completing a four-bit two’s-complement conversion

Programming in C · Control Flow & Loop Tracing · Full GATE CSE 1995 paper

GATE 1995, Q18 5 marks · Descriptive
Report issue

Control Flow & Loop Tracing

Question 18, GATE 1995: Complete blanks A, B, C in this Pascal-like function, for integer −8≤N≤7: if N<0 then N:=A; BINARY:=0; EXPONENT:=1; while N<>0 do begin REM:=N mod 2; BINARY:=BINARY+B*EXPONENT; EXPONENT:=EXPONENT*10; N:=C end; TWOSCOMP:=BINARY. REM, EXPONENT and BINARY are integer variables. The returned decimal integer has the binary digits as its decimal digits. GFG declares REM; GateForum declares RAM but uses REM.
Question 18, GATE 1995: Complete blanks A, B, C in this Pascal-like function, for integer −8≤N≤7: if N<0 then N:=A; BINARY:=0; EXPONENT:=1; while N<>0 do begin REM:=N mod 2; BINARY:=BINARY+B*EXPONENT; EXPONENT:=EXPONENT*10; N:=C end; TWOSCOMP:=BINARY. REM, EXPONENT and BINARY are integer variables. The returned decimal integer has the binary digits as its decimal digits. GFG declares REM; GateForum declares RAM but uses REM.
Tap to enlarge
Answer & solution

Answer: A=N+16; B=REM; C=N div 2. (no official key was published)

Four bits represent signed values from −8 to 7. A negative N has the same four-bit pattern as the unsigned residue N+24=N+16. Thus the first blank is N+16: −8 maps to 8 (1000), and −1 maps to 15 (1111). Nonnegative inputs need no conversion before digit extraction.

For a nonnegative integer, N mod 2 is its least significant binary digit. The current EXPONENT is 1,10,100,1000, so adding REM*EXPONENT puts that bit in the corresponding decimal digit position of the returned integer. Hence B is REM. Integer division N div 2 discards the extracted bit; hence C is N div 2, not real division. Each iteration reduces the nonzero quotient and the loop terminates.

For N=−3, convert to 13. The remainders are 1,0,1,1, the accumulating decimal result is 1,1,101,1101, and the quotients are 6,3,1,0. Thus the result 1101 denotes the correct four-bit pattern. N=0 skips the loop and returns 0; positive outputs omit leading zero digits because they are stored as integers. Displaying exactly four bits requires zero-padding separately. Outside the guarded range the printed function does not assign its return value.

Original paper, page 7