Write a program that prompts a user to enter a binary number (0s and 1s). Your p
ID: 3624290 • Letter: W
Question
Write a program that prompts a user to enter a binary number (0s and 1s). Your program then checks
that it is indeed a binary number, meaning that it contains only 0s and 1s. If it is not the case, your
program should print a message that the number is not a valid binary number. If it is a valid binary
number then your program should count how many 1s are in the word and output the count.
Following is a sample ,the program should be like this:
-------------------------------------------------------------------
Welcome to Shi's Binary Number Evaluator
-------------------------------------------------------------------
Please enter a binary number and I will tell you how many 1s there are: 10101010
There are 4 1s in the binary number 10101010
Thank you for using Shi's Binary Number Evaluator
Explanation / Answer
// Perfectly Worked Under Dev C++ NOW U CAN CHECK
// Previous Program also working fine only thing is u are not stopping window to see result.
#include <iostream>
#include <string>
#include<conio.h>
using namespace std;
int main()
{
string inString; //user input string
//to count number of 1s
int count=0;
//to check if number is invalid
int check=0;
int i=0;
//banner
cout<<"----------------------------------------------------"<<endl;
cout<<"Welcome to Binary Number Evaluator"<<endl;
cout<<"----------------------------------------------------"<<endl<<endl;
//getting user input
cout<<endl<<"Please enter a binary number and I will tell you how many 1s there are: ";
cin>>inString;
//loop till the length of string
while(i<inString.length())
{
//if the current bit is not 1 or 0
if(inString[i]!='1' && inString[i]!='0')
{
cout<<endl<<"That is not a valid binary number"<<endl;
check=1; //invalid number
break; //break loop
}
else if(inString[i]=='1')
{
count++; //counting 1s
}
i++;
}
//displaying result
if(check==0)
cout<<endl<<"There are "<<count<<" 1s in binary number "<<inString<<endl;
cout<<"Thank you for using Binary Number Evaluator"<<endl<<endl;
getch();
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.