© Fort Street High School Robotics
Computers are useful because it can do calculations very quickly. C allows us to perform some arithmetic operations, as well as some logical operations (the next topic!)
We'll introduce some new symbols - addition, subtraction, multiplication and 'division'!
Action | Symbol | Comment |
---|---|---|
Addition | + |
Adds two numbers, e.g. 5 + 3 = 8 |
Subtraction | - |
Subtracts two numbers, e.g. 5 - 3 = 2 |
Multiplication | * |
Multiplies two numbers, e.g. 5 * 3 = 15 |
Division | / |
Divides and rounds down, e.g. 5 / 3 = 1 |
Modulus | % |
Gets the remainder, e.g. 5 % 3 = 2 |
Let's buy some pizza.
#include <stdio.h>
int main () {
int pizzas = 10; // Create a variable
int cost = pizzas * 8;
// print out the number and price of pizzas
printf("%d pizzas cost %d.\n", pizzas, cost);
return 0;
}
cost = pizzas * 8
%d
, and fill it in with another argument, cost
. Look carefully at the location of the quotes and commas.Let's split our pizza and share some slices!
#include <stdio.h>
int main () {
// We have 17 slices of pizza to share between 4 people.
int slices = 17;
int people = 4;
// print out how many slices per person
printf("Each person gets %d slices.\n", slices / people);
// print out the remainder
printf("There will be %d slices left.\n", slices % people);
return 0;
}
slicesPerPerson
and slicesLeft
- we just let printf
calculate it before printing.