
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Binary Representation of a Given Number in C++
A binary number is a number that consists of only two digits 0 and 1. For example, 01010111.
There are various ways to represent a given number in binary form.
Recursive method
This method is used to represent a number in its binary form using recursion.
Algorithm
Step 1 : if number > 1. Follow step 2 and 3. Step 2 : push the number to a stand. Step 3 : call function recursively with number/2 Step 4 : pop number from stack and print remainder by dividing it by 2.
Example
#include<iostream> using namespace std; void tobinary(unsigned number){ if (number > 1) tobinary(number/2); cout << number % 2; } int main(){ int n = 6; cout<<"The number is "<<n<<" and its binary representation is "; tobinary(n); n = 12; cout<<"\nThe number is "<<n<<" and its binary representation is "; tobinary(n); }
Output
The number is 6 and its binary representation is 110 The number is 12 and its binary representation is 1100
Advertisements