Q:

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

belongs to collection: C# Basic Programs | basics

0

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

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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 number1number2, 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.

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C# Basic Programs | basics

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
C# program to print the edge values using Pow() me... >>
<< C# program to print Floyd\'s triangle...