CodeBlanks Logo Icon CodeBlanks

Arithmetic operators

Learn basic arithmetic with +, -, *, / and %.

Arithmetic operators

C uses five arithmetic operators often: +, -, *, / and %. The first four are the addition, subtraction, multiplication and division you know. % gives the remainder of a division.

17 % 5  /* 2: 17 = 3*5 + 2 */
7 / 2   /* 3: integer division */

When two int values are divided the fraction is dropped; the result is still an int. Use double if you need the fraction.

Integer division

When two int values are divided the result is an int and the fraction is dropped. 7 / 2 gives 3, not 3.5. This is called integer division.

int a = 7 / 2;   /* a = 3 */
double b = 7.0 / 2.0;  /* b = 3.5 */

For a fractional result make at least one side a double. Writing the literal as 7.0 is enough.

Practice Print five operations

Define int a = 7, b = 3;. With five printf calls print a + b, a - b, a * b, a / b and a % b on separate lines. Output should be 10, 4, 21, 2, 1.

Starter code

main.c
#include <stdio.h>

int main(void) {
    int a = 7, b = 3;
    /* print a + b, a - b, a * b, a / b, a % b */
    return 0;
}

Sample solution

main.c
#include <stdio.h>

int main(void) {
    int a = 7, b = 3;
    printf("%d\n", a + b);
    printf("%d\n", a - b);
    printf("%d\n", a * b);
    printf("%d\n", a / b);
    printf("%d\n", a % b);
    return 0;
}

Expected output

10
4
21
2
1

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What is the result of 17 % 5?

  • 3
  • 2 Correct answer
  • 12
  • 0

Explanation: 17 = 3*5 + 2, so the remainder is 2.

2 Complete the remainder operator

Question
int r = 17 ____ 5;  /* remainder: 2 */
Answer
int r = 17 % 5;  /* remainder: 2 */

Explanation: The % operator gives the remainder.

3 Match operators to their meanings

Term Meaning
+ Addition
- Subtraction
* Multiplication
/ Division

All lessons in Beginner