Programming in C (Part 5 - Arithmetic Operators) — 19 Dec, 2016

Hey guys, It's been a long time since I wrote an article in this series. I was planning to write about loops but after thinking a bit I came to the conclusion that there's a topic that deserves special attention, I'm talking about operators.

There are various types of operators in C, we will talk about Arithmetic and Increment/Decrement operators.

Arithmetic Operators

These are the easiest to understand because you are used to them (all calculators have them), they need two operands, the following code is self explanatory:

#include <stdio.h>

int main(){
    const int A = 20;
    const int B = 4;
    int c;

    //Printing the values
    printf("A = %d\nB = %d\n\n", A, B);

    c = A+B;
    printf("%d + %d = %d\n", A, B, c);

    c = A-B;
    printf("%d - %d = %d\n", A, B, c);

    c = A*B;
    printf("%d * %d = %d\n", A, B, c);

    c = A/B;
    printf("%d / %d = %d\n", A, B, c);

    c = A%B;
    printf("%d %% %d = %d\n", A, B, c);

As you can see this is very easy to understand, c is the only variable here because A and B never need to change.

Increment/Decrement operators

These operators only take one operand, they are very useful in Loops, also they can be placed before or after the operand.

#include <stdio.h>

int main(){
    int a = 1;

    printf("%d\n",a); //print 1

    a++; //a is now 2
    ++a; //a is now 3
    a--; //a is now 2
    --a; //a is now 1

    return 0;

Postfix or Prefix?

The order matters, you can see that by running this example:

#include <stdio.h>

int main(){
    int b = 1;
    printf("%d\n",b++); //display 1 and then increment
    printf("%d\n",b); //the current b value is 2
    printf("%d\n",++b); //increment to 3 and then show

    printf("%d\n",b); //final value should be 3; 

    return 0;

Hope you enjoy this tutorial, the next topic will probably be about Assignment Operators.