3.17 END OF CHAPTER PROGRAMS

Problem: Write a program to find the decimal value of a 4-bit binary string.

Solution: See Program 3.10.

Program 3.10 Converting binary string to decimal number

// binary1.cpp#include<IOSTREAM.H>#include<conio.h>//long factor(int n ) ;int main(){ char box[10];  int sum, i;    cout << “<---binary1.out--->” << endl ;    cout <<“Give 4 bit binary string:” ;   cin >>box;sum = 0;for (i=0;i<4;i++)        { sum = sum*2;          if (box[i] == ‘1’) sum = sum + 1;        }cout <<“equivalent decimal number is ” << sum << endl;   getch();   return 0;}

If you run this program, you will get the following output:

 

OUTPUT  <---binary1.out--->  Give 4 bit binary string:1100  equivalent decimal number is 12

Get Object Oriented Programming with C++, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.