Skip to content

Commit 6915d59

Browse files
authored
feat: improve conversions/binary_to_decimal.c (#1262)
* Update binary_to_decimal.c 1. Removed the unused variable remainder. 2. Changed the variable name number to binary_number for clarity. 3. Removed the initialisation of number and temp since they are assigned values later. 4. Removed the newline character from the printf statement to improve readability. 5.Added a return statement at the end of main function. * Update binary_to_decimal.c
1 parent a555d2d commit 6915d59

File tree

1 file changed

+26
-13
lines changed

1 file changed

+26
-13
lines changed

conversions/binary_to_decimal.c

+26-13
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,37 @@
11
/**
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+
*/
56

67
#include <stdio.h>
78

89
int main()
910
{
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;
1312

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)
1619
{
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;
2131
}
2232

23-
printf("%d\n", decimal_number);
33+
// Output the decimal equivalent
34+
printf("Decimal equivalent: %d\n", decimal_number);
35+
36+
return 0;
2437
}

0 commit comments

Comments
 (0)