1

Hello everyone once again,

I need to write a code in Pascal which converts a decimal number into a binary number, and saves this into an array, and then writes it from MSD to LSD.

I've got most of the code, however when I want to print it, I don't understand one significant thing:

I put the codesnippet

FOR i := 15 DOWNTO 1 DO
write(Integer(dualCalc[i]));

as output. When I run this program, I get the number 0000000000001010 as output, which is correct and also 16 bits. How? 15 DOWNTO 1 is only 15 bits, so how is the output 16 bits?

When I put

FOR i := 15 DOWNTO 0 DO
write(Integer(dualCalc[i]));

I get 00000000000010100, which is just wrong and 17 bits.

Can someone explain to me how this is possible?

Entire Code below.

PROGRAM ConvertNum;


TYPE
dual = ARRAY[0..15] OF BOOLEAN;


PROCEDURE Dec2Dual (decimal: INTEGER; VAR dualCalc: dual); 

VAR


i: INTEGER;
calculation: INTEGER;
divisionBool: BOOLEAN;


BEGIN

i := 0;    


WHILE (i < 16) AND (decimal > 0) DO
    BEGIN
        calculation := decimal mod 2;
            IF calculation = 0 THEN
            divisionBool := FALSE
            ELSE
            divisionBool := TRUE;
        dualCalc[i] := divisionBool;
        decimal := decimal div 2;
        i := i + 1;
    END;


FOR i := 15 DOWNTO 0 DO
write(Integer(dualCalc[i]));


END;

VAR

aThree: ARRAY[0..15] OF BOOLEAN;
inputVar: INTEGER;
DecOut: INTEGER;

BEGIN

readln(inputVar);

Dec2Dual(inputVar, aThree);

END.
3
  • 2
    Sorry to have to tell you, but you have a test case error. I can not point you at that error, because the code you have provided, doesn't show it. The loop produces correct (16 bit) binary output for all decimal values 0..15 (0000000000000000, 0000000000000001 ... 0000000000001111). No 17 digit outputs of the FOR i := 15 DOWNTO 0 DO loop. Commented Nov 1, 2024 at 15:11
  • @TomBrunberg Thank you for your comment, Kai Burghardt found the error, it was caused by an excess Writeln() Commented Nov 2, 2024 at 10:18
  • Sorry, but I have no idea what "excess WriteLn" you are talking about, as there are none in your code. Well, never mind... Commented Nov 2, 2024 at 17:09

1 Answer 1

4
  • In Pascal for‑loop limits are inclusive. Thus a loop
    for x := 1 to 1 do
    begin
        writeLn(x)
    end
    
    prints one line containing 1. This circumstance is probably inspired by mathematicians’ notation of sums and products, ∑ and ∏, that uses inclusive limits, too.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.