Exercise
Function Multiply & Multiplyr
Objective
Write two C# functions, Multiply and MultiplyR, to calculate the product of two numbers using sums. T he first version must be iterative, and the second one must be recursive.
Write Your C# Exercise
C# Exercise Example
// Import the System namespace to use basic classes like Console
using System;
class Program
{
// Function to multiply two numbers iteratively using addition
public static int Multiply(int a, int b)
{
int product = 0; // Variable to store the product
// Add 'a' to itself 'b' times to simulate multiplication
for (int i = 0; i < Math.Abs(b); i++)
{
product += a; // Add 'a' repeatedly
}
// If b is negative, the product should be negative
if (b < 0)
{
product = -product; // Negate the product
}
return product;
}
// Function to multiply two numbers recursively using addition
public static int MultiplyR(int a, int b)
{
// Base case: if b is 0, the product is 0
if (b == 0)
{
return 0;
}
else
{
// Recursive case: add 'a' recursively
return a + MultiplyR(a, b - 1);
}
}
// Main function to test the Multiply and MultiplyR functions
public static void Main()
{
// Test the Multiply function
Console.WriteLine("Iterative Multiply:");
Console.WriteLine("3 * 4 = " + Multiply(3, 4)); // Expected output: 12
Console.WriteLine("-3 * 4 = " + Multiply(-3, 4)); // Expected output: -12
Console.WriteLine("3 * -4 = " + Multiply(3, -4)); // Expected output: -12
Console.WriteLine("0 * 4 = " + Multiply(0, 4)); // Expected output: 0
// Test the MultiplyR function
Console.WriteLine("\nRecursive Multiply:");
Console.WriteLine("3 * 4 = " + MultiplyR(3, 4)); // Expected output: 12
Console.WriteLine("-3 * 4 = " + MultiplyR(-3, 4)); // Expected output: -12
Console.WriteLine("3 * -4 = " + MultiplyR(3, -4)); // Expected output: -12
Console.WriteLine("0 * 4 = " + MultiplyR(0, 4)); // Expected output: 0
}
}