GoogleTag

Google Search

[Programming] Question 18: Write a Program to convert the binary number into a decimal number

Learn how to write a C program to convert a binary number into its decimal equivalent. This guide provides a step-by-step explanation of how to process a binary number, compute its decimal value using bitwise operations or mathematical calculations, and output the result. The tutorial includes sample code and detailed instructions to help you understand and implement the conversion effectively in C.

#include <stdio.h>

int main() {
	long long binaryNumber;
	int decimalNumber = 0, i = 0, remainder;

	printf("Enter a binary number: ");
	scanf("%lld", &binaryNumber);

	while (binaryNumber != 0) {
		remainder = binaryNumber % 10;
		binaryNumber /= 10;
		decimalNumber += remainder * pow(2, i);
		++i;
	}

	printf("Decimal equivalent: %d\n", decimalNumber);

	return 0;
} 

Inside the main() function:

- A long long variable `binaryNumber` is declared to store the binary number entered by the user.

- Integer variables `decimalNumber`, `i`, and `remainder` are declared to store the equivalent decimal number, index, and remainder respectively.

- The user is prompted to enter a binary number.

- Using a while loop, each digit of the binary number is extracted from right to left.

- For each digit, the decimal equivalent is calculated using the formula: `decimalNumber += remainder * pow(2, i)`.

- Finally, the decimal equivalent is printed to the console.



Featured Posts

SQL Interview Questions Topics

 SQL Topics to prepare for interviews,   SQL Basics: Introduction to SQL SQL Data Types DDL (Data Definition Language): C...

Popular Posts