# Write a Golang program to convert a decimal number to its binary form

Go ProgrammingServer Side ProgrammingProgramming

#### Cyber Security : Go from Zero to Hero

Most Popular

60 Lectures 5.5 hours

#### Master C and Embedded C Programming- Learn as you go

66 Lectures 5.5 hours

#### C Programming from scratch- Master C Programming

Best Seller

60 Lectures 8 hours

## Examples

• Input decimal_num = 13 => Output = 8+4+1 => 1101
• Input decimal_num = 11 => Output = 8+2+1 => 1011

## Approach to solve this problem

• Step 1: Define a function that accepts a decimal number, decimal_num, type is int.
• Step 2: Define an array to store the remainder while dividing decimal number by 2.
• Step 3: Start a for loop until the decimal number becomes 0.
• Step 4: Print the binary array in reverse order.

## Program

Live Demo

package main
import (
"fmt"
)

func decimalToBinary(num int){
var binary []int

for num !=0 {
binary = append(binary, num%2)
num = num / 2
}
if len(binary)==0{
fmt.Printf("%d\n", 0)
} else {
for i:=len(binary)-1; i>=0; i--{
fmt.Printf("%d", binary[i])
}
fmt.Println()
}
}

func main() {
decimalToBinary(87)
decimalToBinary(10)
decimalToBinary(31)
decimalToBinary(0)
}

## Output

1010111
1010
11111
0