Added exercise 4.27
[Cpp-Deitel-Exercises.git] / Chapter-4 / 4-27.cpp
blob4e9d57f6d49f4b5dca59d4a3d6994110a302f0ef
1 /*C++ How to Program, 9/E, by Paul Deitel & Harvey Deitel.
3 Solution of exercise 4.27:
4 (Printing the Decimal Equivalent of a Binary Number) Input an integer
5 containing only 0s and 1s (i.e., a "binary" integer) and print its decimal
6 equivalent. Use the modulus and division operators to pick off the "binary"
7 number's digits one at a time from right to left. Much as in the decimal
8 number system, where the rightmost digit has a positional value of 1, the next
9 digit left has a positional value of 10, then 100, then 1000, and so on, in
10 the binary number system the rightmost digit has a positional value of 1, the
11 next digit left has a positional value of 2, then 4, then 8, and so on. Thus
12 the decimal number 234 can be interpreted as 2 * 100 + 3 * 10 + 4 * 1. The
13 decimal equivalent of binary 1101 is 1 * 1 + 0 * 2 + 1 * 4 + 1 * 8 or 1 + 0 +
14 4 + 8, or 13. [Note: To learn more about binary numbers, refer to Appendix D.]
16 Written by Juan Carlos Moreno (jcmhsoftware@gmail.com), 2023-03-08.
19 #include <iostream>
21 using namespace std;
23 int main()
25 int binary_number, digit, number, decimal_equivalent = 0;
26 int power_of_ten = 1000000000, power_of_two = 1024;
28 cout << "Input the binary integer (only 0s and 1s): ";
29 cin >> binary_number;
30 number = binary_number;
32 while ((power_of_ten >= 1) && (power_of_two >= 1))
34 digit = number / power_of_ten;
35 number = number % power_of_ten;
36 power_of_ten = power_of_ten / 10;
37 power_of_two = power_of_two / 2;
38 decimal_equivalent = decimal_equivalent + digit*power_of_two;
41 cout << "The decimal equivalent of binary " << binary_number << " is "
42 << decimal_equivalent << "." << endl;
44 return 0;