Get Update on recent Technology & Programming

Wednesday, 15 November 2017

C Program to convert a binary number to a decimal number

Posted by   on Pinterest

C Program to convert a binary number to a decimal number







#include<stdio.h>

int main(void)

{

 int n,nsave,rem,d,j=1,dec=0;

 printf("Enter the number in binary : ");

 scanf("%d",&n);

 nsave=n;

 while(n>0)

 {

  rem=n%10; /*taking last digit of n*/

  d=rem*j;

  dec+=d;

  j*=2;

  n/=10;  /*skipping last digit of n*/

 }

 printf("Binary number = %d, Decimal number = %d\n",nsave,dec);

 return 0;

}


The given code is a C program that converts a binary number entered by the user into its decimal equivalent. Here's a breakdown of the code:


The program includes the necessary header file stdio.h and defines the main function. It declares several variables:

  • n represents the input binary number.
  • nsave stores a copy of the original input for printing later.
  • rem is used to store the remainder when dividing the number by 10.
  • d stores the calculated value of each digit.
  • j is used to calculate the power of 2 for each digit.
  • dec holds the final decimal value.

The program prompts the user to enter a binary number and reads it using the scanf function. The original value of n is saved in nsave.




The program uses a while loop to convert the binary number to decimal. In each iteration, it performs the following steps:

  • Calculates the remainder (rem) when dividing n by 10 to obtain the last digit.
  • Multiplies the remainder by j to calculate the decimal value of the current digit.
  • Adds the calculated value (d) to the dec variable.
  • Multiplies j by 2 to increase its power for the next digit.
  • Divides n by 10 to remove the last digit.

Once the loop finishes, the decimal value is stored in dec.


Finally, the program displays the original binary number (nsave) and the converted decimal number (dec) using the printf function. It then returns 0 to indicate successful program execution.

Overall, this code takes a binary number as input and converts it into its decimal equivalent.

2 comments:
Write comments
  1. This is my first time i visit here and I found so many interesting stuff in your blog especially it's discussion, thank you. recover lost bitcoins

    ReplyDelete
  2. minecraft coding I would like to say that this blog really convinced me to do it! Thanks, very good post.

    ReplyDelete

Hey, we've just launched a new custom color Blogger template. You'll like it -
Join Our Newsletter