|
1 | 1 | /**
|
2 |
| - * Modified 07/12/2017, Kyler Smith |
3 |
| - * |
4 |
| - */ |
| 2 | +* Modified 24/05/2023, Indrranil Pawar |
| 3 | +* |
| 4 | +* C program that converts a binary number to its decimal equivalent. |
| 5 | +*/ |
5 | 6 |
|
6 | 7 | #include <stdio.h>
|
7 | 8 |
|
8 | 9 | int main()
|
9 | 10 | {
|
10 |
| - int remainder, number = 0, decimal_number = 0, temp = 1; |
11 |
| - printf("\n Enter any binary number= "); |
12 |
| - scanf("%d", &number); |
| 11 | + int binary_number, decimal_number = 0, temp = 1; |
13 | 12 |
|
14 |
| - // Iterate over the number until the end. |
15 |
| - while (number > 0) |
| 13 | + // Input the binary number |
| 14 | + printf("Enter any binary number: "); |
| 15 | + scanf("%d", &binary_number); |
| 16 | + |
| 17 | + // Convert binary to decimal |
| 18 | + while (binary_number > 0) |
16 | 19 | {
|
17 |
| - remainder = number % 10; |
18 |
| - number = number / 10; |
19 |
| - decimal_number += remainder * temp; |
20 |
| - temp = temp * 2; // used as power of 2 |
| 20 | + // Extract the rightmost digit of the binary number |
| 21 | + int digit = binary_number % 10; |
| 22 | + |
| 23 | + // Multiply the rightmost digit with the corresponding power of 2 and add to the decimal number |
| 24 | + decimal_number += digit * temp; |
| 25 | + |
| 26 | + // Remove the rightmost digit from the binary number |
| 27 | + binary_number /= 10; |
| 28 | + |
| 29 | + // Increase the power of 2 for the next digit |
| 30 | + temp *= 2; |
21 | 31 | }
|
22 | 32 |
|
23 |
| - printf("%d\n", decimal_number); |
| 33 | + // Output the decimal equivalent |
| 34 | + printf("Decimal equivalent: %d\n", decimal_number); |
| 35 | + |
| 36 | + return 0; |
24 | 37 | }
|
0 commit comments