C PROGRAMMING PROGRAM • LOOPS & NUMBER PROBLEMS

Convert Decimal to Binary

Learn how to convert decimal to binary using a clear C program.

BeginnerBase conversionRemaindersArray

PROBLEM UNDERSTANDING

Input and expected output

Sample input
45
Sample output
Binary = 101101

COMPLETE C PROGRAM

Complete C implementation

decimal-to-binary.c
Open in compiler
#include <stdio.h>

int main(void)
{
    unsigned int number, value;
    int bits[32], count = 0;

    printf("Enter a non-negative decimal integer: ");
    scanf("%u", &number);
    value = number;
    do {
        bits[count++] = (int) (value % 2);
        value /= 2;
    } while (value > 0);
    printf("Binary = ");
    for (int index = count - 1; index >= 0; index--) printf("%d", bits[index]);
    printf("\n");
    return 0;
}

GUIDED CODE TOUR • NOT LIVE EXECUTION

Study the program line by line

Use the real compiler button above to run and debug with different inputs.

CURRENT STEP

Select Start to walk through the important lines.

SELECTED LINE

No line selected

EXPECTED OUTPUT FOR THE SAMPLE

Binary = 101101
0%Step 0 of 0

PROGRAM EXPLANATION

Algorithm and explanation

  1. Read the required input values.
  2. Collect remainders from repeated division by two and print them in reverse order.
  3. Display the computed result.

Collect remainders from repeated division by two and print them in reverse order.

EFFICIENCY

Time and space complexity

Time complexity

O(log n)

Auxiliary space

O(log n)

DEBUGGING CHECKLIST

Common mistakes

Check this

Use the correct format specifier for every variable.

Check this

Initialize variables before using their values.

Check this

Check braces, semicolons and input order carefully.

Try it yourself

Practice: Run the program with the sample input, predict its output, and then test one boundary case of your own.