Swift program to convert the decimal number to binary using recursion


This tutorial will discuss how to write Swift program to convert the decimal number to binary using recursion.

Decimal numbers are those numbers whose base value is 10. Decimal numbers are also known as base-10 number system which contain 10 numbers: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9. Here, the position of every digit in the decimal number has weight is a power of 10.

Binary numbers are those numbers whose base value is 2. Binary numbers are also known as base-16 number system which contain only two number 1 and 0. Here, the position of every digit in the binary number has weight is a power of 2.

For example, (1011)2 is a binary number. Binary numbers are the most commonly used number system in computer devices where every digit is represented by a bit.

Here we convert decimal to binary using recursion. Recursion is a process in which a function call itself to complete the specified task.

Below is a demonstration of the same −

Input

Suppose our given input is −

Decimal Number = 10

Output

The desired output would be −

Binary number = 1010

Algorithm

Following is the algorithm −

Step 1 − Create a recursive function

Step 2 − Declare a variable to store result.

Step 3 − Set base condition to stop recursive function. Here the base condition is (num != 0)

Step 4 − Convert decimal number into binary number by calling the function itself and return the result.

StoreBinary = (num%2)+10*ConvertBinary(num: num/2)

Step 5 − Declare another variable to store decimal number.

Step 6 − Call the function and pass decimal number into it.

Step 7 − Print the output

Example

The following program shows how to convert the decimal number to binary using recursion.

import Foundation
import Glibc

// Recursive function to convert decimal to binary
func ConvertBinary(num: Int)->Int{
   var StoreBinary:Int
    
   // Base condition
   if (num != 0){
    
      // Converting decimal to binary
      StoreBinary = (num%2)+10*ConvertBinary(num: num/2)
      return StoreBinary
   }
   else{
      return 0
   }
}

// Decimal Number
var decimalNum = 11

print("Decimal number is: (decimalNum)")
print("Converted binary number is: ", ConvertBinary(num
:decimalNum))

Output

Decimal number is: (decimalNum)
Converted binary number is:  1011

Here in the above code, we create a recursive function named ConvertBinary(). This function convert decimal number into binary by calling itself recursively. So, the entered decimal number is 11 hence the equivalent binary number is 1011.

Updated on: 13-Dec-2022

216 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements