Navigation Menu

Currently the navigation bar is not functioning. Use the Blog Archive or the Google Custom Search to find content.

Monday 24 June 2013

C++ program to find a binary equivalent of a number using recursion

Given below is a C++ Program to find a binary equivalent of a number using recursion.

Example :

2 / 14 = 7 Quotient | 0 Remainder
2 / 7 = 3 Quotient | 1 Remainder
2 / 3 = 1 Quotient | 1 Remainder
2 / 1 = 0 Quotient | 1 Remainder

Now take all the Remainder in reverse order. Now we have 14 = 11102.

Links that you may find important :

https://en.wikipedia.org/wiki/Binary_number
http://www.mathsisfun.com/binary-number-system.html
http://acc6.its.brooklyn.cuny.edu/~gurwitz/core5/nav2tool.html

Code :
#include <iostream.h>
#include <conio.h>
#include <string.h>
#define range 8
char a[range]="00000000";
int count;
void binary(int no,int count)
{
 if(no!=0)
 {
  int k;
  k=no%2;
  no=no/2;
  if(k==0)
  a[count]=48;
  if(k==1)
  a[count]=49;
  binary(no,count+1);
 }
}
void main()
{
 int no;
 clrscr();
 cout<<"Enter number to be converted to binary : ";
 cin>>no;
 binary(no,0);
 strrev(a);
 cout<<endl<<a;
 getch();
}
Output :
Enter number to be converted to binary : 127

01111111
Note : The program above has been tested using TurboCPP. Leave a comment if you feel the program is incorrect and/or has errors and/or if the program and its output don't match. Please report about broken links.

No comments:

Post a Comment