Ad

Chapter - 6: Functions And Pointers

A positive integer is entered through the keyboard, write a function to find the binary equivalent of this number:


Ad
G
Sections
6
Exercises

(1) Without using recursion
(2) Using recursion


#include<stdio.h>
#include<conio.h>

void rec_bin(int);
void nonrec_bin(int);

int main()
{
	printf("\n\nUsing recursion binary Equivalent of 12 is : ");
	rec_bin(12);

	printf("\n\nWithout using recursion binary Equivalent of 18 is : ");
	nonrec_bin(18);
	_getch();
	return 0;
}

//non recursive function
void nonrec_bin(int num)
{
	int sum = 0;
	for (; num; num /= 2)
	{
		//Next digit will placed at first position.
		sum += num % 2;
		sum *= 10;
	}
	printf("%d", sum);
}

//recursive function
void rec_bin(int num)
{
	if (num == 0)
		return;
	rec_bin(num / 2);
	printf("%d", num % 2);
}
Ad

© 2024 Garbage Valuegarbage value logo