Convert binary to decimal 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, bin, n and an array a
  • The program then prompts the user to enter a binary number 'n'
  • Then, it uses a for loop to convert the entered binary number to decimal
  • Within the for loop, it uses the modulus operator(%) to get the last digit of the binary number and stores it in an array 'a'
  • Then it uses integer division(/) to remove the last digit from the binary number
  • Next, it uses another for loop to iterate through the array 'a'
  • Within the for loop, it uses the pow() function to calculate the power of 2 raised to the current index of the array 'a' and stores the result in variable bin
  • Finally, it prints the decimal number using printf statement and the program ends by returning 0 as the value of the main function.

Source Code

#include<stdio.h>
int main()
{
  int i,bin=0,n,a[10];
  printf("\nEnter the Binary number:");
  scanf("%d",&n);
  for(i=0;n!=0;i++)
  {
    a[i]=n%10;
    n=n/10;
  }
  n=i;
  for(i=0;i<n;i++)
  {
    bin+=a[i]*pow(2,i);
  }
  printf("%d",bin);
  return 0;
}
To download raw file Click Here

Output

Enter the Binary number:1100
Decimal Value: 12

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