Write a C++ program to convert a number from decimal to binary using while loop
- User
Write a C++ program to convert a number from decimal to binary using while loop
- Assistant
Here is a C++ program that converts a number from decimal to binary using a while loop:
c++#include <iostream> using namespace std; int main() { int num, rem, binary = 0, base = 1; cout << "Enter a decimal number: "; cin >> num; while (num > 0) { rem = num % 2; binary = binary + rem * base; num = num / 2; base = base * 10; } cout << "Binary equivalent: " << binary << endl; return 0; }In this program, we first initialize the
numvariable to store the decimal number entered by the user. We also initializeremto store the remainder of the division,binaryto store the binary equivalent, andbaseto calculate the place value of the binary digits.Then we use a while loop to keep dividing the by 2 until it becomes 0. Inside the loop, we calculate the remainder and update and accordingly. We multiply by the to place it in the correct position in the binary number. After each iteration, we update the by multiplying it by 10 to move to the next place value.