Computers don’t mind math, and as long as you enter the numbers correctly, your C program will always do your math right with the use of operators.

A lot of C operators work exactly the way you expect them to. You use a plus sign (+) when you want to add, and you use a minus sign (-) when you want to subtract. An *expression* includes one or more operators. C programmers often use math expressions on the right side of the assignment operator when filling variables with values, like this:

totalSales = localSales + internationalSales - salesReturns;

**Note : **If you want to subtract a negative value, be sure to put a space between the minus signs, like this:

newValue = oldValue - -factor;

If you omit the space, C thinks you’re using another operator, – -, called the *decrement* operator.

You can even put a math expression inside a printf():

printf("In 3 years, I'll be %d years old.\n", age + 3);

If you want to multiply and divide, you can do so by using the * and / symbols. The following statement assigns a value to a variable using multiplication and division:

newFactor = fact * 1.2 / 0.5;

**Note : **If you put integers on *both* sides of the division symbol (/), C computes the *integer* * division result*. Study the following program to get familiar with integer division and

**regular division**.

/* This is a sample program that demonstrates math operators, and the different types of division. */ #include <stdio.h> main() { // Two sets of equivalent variables, with one set // floating-point and the other integer float a = 19.0; float b = 5.0; float floatAnswer; int x = 19; int y = 5; int intAnswer; // Using two float variables creates an answer of 3.8 floatAnswer = a / b; printf("%.1f divided by %.1f equals %.1f\n", a, b, floatAnswer); floatAnswer = x /y; //Take 2 creates an answer of 3.0 printf("%d divided by %d equals %.1f\n", x, y, floatAnswer); // This will also be 3, as it truncates and doesn't round up intAnswer = a / b; printf("%.1f divided by %.1f equals %d\n", a, b, intAnswer); intAnswer = x % y; // This calculates the remainder (4) printf("%d modulus (i.e. remainder of) %d equals %d", x, y, intAnswer); return 0; }

If you need the remainder after integer division, use C’s ** modulus operator (%)**.

ansMod = x % y; /* 4 is the remainder of 19 / 5 */

**Note : **You can’t use % between anything but integer data types.

**Order of Operators**

C doesn’t always compute math operations in the order you expect. The following expression explains it in a nutshell:

ans = 5 + 2 * 3; /* Puts 11 in ans */

C always computes multiplication before addition. C is following the ** order of operators table**. C first multiplies 2 and 3 to get 6, and then adds 5 to get 11.

Following Table lists the complete order of operators. For each level, if your expression has more than one operator from the same level, C resolves them using the associativity direction listed. So if you do multiplication and division, C performs the operation that appears first when reading left to right, and then moves on to the next operation. When it has completed a level, it moves down to the next level. As you can see in the table, *, /, and % appear before + and -. Therefore, if C sees an expression with a combination of these operators, it evaluates *, /, and % before computing + and -.

Here is a difficult expression. All the variables and numbers are integers. See if you can figure out the answer by the way C would evaluate the expression:

ans = 5 + 2 * 4 / 2 % 3 + 10 - 3; /* What is the answer? */

Figure shows how to solve for the answer, 13.

As *, /, and % all reside on the same level, they were evaluated from left to right, as dictated by the order of operators table’s Associativity column.

Suppose you want to compute the average of four variables. The following will *not* work:

avg = i + j + k + l / 4; /* Will NOT compute average! */

The reason is simple when you understand the order of operators. C computes the division first, so l / 4 is evaluated first and then i, j, and k are added to that divided result. If you want to override the order of operators, as you would do in this case, you have to learn to use ample parentheses around expressions.

**Parentheses**

If you need to override the order of operators, you can. As demonstrated in Table above, if you group an expression inside parentheses, C evaluates that expression before the others. Parentheses have top precedence:

ans = (5 + 2) * 3; /* Puts 21 in ans */

Even though multiplication is usually performed before addition, the parentheses force C to evaluate 5 + 2 first and then multiply the resulting 7 by 3. Therefore, if you want to average four values, you can do so by grouping the addition of the values in parentheses:

avg = (i + j + k + l) / 4; /* Computes average */

**Note : **Use lots of parentheses. They clarify your expressions. Even if the regular operator order will suffice for your expression, parentheses make the expression easier for you to decipher if you need to change the program later.

**Assignments**

**Assignment** has **very low priority** in the table, and it associates from **right to left**.

The right-to-left associativity lets you perform an interesting operation: You can assign a value to more than one variable in the same expression. To assign the value of 9 to 10 different variables, you *could *do this:

a = 9; b = 9; c = 9; d = 9; e = 9; f = 9; g = 9; h = 9; i = 9; j = 9;

but this is easier:

a = b = c = d = e = f = g = h = i = j = 9;

Because of the right-to-left associativity, C first assigns the 9 to j, then puts the 9 in i, and so on.

**Note : **C doesn’t initialize variables for you. If you wanted to put 0 in a bunch of variables, a multiple assignment would do it for you.

**Every C expression produces a value**. The expression j = 9; does put a 9 in j, but it also results in a completed value of 9, which is available to store somewhere else, if needed. The fact that every assignment results in an expression lets you do things like this that you can’t always do in other programming languages:

a = 5 * (b = 2); /* Puts a 2 in b and 10 in a */

Here’s one last program example that uses assignments, operators, and parentheses to change the order of operators:

#include <stdio.h> main() { int grade1, grade2, grade3, grade4; float averageGrade, gradeDelta, percentDiff; /* The student got 88s on the first and third test, so a multiple assignment statement works. */ grade1 = grade3 = 88; grade2 = 79; // The user needs to enter the fourth grade printf("What did you get on the fourth test"); printf(" (An integer between 0 and 100)?"); scanf(" %d", &grade4); averageGrade = (grade1+grade2+grade3+grade4)/4; printf("Your average is %.1f.\n", averageGrade); gradeDelta = 95 - averageGrade; percentDiff = 100 * ((95-averageGrade) / 95); printf("Your grade is %.1f points lower than the ", gradeDelta); printf("top grade in the class (95)\n"); printf("You are %.1f percent behind ", percentDiff); printf("that grade!\n\n\n"); return 0; }

Scanf < Prev Next > Compound operators & Typecasting

[…] Preprocessor directives & Header files < Prev Next > Basic Arithmetic […]

LikeLike

[…] Basic Arithmetic < Prev Next > if-else & Relational operators […]

LikeLike