C# Program to Find Product of Two Numbers using Recursion

This C# program demonstrates how to find the product of two numbers using recursion. Recursion is a technique where a function calls itself to solve a problem. In this program, we will take two integer inputs from the user and find their product using a recursive function.

Problem statement

Write a C# program that calculates the product of two numbers using recursion. The program should prompt the user to enter two integers, and then it should use a recursive function to find their product. If either of the input numbers is 0, the program should return 0 as the product.

C# Program to Find Product of Two Numbers using Recursion

using System;

class Program
    static void Main()
        Console.WriteLine("Welcome to the Product of Two Numbers Program!");

        // Input
        Console.Write("Enter the first number: ");
        int num1 = Convert.ToInt32(Console.ReadLine());

        Console.Write("Enter the second number: ");
        int num2 = Convert.ToInt32(Console.ReadLine());

        // Calculate the product using recursion
        int result = MultiplyRecursive(num1, num2);

        // Output
        Console.WriteLine($"The product of {num1} and {num2} is: {result}");

    // Recursive function to find the product of two numbers
    static int MultiplyRecursive(int num1, int num2)
        // Base case: If either number is 0, the product is 0
        if (num1 == 0 || num2 == 0)
            return 0;

        // Recursive case: Multiply num1 by (num2-1) and add num1
        return num1 + MultiplyRecursive(num1, num2 - 1);

How it works

  1. We start by taking two integer inputs, num1 and num2, from the user.
  2. The MultiplyRecursive function is called with these two numbers to find their product using recursion.
  3. Inside the MultiplyRecursive function, we have two cases:
    • Base case: If either num1 or num2 is 0, we return 0 because the product of any number and 0 is 0.
    • Recursive case: We recursively call MultiplyRecursive with num1 and num2 - 1 and add num1 to the result. This effectively simulates multiplication by repeatedly adding num1 to itself num2 times.
  4. The result is displayed as the product of the two input numbers.

Input / Output