Convert decimal to binary using One Dimensional Array in C


This program is written in C programming language and it does the following:

  • It first declares some integer variables i, n and an array a
  • The program then prompts the user to enter a decimal number 'n'
  • Then, it uses a for loop to convert the entered decimal number to binary
  • Within the for loop, it uses the modulus operator(%) to get the remainder of the decimal number divided by 2 and stores it in an array 'a'
  • Then it uses integer division(/) to update the decimal number to its quotient
  • Next, it uses another for loop to iterate through the array 'a' and prints the array in reverse order
  • The final output will be the binary representation of the decimal number entered
  • The program ends by returning 0 as the value of the main function.

Source Code

#include<stdio.h>
int main()
{
  int i,n,a[10];
  printf("\nEnter the Decimal value:");
  scanf("%d",&n);
  for(i=0;n!=0;i++)
  {
    a[i]=n%2;
    n=n/2;
  }
  n=i;
  printf("\nBinary Value:");
  for(i=0;i<n;i++)
  {
    printf("%d",a[n-i-1]);
  }
  return 0;
}

To download raw file Click Here

Output

Enter the Decimal value:20
Binary Value:10100

List of Programs


Sample Programs


Switch Case in C


Conditional Operators in C


Goto Statement in C


While Loop Example Programs


Looping Statements in C

For Loop Example Programs


Array Examples in C

One Dimensional Array


Two Dimensional Array in C


String Example Programs in C


Functions Example Programs in C