Program to convert binary to decimal using while loop

Problem statement:- Program to convert binary to a decimal using while loop.

Data requirement:-

   Input Data:- binary

  Output Data:-
decimal

Program in C

Here is the source code of the C Program to convert binary to a decimal using a while loop.

Code:

#include <stdio.h>
#include <math.h>
int
main ()
{
   int binary;
    printf("Enter Binary number:");
    scanf("%d", &binary);
   int decimal= 0, temp = 0, reminder;
    while (binary!=0)
    {
        reminder = binary % 10;
        binary = binary / 10;
        decimal = decimal + reminder*pow(2,temp);
        temp++;
    }

    printf("Decimal number is: %d",decimal);
    return 0;
}

Input/Output:
Enter Binary number:
1011110
Decimal number is: 94

Program in C++

Here is the source code of the C++ Program to convert binary to a decimal using a while loop.

Code:

#include <iostream>
#include<cmath>
using namespace std;
int
main ()
{
   int binary;
    cout<<"Enter Binary number:";
     cin>>binary;
   int decimal= 0, temp = 0, reminder;
    while (binary!=0)
    {
        reminder = binary % 10;
        binary = binary / 10;
        decimal = decimal + reminder*pow(2,temp);
        temp++;
    }

    cout<<"Decimal number is: "<<decimal;
    return 0;
}

Input/Output:
Enter Binary number:
111101
Decimal number is: 61

Program in Java

Here is the source code of the Java Program to convert binary to a decimal using a while loop.

Code:

import java.util.Scanner;
public class BinaryToDecimal {

public static void main(String[] args) {
Scanner cs=new Scanner(System.in);
int binary;
    System.out.println("Enter Binary number:");
    binary=cs.nextInt();
   int decimal= 0, temp = 0, reminder;
    while (binary!=0)
    {
        reminder = binary % 10;
        binary = binary / 10;
        decimal = (int) (decimal + (reminder*Math.pow(2,temp)));
        temp++;
    }
    System.out.println("Decimal number is: "+decimal);
cs.close();
}
}

Input/Output:
Enter Binary number:
110110
Decimal number is: 54

Program in Python

Here is the source code of the Python Program to convert binary to a decimal using a while loop.

Code:

print("Enter Binary number:")
binary=int(input())
decimal= 0
temp = 0
while (binary!=0):

        reminder = binary % 10
        binary = binary // 10
        decimal = decimal + reminder*pow(2,temp)
        temp=temp+1
print("Decimal number is: ",decimal) 

Input/Output:
Enter a Decimal Number: 
5
The Binary Number is:  101





Post a Comment

0 Comments