Recursion example-2 (easy)


Product of n numbers read from the input.

Program:

#include<stdio.h>
int read_mul(int);                                       /*  function prototype   */
int main()
{
       int n;
       printf("enter number of numbers");
       scanf("%d",&n);                                  /* read number of numbers  */
       printf("%d",read_mul(n));                   /* print product   */
       return 0;
}
int read_mul(int n)                                      /* function definition  */
{
       if(n==0)                                  /* base case i.e., if n=0 stop recursion and return 1 */
       return 1;
       int x;                                                     /* if n is not zero read and evaluate product  */
       scanf("%d",&x);
       return x*read_mul(n-1);                      /*  recursive function call   */

}

Sample input:

5
1 2 3 4 5

Output:
120

No comments: