Write a recursive function that converts a decimal integer to binary.


Difficulty level
This exercise is mostly suitable for students
#include<stdio.h>
#include<conio.h>

// Writing of n is decomposed of 
//  - Writing of n/2 if n > 1
//  - unit digit (0 ou 1)
void binaryrec(int n)
{
  	if (n > 1)
    		binaryrec(n/2);
  	printf("%d", n%2);
}
 
void main()
{
  	int n;


  	printf("n : ");
  	scanf("%d", &n);

  	binaryrec(n);
  	printf("\n");

	getch();
}

Back to the list of exercises
Looking for a more challenging exercise, try this one !!
Replace all occurrences of a string in an another string