C language converts decimal numbers to binary (recursive, specified number of digits)

Source: Internet
Author: User
Tags define function

/* Use recursive algorithm */

#include <stdio.h>
void B (int n)//define function
{
if (n! = 0)
{
printf ("%d", n%2);
B (N/2);
}
}
int main ()
{

int n;
printf ("Input number:");

scanf ("%d", &n);

printf ("Output binary:");

B (n); Prints the binary number in the B () function
return 0;
}

/* Define an array and use Do{}while () to assign values */

#include <stdio.h>
int main ()
{
int A;
Char s[20];
int i = 0, rem;
printf ("Input number:");
scanf ("%d", &a);
Do
{
rem = a% 2;

A = A/2;
S[i] = REM;
i++;
} while (A! = 0);
printf ("Output binary:");
while (i > 0)
printf ("%d", s[--i]);//

return 0;
}

/* The code can implement a fixed output number */

#include <stdio.h>
#define N 32//fixed number of digits
int main ()
{
int Arr[n] = {0};//The array is initialized to 0 (the output 0 is filled when the number of bits is not satisfied)
int i;
int n;
printf ("Input number:");
scanf ("%d", &n);
for (i = N-1; I >=0; i--)//array from backward to forward assignment
{
Arr[i] = n% 2;
n = N/2;
}

printf ("Output binary:");
for (i = 0; I <= N-1; i++)
{
printf ("%d", arr[i]);
}
return 0;
}

C language converts decimal numbers to binary (recursive, specified number of digits)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.