Convert Decimal to Binary using While Loop in C++


This is a C++ program that converts a decimal number to its binary equivalent. Let's go through the program step-by-step:

  • The program starts by including the necessary header file iostream.
  • The using namespace std statement is used to avoid writing std:: before every standard library function.
  • The main() function is the entry point of the program.
  • Inside main(), the program declares some integer variables n, r, m, and bin.
  • The user is prompted to enter the decimal number to be converted.
  • The program then enters a while loop that continues until the decimal number becomes zero.
  • Inside the while loop, the program takes the modulus of the decimal number with respect to 2 and stores it in the variable r.
  • The program then calculates the binary value by adding the product of r and m to the variable bin. The variable m is used to keep track of the place value of the binary digit.
  • The variable n is updated by dividing it by 2.
  • The program then continues the while loop with the new value of n.
  • Once the while loop completes, the program prints the binary value.

Overall, the program correctly converts the decimal number to its binary equivalent and prints the result to the console. However, the variable m is initialized to 1 but is not necessary for the conversion. The program could instead initialize bin to 0 and multiply it by 2 instead of m in step 8. Additionally, the program assumes that the user will enter a non-negative integer, so it may not work correctly for negative numbers or non-integer inputs. It's a good practice to add error checking to ensure that the program behaves correctly for all possible inputs.

Source Code

#include<iostream>
using namespace std;
int main()
{
    int n,r,m=1,bin=0;
    cout<<"\nEnter the Number : ";
    cin>>n;
    while(n!=0)
    {
        r=n%2;
        bin=bin+(r*m);
        m=m*10;
        n=n/2;
    }
    cout<<"\nBinary Value : "<<bin;
    return 0;
}
To download raw file Click Here

Output

Enter the Number : 12234
Binary Value : 757986226

Program List


Flow Control

IF Statement Examples


Switch Case


Goto Statement


Break and Continue


While Loop


Do While Loop


For Loop


Friend Function in C++


String Examples


Array Examples


Structure Examples


Structure & Pointer Examples


Structure & Functions Examples


Enumeration Examples


Template Examples


Functions


Inheritance Examples

Hierarchical Inheritance


Hybrid Inheritance


Multilevel Inheritance


Multiple Inheritance


Single Level Inheritance


Class and Objects

Constructor Example


Destructor Example


Operator Overloading Example


Operator and Function Example


List of Programs


Pointer Examples


Memory Management Examples


Pointers and Arrays


Virtual Function Examples