Course contentsShow
← C
Lesson 152 of 1,2193. Operators and ExpressionsFree lesson

Multiplication `*` mechanics

Multiplication * mechanics

What you'll learn: How to use the asterisk symbol to perform multiplication and how C handles different number types during the calculation.

The Star of the Show

In the world of C, we don't use the letter "x" or a dot to multiply numbers. Instead, we use the asterisk symbol (*). Think of the * as a specialized factory machine: you feed it two values, it cranks the gears, and it spits out a single product.

Whether you are calculating the area of a room or doubling a player's score in a game, the syntax remains the same. You place the operator between two operands, like this: result = a * b;.

Mixing Integers and Decimals

C is very logical about how it calculates products. The "flavor" of your result depends entirely on the "flavor" of the numbers you are multiplying.

  1. Integer x Integer: If you multiply two whole numbers (integers), the result is always a whole number. 5 * 3 will always be 15.
  2. Floating Point x Floating Point: If you multiply two decimals, you get a decimal. 2.5 * 2.0 results in 5.0.
  3. The Mixed Match: If you multiply an integer by a decimal, C "promotes" the integer to a decimal behind the scenes to keep the precision. For example, 10 * 0.5 will result in 5.0.

Multiplication in Action

Here is how you might see this in a real program. Notice how we can multiply literal numbers, variables, or even the results of other calculations.

#include <stdio.h>

int main() {
    int cookiesPerBox = 12;
    int numberOfBoxes = 5;
    double pricePerCookie = 1.50;

    // Multiplying two integers
    int totalCookies = cookiesPerBox * numberOfBoxes;

    // Multiplying an integer and a double
    double totalCost = totalCookies * pricePerCookie;

    printf("Total cookies: %d\n", totalCookies);
    printf("Total cost: $%.2f\n", totalCost);

    return 0;
}

Watch Out for Overflow

When using multiplication, remember that computers have limits. If you multiply two very large integers, the result might exceed the storage capacity of that variable type. This is called "overflow." It’s like trying to fit a gallon of water into a pint glass; the excess just spills away, leaving you with a strange, incorrect number. Always ensure your variable type (like int or long) is big enough to hold the potential product.

Key takeaway

Use the * operator to multiply values, keeping in mind that mixing integers with decimals will result in a decimal (floating-point) answer.