difference between recursive and non recursive

Hello,
I am studying recursion but I didn't get that how do we know which program is made recursively and which is not .I will be thankfull if someone explains me this .
A recursive function is a function that calls itself. A non-recursive one is the one that doesn't.
Can you give an example of such kind of program.I will be glad.
A common example of recursion is a factorial function:
1
2
3
4
5
6
int factorial(int n)
{
   if(n == 1)
      return 1;
   return n*factorial(n - 1);
}


http://www.cplusplus.com/forum/articles/2231/
Sir,
my question is how do we know if the program is recursive or non revursive.
please give example of these two programs.
Is a function that can be recursive, not a program
so you mean If a program has a function other than main() It is recursive and a program that has only one int main() function then it is non recursive.
Sigh.

No.

If a program contains at least one function that calls itself, then it is recursive.
If the program does not contain any such functions, then it is not recursive.

A program is never recursive.
A function may be recursive.

Recursion:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
using namespace std;

void print( int i )
  {
  if (i == 0) return;
  cout << i << endl;
  print( i - 1 );
  }

int main()
  {
  print( 10 );
  return 0;
  }


Not recursive:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
using namespace std;

void print( int i )
  {
  while (i > 0)
    {
    cout << i << endl;
    i = i - 1;
    }
  }

int main()
  {
  print( 10 );
  return 0;
  }

Good luck!
This program has a function and it calls itself then how is it not recursive.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
using namespace std;

void print( int i )
  {
  while (i > 0)
    {
    cout << i << endl;
    i = i - 1;
    }
  }

int main()
  {
  print( 10 );  //function calls itself
  return 0
Last edited on
You're too tired. Go get some sleep and come back. ;-)

Line 15 is in the main() function.
main() calls print().
print() does not call itself.

Hope this helps.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
using namespace std;

void print( int i )
  {
  if (i == 0) return;
  cout << i << endl;
  print( i - 1 );
  }

int main()
  {
  print( 10 );  // print does not call itself ,main calls print() ,Then how come this is recursive ?
  return 0;
  }
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
using namespace std;

void print( int i )
  {
  if (i == 0) return;
  cout << i << endl;
  print( i - 1 );//if print doesn't call itself what is this?
  }

int main()
  {
  print( 10 );
  return 0;
  }
Thank you Buzzy and Duoas !
I got it now .

Topic archived. No new replies allowed.