The basic operators in C

There are several categories of operators in C – sign, assignment, arithmetic, relational, boolean, bitwise and more. At this point of the tutorial, we need to cover the most basic operators – sign, assignment and arithmetic. Later, when we talk about conditional constructions we will talk about relational and boolean operations, too.

Operand

Advertise on this site. I promise you will like the rates :)

Operands are the arguments that the operators accept. Different operators accept different number of operands 1,2 or 3. For instance the sum operator + accepts two operands. They are the numbers that will be summed:

    8 + 12

Here, the digit 8 is the left argument, because it is on the left of the operator and 12 is the right.

Sign

The sign operators change a number value to negative or positive. By default all numbers are positive, so the plus sign is not used in practice as a sign operator.

  • +
  • -

We use the - to indicate that a given value is negative. Usually we don't really think of it as an operator, but that's exactly what it is.
Minus is one of the few unary operators in C. Unary means that it takes only one operand – the number. Here are several obvious examples:

    -1, -15.04f, -20.55

Arithmetic operators in C

Sum +

   2 + 2 = 4 , not a big deal.

We cannot put two operators next to each other. If for some reason you decide to sum negative numbers, use parenthesis to separate the operators:

    float total = sum + (-5);

Of course normally we will not use this form, but just use the next...

Subtract -

    2 - 2 = 0

No surprise here, either. The rule for parenthesis remains if you want to do something weird:

    -5 - (-4-(-3)) = ? This is your first homework task.

Multiply *

In C, the symbol, used for multiplication is the asterisk *.

    3 * 3 = 9

Nothing fancy to add here.

Division /

Don't skip this! The division operator is the forward slash.

    4 / 2 = 2

BUT!

    5 / 2 = 2 , too.

If all operands of the division are integers, the result will always be integer. If you want to get a fraction result, at least one of the arguments needs to be a fraction:

    5.0 / 2 = 2.5
    5 / 2.0 = 2.5
    (double) 5/2=2.5
    5/ (float)2 = 2.5

Division with remainder %

To take the remainder of a division in C, use the % operator. It accepts two arguments and returns only the remainder of their division.

    5 % 2 = 1
    4 % 2 = 0

This operation can be performed only with integer numbers.

Increment and decrement operators in C

In programming very often we need to increment or decrement a variable by 1. For this reason there are two operators in C that make it even easier to do that:

  • ++ “Increment”
  • -- “Decrement”

They both accept only one operand left or right. Here are examples:

    i++;
    --count;

When the operator is used before the variable, it is a prefix. When it is after the name of the variable it is a suffix.
The prefix increment/decrement changes the variable, before its value is used in the current statement. This will print “The total count is 6”:

    int count = 5;
    printf("The total count is %d", ++count);

When used as suffix, the operators change the variable after its value is used in the current statement.

    char letter = 'G';
    printf("Your letter is %c", letter--);

Two things:

  • Recall from the C data types lesson, that we can handle chars like numbers. That's why it is OK to decrement a char variable
  • The suffix operator will change the variable after its value is printed to the display. This means that the above will print “Your letter is G”.

Assignment operators in C

You have already seen the c operator for value assignment "=". It accepts two arguments left and right. Sometimes we refer to them as L-value and R-value. The left operand must be modifiable, because it will accept the value of the right side. The right side will not change its value.

Let's create an int variable and assign it with the value of the constant 1.

    int recordId = 1;

We can also assign the result of a calculation:

    float average = sum / count;

Since the right side is not a constant, first it must be calculated and then the result will be assigned to the left side. Of course, at this moment the two variables (sum and count) should already have been initialized.

Short assignment operators in C

Sometimes we just need to modify the value of a variable, by adding to it, dividing it etc. In these cases we will write something like:

    count = count + 5;
    average = average / 2;

In this case we write the name of the same variable two times. For such situations we can use the short version of the assignment operator:

    count += 5; will do is exactly the same thing like count = count + 5;
    average /= 2; will do the same like average = average / 2;

This rule works for any of the operators +, -, /, *, %, >>, <<, |, &, &. The last operators( >>, <<, |, &, &.) are called bitwise operators. They change the numbers on bit level and we will look at them later.

Example program 1

Write a program that asks the user for the fuel usage of three trips and then finds the average. Find the average both as an int and as a float.

#include <stdio.h>

int main(void)
{
	int trip1, trip2, trip3, sum, averageInt;
	float averageFloat;
	sum = 0;
	printf("Input the fuel usage for the first trip:");
	scanf("%d", &trip1);
	sum += trip1;
	printf("Input the fuel usage for the second trip:");
	scanf("%d", &trip2);
	sum += trip2;
	printf("Input the fuel usage for the third trip:");
	scanf("%d", &trip3);
	sum+= trip3;
	averageInt = sum / 3;
	averageFloat = (float) sum / 3;
	printf("The average fuel consumption is %.2f\n", averageFloat);
	printf("The average fuel consumption, rounded down is %d\n", averageInt);
		
	return 0;
}

Relational operators in C

We use the relational operators in C to compare values. We can check for equality or if a given value is greater or smaller than the other.
All these operations give a result of logical evaluation. Since C does not have a boolean data type(not until C99), the result is an integer number. A zero means that the condition that we checked is false. Any result, different from 0 is true and the most common truth value is 1.

Equal to ==

The operator to check for equality is ==. This is double the sign =. Beginners often forget that and try to make a comparison with a single equals symbol, which is the operator for assignment.

    int equals = 5 == 5;
    printf("Is 5 equal to 5? : %d", equals);

Let's see how this works. First, the comparison(5 == 5) from the right side is done. The numbers are equal, so the operation returns 1. This result is assigned to the variable equals and then we print that result.

Not equal to !=

    int notEquals = 5 != 5;
    printf("Are the numbers not equal? : %d", notEquals);
    printf("Second check : %d", 3 != 2);

The first printf will print 0 and the second will output 1.

Less than < and less than or equal to <=

Less than ( < ) will return 1 if the left operand is less than the right.

    int lessThan = 5 < 9;
    printf("is 5 less than 9? : %d", lessThan);

The less than or equal to ( <= ) operator works like the previous, but it also returns true when the two operands are equal.

    int check1 = 5 <= 6;
    int check2 = 5 <= 5;

Both these comparisons return 1("true").

Greater than > and greater than or equal to >=

No surprises here:

    printf("%d", 5 > 6);

will print 0.

    printf("%d %d %d", 5 >= 4, 5 >= 5, 5 >= 6);

will print 1 1 0.

Homework

  1. How much is "-5 - (-4-(-3))" ? Answer now and then test this with a C program.
  2. What is the result of the operation: 7 / 3?
  3. How can we get a fractional result for the division above?
  4. How much is 11 % 4? Write a short program to check your answer.
  5. Write a program to calculate the perimeter of a rectangle. You need to ask the user to input the length of two sides.
   Search this site: