Question 1: Write a program that reads in a positive integer (decimal number) wi
ID: 3705278 • Letter: Q
Question
Question 1: Write a program that reads in a positive integer (decimal number) with maximum 5 digits and display its equivalent binary number. You can watch this video to know how to convert a decimal number to a binary number. https://www.youtube.com/watch?v ZROpC6 iW5Q If the input is invalid, please keep on asking until you get the correct input. Hint: you can use either a recursive function or an iteration (loop) with an array. Example: Bold means user input Enter a positive integer with maximum 5 digits: 123456 Invalid input. Try again. Enter a positive integer with maximum 5 digits: 25 Decimal 25 Binary 11001.Explanation / Answer
Since no specific language is mentioned, I have written this code in C++
#include <iostream>
using namespace std;
int toBinary(int num)
{
if (num == 0)
return 0;
else
return (num % 2 +
10 * toBinary(num / 2));
}
int main() {
int n,counter=0,temp;
cout<<"Enter a Positive number maximum of 5 digits: ";
cin>>n;
temp=n;
while(temp!=0){
temp=temp/10;
counter++;
}
if(counter>5)
cout<<"Invalid Input. Try again.";
else{
cout<<"decimal "<<n<<"= "<<toBinary(n);
}
return 0;
}
Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.