You are here:

C/C programming

Advertisement


Question
I would like to know the difference between iteration and recursion. Also the way to expalin to recursion in a simple way

Answer

Hi dear Jasmin !

 Although both iteration and recusion are almost equvalent , they are slightly differs in architecture , where as the purpose of reucursion an d iteration in computing environment is same , iteration describes the style of programming used in imperative programming languages. This contrasts with recursion, which has a more declarative approach.

presenting you sample code to illustrate iteration and recursion !

#include<stdio.h>

/* Prog 1 using iteration */
void main()
{
  int i ,n, fact = 1;
  printf("Enter n :");
  scanf("%d" , &n);
  for( i = 1 ; i < n ; i++)
     fact += fact*i;
  printf("%d" , fact);
}

/* Prog 2 using recursion */
int fact(int n)
{
  if ( n == 0 )
     return 1;
  else
     return n* fact( n-1);
}
void main()
{
  printf("%d" , fact(5));
}

Perhaps output of both programs remains same . In the first programme ,the value of i varies over time from 1 to n , while in recursion input parameter changes over time !

In short iteration and recursion can be defined as "an object revolves another object " and " an object rotates and revolves another object " respectively !

Feel free to post follow up for further quries !

Thanks and Regards!
Prince M. Premnath.  

C

All Answers


Answers by Expert:


Ask Experts

Volunteer


Prince M. Premnath

Expertise


I'm sure that I can solve any doubts in Turbo C ,Graphics Programing ,Mouse, Hardware Programming ,File System ,Interrupts, BIOS handling , TSR Programming , General Concepts in C Language, handling inline Assembly statements

Experience

Research over 6+ Years

Organizations
CG-VAK Softwares and Exports Limited

Education/Credentials
Masters in Computer Applications

©2012 About.com, a part of The New York Times Company. All rights reserved.