Recursion

This is a discussion on Recursion within the C++ Programming forums, part of the General Programming Boards category; How would I write a c program which will recursively compute the product of all even numbers greater than 0 ...

  1. #1
    cwd
    cwd is offline
    Registered User
    Join Date
    Sep 2001
    Posts
    9

    Recursion

    How would I write a c program which will recursively compute the product of all even numbers greater than 0 and <= N, for values of N={16,7,9}, and print the results to an output file. For instance, if N=5, the product would be 4 x 2=8.

    here is what I have so far,

    #include <stdio.h>

    main()
    {

    }

    void recurse()
    {
    static count=1;
    int n;
    int array[n]={16,17,9};
    printf("%d",count);
    count++;
    n++;
    }

  2. #2
    zen
    zen is offline
    of Zen Hall zen's Avatar
    Join Date
    Aug 2001
    Posts
    1,007
    A recursive function calls itself. One method would be -

    1. Pass in the value 16,7 or 9 into your function.

    2. Check to see if it's even and if not minus one.

    3. If this value is not zero store the value of this value multiplied by two less than itself.

    4. If the value is not zero pass this value into the function (recursively) and add the return value to the value obtained in the previous step.

    5. Return the value.

    Code:
    int recurse(int num)
    {
    	if(num%2!=0)
    		num--;
    
    	int r=0;
    	if(num>0)
    	r=num*(num-2)+recurse(num-2);
    
    	return r;
    }
    zen

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Template Recursion Pickle
    By SevenThunders in forum C++ Programming
    Replies: 20
    Last Post: 02-05-2009, 08:45 PM
  2. convert Recursion to linear can it be done
    By umen242 in forum C++ Programming
    Replies: 2
    Last Post: 10-15-2008, 02:58 AM
  3. Recursion... why?
    By swgh in forum C++ Programming
    Replies: 4
    Last Post: 06-09-2008, 09:37 AM
  4. a simple recursion question
    By tetra in forum C++ Programming
    Replies: 6
    Last Post: 10-27-2002, 09:56 AM
  5. To Recur(sion) or to Iterate?That is the question
    By jasrajva in forum C Programming
    Replies: 4
    Last Post: 11-07-2001, 08:24 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21