How to find the product of 2 numbers using recursion in C#?


Firstly, set the two numbers to be multiplied.

val1 = 10;
val2 = 20;

Now cal the method to find the product.

product(val1, val2);

Under the product method, a recursive call will get you the product.

val1 + product(val1, val2 – 1)

Let us see the complete code to find the product of 2 numbers using recusion.

Example

using System;
class Calculation {
   public static void Main() {
      int val1, val2, res;
      // the two numbers
      val1 = 10;
      val2 = 20;
      // finding product
      Demo d = new Demo();
      res = d.product(val1, val2);
      Console.WriteLine("{0} x {1} = {2}", val1, val2, res);
      Console.ReadLine();
   }
}
class Demo {
   public int product(int val1, int val2) {
      if (val1 < val2) {
         return product(val2, val1);
      } else if (val2 != 0) {
         return (val1 + product(val1, val2 - 1));
      } else {
         return 0;
      }
   }
}

Updated on: 22-Jun-2020

138 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements