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.
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.
int
, double
) for the multiplication operator.using System; // 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
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.
ToString
format pattern.using System; // 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
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.
We looked at multiplying numbers. The multiplication operator is the star character. The compound operator is represented by the "*=" characters.