155: Write a program that converts an integer e.g. 5 to its binary form. Print out binary in the following format: Enter decimal no: 5 Binary is: 101
// Write a program that converts an integer e.g. 5 to its binary form.
// Print out binary in the following format:
// Enter decimal no: 5
// Binary is: 101
#include <iostream>
using namespace std;
int main()
{
cout << "Muhammad Umar Chaudhry" << endl;
cout << "SU92-BSCSM-S23-007" << endl;
cout << "Question # 13" << endl
<< endl;
int num;
cout << "Enter decimal no: ";
cin >> num;
// getting reverse binary
int temp_rem, temp_binary = 0;
while (num > 0)
{
temp_rem = num % 2;
temp_binary = temp_binary * 10 + temp_rem;
num = num / 2; // in binary every number is divided by 2 not 10
}
// reversing the number to get actual binary
int rem, binary = 0;
while (temp_binary > 0)
{
rem = temp_binary % 10;
binary = binary * 10 + rem;
temp_binary = temp_binary / 10;
}
cout << "Binary is: " << binary << endl;
return 0;
}
Comments
Post a Comment