Learning C++ Programming from Scratch, Day 396: Converting Positive Integer N to Binary Number; Question Bank Answer; Method 1

1108 – Converting Positive Integer N to Binary Number

Learning C++ Programming from Scratch, Day 396: Converting Positive Integer N to Binary Number; Question Bank Answer; Method 1

What does this program do?

This program acts like a “digital translator” that converts the numbers we commonly use (like 10, 25) into binary numbers used by computers (like 1010, 11001). It’s similar to translating Chinese into English, but here we are translating decimal numbers into binary numbers.

How does the program work?

  1. Preparation Phase: The program first prepares the necessary tools (including header files and using namespaces)

  2. Receiving Input: It prompts the user to input a regular number (like 10)

  3. Special Case Handling: If the user inputs 0, it directly outputs 0 (since the binary of 0 is still 0)

  4. Translation Process:

  • Repeatedly divide the number by 2, recording the remainder (0 or 1) each time

  • These remainders represent each bit of the binary number, but in reverse order

  • Output Result: Reverse the recorded remainders to output, thus obtaining the correct binary number

  • A Simple Example

    For example, input the number 6:

    1. 6 ÷ 2 = 3 remainder 0 → record 0

    2. 3 ÷ 2 = 1 remainder 1 → record 1

    3. 1 ÷ 2 = 0 remainder 1 → record 1

      The recorded remainders are 0, 1, 1, reversing gives 110, so the binary of 6 is 110

    Reference Code

    #include<bits/stdc++.h>  // Includes all commonly used standard library headers, like preparing a toolbox
    using namespace std;     // Using the standard namespace, so we don't have to write std:: every time
    /*1108 - Converting Positive Integer N to Binary Number
    This program's function is to convert the input decimal integer into binary form*/
    int main(){    // Define variables:    // num - stores the user's input decimal number    // two[100] - array to store binary bits during conversion (up to 100 bits)    // i, j - loop counters    int num, two[100], i, j;
        // Get an integer input from the user    cin >> num;
        // Special case handling: if the input is 0, directly output 0    // Because the binary representation of 0 is 0    if ( num == 0 ){        cout << "0";    }
        // Start the conversion process:    // By repeatedly dividing by 2 and recording remainders    // The loop runs a maximum of 100 times (to prevent array overflow)    for ( i = 0 ; i < 100 ; i ++ ){        // If num has become 0 or negative, stop the loop        if ( num <= 0 ){            break;        }        // Calculate the current num divided by 2's remainder, store in array        // This remainder is a binary bit (0 or 1)        two[i] = num%2;
            // Debug output, can check the result of each calculation        // cout << "two["<< i << "]= " << two[i] << "   num="<<num<<endl;
            // Update num to the quotient of dividing by 2, preparing for the next calculation        num = num/2;
            // Debug output, can check the change of num        // cout << "   num="<<num<<endl;    }
        // Output result:    // Because the previously recorded binary bits are in reverse order (least significant bit first)    // Now we need to output from back to front to get the correct binary number    for ( j = i-1 ; j >= 0 ; j -- ){        cout << two[j];    }
        return 0;  // Program ends normally
    }

    1. Purpose of the Program

    This program is a decimal to binary converter. It can convert decimal numbers (like 123) that we use in daily life into binary numbers (like 1111011) used by computers.

    2. Basic Concepts

    • Decimal: The number system we commonly use, consisting of ten digits from 0 to 9

    • Binary: The number system used by computers, consisting of only two digits, 0 and 1

    • Conversion Principle: By repeatedly dividing by 2 and recording the remainders, finally arranging the remainders in reverse order

    3. Working Principle of the Program

    Input Phase

    1. After the program starts, it waits for the user to input an integer

    2. This integer will be stored in the variable<span>num</span>

    Special Case Handling

    • If the user inputs 0, the program will directly output “0”, because:

      • The binary representation of 0 is 0

      • No calculations are needed

    Conversion Process

    1. Initialization: Prepare an array<span>two</span> to store binary bits

    2. Loop Calculation:

    • In each loop, the program does three things:

    1. Calculate<span>num</span> divided by 2’s remainder (using<span>%</span> operator)

    2. Store this remainder (0 or 1) in the array

    3. Update<span>num</span> to the quotient of dividing by 2 (using<span>/</span> operator)

  • Termination Condition: Stop the loop when<span>num</span> becomes 0

  • Output Phase

    1. Reverse Output: Since the binary bits obtained during calculation are in reverse order (the last bit calculated first), they need to be output from back to front

    2. Display Result: Output the numbers in the array in the correct order, which is the final binary representation

    4. Example Demonstration

    Example 1: Input 6

    1. First round of loop:

    • 6 ÷ 2 = 3 remainder 0 → two[0] = 0

    • num = 3

  • Second round of loop:

    • 3 ÷ 2 = 1 remainder 1 → two[1] = 1

    • num = 1

  • Third round of loop:

    • 1 ÷ 2 = 0 remainder 1 → two[2] = 1

    • num = 0 (loop ends)

  • Output: two[2], two[1], two[0] → 1 1 0

  • Result: 110

  • Example 2: Input 13

    1. First round: 13 ÷ 2 = 6 remainder 1 → two[0] = 1

    2. Second round: 6 ÷ 2 = 3 remainder 0 → two[1] = 0

    3. Third round: 3 ÷ 2 = 1 remainder 1 → two[2] = 1

    4. Fourth round: 1 ÷ 2 = 0 remainder 1 → two[3] = 1

    5. Output: two[3], two[2], two[1], two[0] → 1 1 0 1

    6. Result: 1101

    5. Considerations

    1. Input Range:

    • The program can handle positive integers

    • If a negative number is input, the program will terminate directly (because of the loop condition num<=0)

  • Array Size:

    • The size of the array two is 100, meaning it can convert numbers up to 2^100

    • This is sufficient for normal use

  • Output Format:

    • The output binary number does not have a prefix (like “0b”)

    • It directly displays pure binary digits

  • Debug Information:

    • The commented cout statements in the program can be used to view the conversion process

    • If debugging is needed, these comments can be uncommented

    6. Learning Value

    Through this program, beginners can learn:

    1. Basic input and output operations

    2. Use of loop structures

    3. Basic operations with arrays

    4. Application of division and modulus operations

    5. Basic principles of number system conversion

    Leave a Comment