Skip to main content
Engineering LibreTexts

18.2: Recursive Print Binary Example

  • Page ID
    54379
  • \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)

    \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)

    \( \newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\)

    ( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\)

    \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\)

    \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\)

    \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\)

    \( \newcommand{\Span}{\mathrm{span}}\)

    \( \newcommand{\id}{\mathrm{id}}\)

    \( \newcommand{\Span}{\mathrm{span}}\)

    \( \newcommand{\kernel}{\mathrm{null}\,}\)

    \( \newcommand{\range}{\mathrm{range}\,}\)

    \( \newcommand{\RealPart}{\mathrm{Re}}\)

    \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\)

    \( \newcommand{\Argument}{\mathrm{Arg}}\)

    \( \newcommand{\norm}[1]{\| #1 \|}\)

    \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\)

    \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\AA}{\unicode[.8,0]{x212B}}\)

    \( \newcommand{\vectorA}[1]{\vec{#1}}      % arrow\)

    \( \newcommand{\vectorAt}[1]{\vec{\text{#1}}}      % arrow\)

    \( \newcommand{\vectorB}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)

    \( \newcommand{\vectorC}[1]{\textbf{#1}} \)

    \( \newcommand{\vectorD}[1]{\overrightarrow{#1}} \)

    \( \newcommand{\vectorDt}[1]{\overrightarrow{\text{#1}}} \)

    \( \newcommand{\vectE}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash{\mathbf {#1}}}} \)

    \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)

    \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)

    \(\newcommand{\avec}{\mathbf a}\) \(\newcommand{\bvec}{\mathbf b}\) \(\newcommand{\cvec}{\mathbf c}\) \(\newcommand{\dvec}{\mathbf d}\) \(\newcommand{\dtil}{\widetilde{\mathbf d}}\) \(\newcommand{\evec}{\mathbf e}\) \(\newcommand{\fvec}{\mathbf f}\) \(\newcommand{\nvec}{\mathbf n}\) \(\newcommand{\pvec}{\mathbf p}\) \(\newcommand{\qvec}{\mathbf q}\) \(\newcommand{\svec}{\mathbf s}\) \(\newcommand{\tvec}{\mathbf t}\) \(\newcommand{\uvec}{\mathbf u}\) \(\newcommand{\vvec}{\mathbf v}\) \(\newcommand{\wvec}{\mathbf w}\) \(\newcommand{\xvec}{\mathbf x}\) \(\newcommand{\yvec}{\mathbf y}\) \(\newcommand{\zvec}{\mathbf z}\) \(\newcommand{\rvec}{\mathbf r}\) \(\newcommand{\mvec}{\mathbf m}\) \(\newcommand{\zerovec}{\mathbf 0}\) \(\newcommand{\onevec}{\mathbf 1}\) \(\newcommand{\real}{\mathbb R}\) \(\newcommand{\twovec}[2]{\left[\begin{array}{r}#1 \\ #2 \end{array}\right]}\) \(\newcommand{\ctwovec}[2]{\left[\begin{array}{c}#1 \\ #2 \end{array}\right]}\) \(\newcommand{\threevec}[3]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \end{array}\right]}\) \(\newcommand{\cthreevec}[3]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \end{array}\right]}\) \(\newcommand{\fourvec}[4]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \\ #4 \end{array}\right]}\) \(\newcommand{\cfourvec}[4]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \\ #4 \end{array}\right]}\) \(\newcommand{\fivevec}[5]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \\ #4 \\ #5 \\ \end{array}\right]}\) \(\newcommand{\cfivevec}[5]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \\ #4 \\ #5 \\ \end{array}\right]}\) \(\newcommand{\mattwo}[4]{\left[\begin{array}{rr}#1 \amp #2 \\ #3 \amp #4 \\ \end{array}\right]}\) \(\newcommand{\laspan}[1]{\text{Span}\{#1\}}\) \(\newcommand{\bcal}{\cal B}\) \(\newcommand{\ccal}{\cal C}\) \(\newcommand{\scal}{\cal S}\) \(\newcommand{\wcal}{\cal W}\) \(\newcommand{\ecal}{\cal E}\) \(\newcommand{\coords}[2]{\left\{#1\right\}_{#2}}\) \(\newcommand{\gray}[1]{\color{gray}{#1}}\) \(\newcommand{\lgray}[1]{\color{lightgray}{#1}}\) \(\newcommand{\rank}{\operatorname{rank}}\) \(\newcommand{\row}{\text{Row}}\) \(\newcommand{\col}{\text{Col}}\) \(\renewcommand{\row}{\text{Row}}\) \(\newcommand{\nul}{\text{Nul}}\) \(\newcommand{\var}{\text{Var}}\) \(\newcommand{\corr}{\text{corr}}\) \(\newcommand{\len}[1]{\left|#1\right|}\) \(\newcommand{\bbar}{\overline{\bvec}}\) \(\newcommand{\bhat}{\widehat{\bvec}}\) \(\newcommand{\bperp}{\bvec^\perp}\) \(\newcommand{\xhat}{\widehat{\xvec}}\) \(\newcommand{\vhat}{\widehat{\vvec}}\) \(\newcommand{\uhat}{\widehat{\uvec}}\) \(\newcommand{\what}{\widehat{\wvec}}\) \(\newcommand{\Sighat}{\widehat{\Sigma}}\) \(\newcommand{\lt}{<}\) \(\newcommand{\gt}{>}\) \(\newcommand{\amp}{&}\) \(\definecolor{fillinmathshade}{gray}{0.9}\)

    This section provides an example recursive subroutine to accept a decimal number and print that number in binary (i.e., using 1's and 0').

    It is assumed the reader has a basic understanding of binary1 representation. This information is summarized in the chapter on Computer Organization. Additionally, there are many references available on the Internet.

    Understand the Problem

    For this example, the problem is divided into two parts, the main program and the recursive subroutine. The main program will handle the prompting and reading of the decimal number including error checking and re-prompting as needed. The recursive subroutine will display the binary value. Since the error checking is already performed, the recursive subroutine will assume valid input. For more complex examples, the routine may need to perform basic error checking.

    Create the Algorithm

    One basic algorithm to convert a decimal number into a binary number, is successive integer division by 2. For example, given the number 13, 13 divided by 2 is 6 with a remainder of 1. Next, the 6 is divided by 2 giving 3 with a remainder of 0. Again, the 3 is divided by 2 providing a 1 with a remainder of 1. The final 1 is divided by 2 resulting in a 0 with a remainder of 1. With a final result of 0, the algorithm is completed. The process is shown as follows:

    \[ \frac{13}{2} = 6 \quad \textit{remainder } 1 \nonumber \]

    \[ \frac{6}{2} = 3 \quad \textit{remainder } 0 \nonumber \]

    \[ \frac{3}{2} = 1 \quad \textit{remainder } 1 \nonumber \]

    \[ \frac{1}{2} = 0 \quad \textit{remainder } 1 \nonumber \]

    The remainders, always 0 or 1, represent the binary value. However, the resulting remainders are generated in backwards order. As such, the resulting remainders 1, 0, 1, and 1 in this example must be reversed for a final value of \(1101_2\) (as noted in chapter 2).

    This process can be converted into a recursive relation as follows:

    \[ printBinary(n) = \begin{cases} \textit{if } n \leq 1 & n \\ \textit{if } n > 1 & printBinary(n/2) \\ & \text{output } mod(num,2) \end{cases} \nonumber \]

    This definition assumes that the value of \(n\) is positive. The recursive relation can be used by directly converting the algorithm into code.

    Implement the Program

    Based on the recursive definition, a simple recursive subroutine can be created. In order to demonstrate the recursive subroutine, a main program is provided that will read a decimal value from user and ensure it is between 0 and 1,000,000, and then call the recursive routine.

    ! Simple recursive program to print a decimal number in binary
    
    program binary
    implicit none
    integer :: decimalNumber
    
        write (*,'(a/)') "Decimal to Binary Conversion Example"
    
        do
            write (*,'(a)', advance="no")                    &
                "Enter Decimal Number (0 - 1,000,000): "
            read (*,*) decimalNumber
            if (decimalNumber >= 0 .and.                     &
                decimalNumber <= 1000000) exit
    
            write (*,'(a)') "Error, decimal value out of range."
            write (*,'(a)') "Please re-enter."
        end do
    
        write (*,'(/a, i7, a)', advance="no")                &
            "The decimal value of ", decimalNumber, " is "
    
        call printBinary(decimalNumber)
        write (*,'(/)')
    
    contains
    
    ! ************************************************************
    !  Print binary subroutine.
    
    recursive subroutine printBinary(num)
    integer, intent(in) :: num
    
        if (num > 1) call printBinary(num/2)
    
        write (*,'(i1)', advance="no") mod(num,2)
    
        return
    end subroutine printBinary
    
    ! ************************************************************
    end program binary
    

    The spacing and indentation are not required, but help to make the program more readable. The main program ensures that the recursive routine is not called in invalid values (i.e., values \(\leq\) 0).

    Test/Debug the Program

    For this problem, the testing would involve executing the program and entering a series of decimal values and ensure that the results are correct. The Windows calculator provides simple convert-to- binary function that can be used for verification.

    If the program does not provide the correct results, the input to the recursive subroutine should be verified (via write statements). Next, some additional write statements in the recursive subroutine can be added to provide insight into what is being done for each call.


    1. For more information regarding binary representation, refer to: http://en.Wikipedia.org/wiki/Binary_number

    This page titled 18.2: Recursive Print Binary Example is shared under a CC BY-NC-SA 3.0 license and was authored, remixed, and/or curated by Ed Jorgensen via source content that was edited to the style and standards of the LibreTexts platform.

    • Was this article helpful?