# Efficiency of Recursion vs Iteration in C

«
»
Question: Which is more Efficient in C Programming – Recursion OR Iteration?

Answer: In general, recursion is slow, exhausting computer’s memory resources while iteration performs on the same variables and so is efficient. But recursion on the other hand, in some situations, offers convenient tool than iterations. Let’s take an example of a program below which converts integers to binary and displays them.

```/*
* int2bin_thru_recur.c -- program converts integer to binary using
* recursion
*/
#include <stdio.h>
void int2bin(int);

int main(void)
{
int num;

printf("Program converts integer to binary...\n");
printf("Enter some positive integer: (q to quit)\n");
while (scanf("%d", &num) == 1) {
int2bin(num);
printf("\nEnter some positive integer: (q to quit)\n");
}
printf("Thank you!\n");
return 0;
}

void int2bin(int n)
{
int bit;

if (n >= 2) {
bit = n % 2;
int2bin(n / 2);
printf("%d", bit);
return;
}
else {
bit = n;
printf("%d", bit);
return;		/* function type is void */
}
}```

Output of the program when compiled on Linux System.

```Program converts integer to binary...
Enter some positive integer: (q to quit)
12
1100
Enter some positive integer: (q to quit)
44
101100
Enter some positive integer: (q to quit)
123
1111011
Enter some positive integer: (q to quit)
654
1010001110
Enter some positive integer: (q to quit)
q
Thank you!```

While same job when performs using loop requires, in one of approaches, all previous values to be stored in an array and print the values in reverse order.

Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!

Sanfoundry Global Education & Learning Series – 1000 C Tutorials.

If you wish to look at all C Tutorials, go to C Tutorials. 