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

Here, we are going to learn how to calculate the multiplication of two numbers using the left shift operator in C#?
Submitted by Nidhi, on October 03, 2020

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.

Program:

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.






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.