C Study Guide

St. Gabriel's College

|

Basic Math in C

Basic Math Operators

Math in C looks a lot like the math you use everyday. You can use the operators +, -, * and / to solve math problems. The result of a math equation can be assigned to a variable or passed to a function:

int result = (2+4)*3/4;
int age = 22;
printf("Half your age is : %d.\n", age/2);

Try it out: Basic Math

Here are some examples of basic math in C.


Compiler:
Output:

The Modulo operator "%" can be used to calculate the Remainder of a division equation.

14 / 10 == 1        14 % 10 == 4
24 / 10 == 2        24 % 10 == 4
2764 / 10 == 276    2764 % 10 == 4

Try it out: Modulo

This program uses Modulo to check if a number is even or odd.


Compiler:
Output:

The Increment operator "++" can be used to add one to a variable. The Decrement operator "--" is the opposite, it subtracts one from a variable

int age = 22;
age++;
age == 23
age--;
age == 22

Try it out: Increment and Decrement

This program changes age using the increment operator.


Compiler:
Output: