C# - Multiplication of Two Numbers Using Left-Shift Operator

Here, we are going to learn how to calculate the multiplication of two numbers using the left shift operator in C#? By Nidhi Last updated : April 15, 2023

Here, we will create the multiplication using the left shift operator, as we know that multiplication with is number is equivalent to the multiplication with powers of 2, and we can obtain the powers of 2 using the left shift (<<) operator.

C# program to calculate the multiplication of two numbers using the left shift operator

The source code to calculate the multiplication of two numbers using a left-shift operator is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.

//C# program to calculate the multiplication of 
//two binary numbers using left shift operator.

using System;

class MathEx
{
    static int multiplyUsingLeftShift(int num1, int num2)
    {
        int result = 0;
        int count  = 0;

        while (num2 > 0)
        {
            if (num2 % 2 == 1)
                result = result +(num1 << count);

            num2 = num2 / 2;
            count++;
        }
        return result;
    } 
    public static void Main()
    {
        int number1=0;
        int number2=0;
        int product=0;
 
        Console.Write("Enter the 1st number: ");
        number1 = int.Parse(Console.ReadLine());

        Console.Write("Enter the 2nd number: ");
        number2 = int.Parse(Console.ReadLine());

        product = multiplyUsingLeftShift(number1, number2);
        Console.WriteLine("Product of two numbers: {0}", product);
    }
}

Output

Enter the 1st number: 12
Enter the 2nd number: 7
Product of two numbers: 84
Press any key to continue . . .

Explanation

Here, we created a class MathEx that contains two static methods multiplyUsingLeftShift() and Main() method. The multiplyUsingLeftShift() method is used to multiple of two numbers using the left shift operator.

As we know that multiplication with is number is equivalent to the multiplication with powers of 2, and we can obtain the powers of 2 using left shift (<<) operator.

In the Main() method, we created three variables number1, number2, and product initialized with 0. Then read the values of number1 and number2 after that calculate the multiplication and print the result on the console screen.

C# Basic Programs »


Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.