Multiply NumbersMultiply ints with the multiply operator. Consider aspects of multiplication.
C#
Multiply. The multiply operator is an asterisk. It computes the product of 2 numbers. Multiplication is a standard operation: C# is the same as other languages. This operator obeys the operator precedence rules. So we can mix additions and multiplications and multiplication will come first.
Divide
An example. We compute the product of 2 operands using the multiplication operator. You can multiply any 2 numbers that can be implicitly converted to compatible types.
Detail The C# language specification defines many predefined arguments (int, double) for the multiplication operator.
int
double
Here We compute the product of 100 and 5. The number 100 is a constant. The value 5 was determined at program runtime.
Note Because one value was not known at compile-time, the C# compiler cannot compute the product of the operands statically. using System; class Program { static void Main() { // // Use a constant local and a dynamically // ... determined integer as operands. // const int operand1 = 100; int operand2 = int.Parse("5"); // // Compute the product and store it in a local variable. // int product = operand1 * operand2; Console.WriteLine(product); // // You can check the value of a multiple expression in an if-statement. // if ((operand1 * operand2) == 500) { Console.WriteLine("Is equal"); } // // You can multiply a number against itself. // operand2 *= 2; Console.WriteLine(operand2); // Now equal to 10 not 5. } }
500 Is equal 10
Table. Next we write a multiplication table program. It uses two nested for-loops. The numbers we loop over are in the range 1 to 9.
Info In the innermost statement, we use the multiplication operator and then use a ToString format pattern.
for
Also A newline is printed at the end of each nine numbers in the loop. This improves the output format.
using System; class Program { static void Main() { // Loop through all operands in the multiplication table. for (int a = 1; a < 10; a++) { for (int b = 1; b < 10; b++) { // Write the multiplied number. Console.Write((a * b).ToString("00 ")); } // New line. Console.WriteLine(); } } }
01 02 03 04 05 06 07 08 09 02 04 06 08 10 12 14 16 18 03 06 09 12 15 18 21 24 27 04 08 12 16 20 24 28 32 36 05 10 15 20 25 30 35 40 45 06 12 18 24 30 36 42 48 54 07 14 21 28 35 42 49 56 63 08 16 24 32 40 48 56 64 72 09 18 27 36 45 54 63 72 81
Operator precedence. The multiplication operator has a greater precedence than plus or minus. The rules for operator precedence in the C# language are the same as those for arithmetic.