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.

advertisement
advertisement

Sanfoundry Global Education & Learning Series – 1000 C Tutorials.

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

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.