Arithmetic in C
Expressions and the five operators, the order C uses, integer division, casting and the remainder %. Seconds into minutes, the digits of a number, the power program, a bug hunt, and the battery receipt mission.
An expression produces one value
An expression (ביטוי) is a calculation: constants, variables, operators (אופרטורים) and parentheses. However long it is, it produces one value. The values an operator works on are its operands (אופרנדים).
energy = power * seconds / 3600.0;Here the operands are power, seconds and 3600.0, the operators are * and /, and the result is one value. C replaces each name with the value in its box and calculates one operation at a time. With power = 15.0 and seconds = 90:
power * seconds / 3600.0
= 15.0 * 90 / 3600.0
= 1350.0 / 3600.0
= 0.375The five arithmetic operators
| Operator | Meaning | With a = 17, b = 5 |
|---|---|---|
+ | addition | a + b is 22 |
- | subtraction | a - b is 12 |
* | multiplication | a * b is 85 |
/ | division | a / b is 3 |
% | remainder (integers only) | a % b is 2 |
Multiplication is always written with *. In math, 2x means 2 times x; in C, 2x is an error. Write 2 * x.
The last two rows are not what most people expect. They get their own sections below.
Order of operations
C calculates in this order, the precedence (קדימות) of the operators:
( )parentheses*/%, from left to right+-, from left to right=assignment, last
2 + 3 * 4 = 2 + 12 = 14
(2 + 3) * 4 = 5 * 4 = 20
20 / 5 * 2 = 4 * 2 = 8The last line is a trap: / and * are on the same level, so C goes from left to right. When in doubt, add parentheses. They cost nothing and make a formula easy to read.
Integer division
When both operands of / are int, the result is an int. The fraction is cut off, not rounded:
7 / 2 → 3
19 / 10 → 1
7.0 / 2 → 3.5
19.0 / 10 → 1.9Think of 7 / 2 as dealing 7 items into groups of 2: 3 full groups and 1 item left over. Integer division counts the full groups and drops what is left. If at least one operand is a double, the division keeps the fraction.
Casting
When both values are int variables, you cannot add .0 to them. A cast (המרת טיפוס) asks for a double copy of a value for one calculation:
#include <stdio.h>
int main(void)
{
int sum = 7;
int count = 2;
double wrong = sum / count;
double fixed1 = (double)sum / count;
double fixed2 = sum / 2.0;
printf("wrong = %.1f\n", wrong);
printf("fixed1 = %.1f\n", fixed1);
printf("fixed2 = %.1f\n", fixed2);
return 0;
}wrong = 3.0
fixed1 = 3.5
fixed2 = 3.5(double)sum is 7.0, so 7.0 / 2 is real division. The cast does not change the variable: sum is still an int holding 7. Where you put it matters: (double)(sum / count) casts the 3 that is already cut, and gives 3.0.
The remainder: %
% gives what is left over after integer division. It has nothing to do with percent.
17 / 5 = 3 (3 full groups of 5)
17 % 5 = 2 (2 left over)Three uses that come back all year:
| Job | Expression | Example |
|---|---|---|
| last digit of a number | number % 10 | 572 % 10 is 2 |
| full minutes | seconds / 60 | 137 / 60 is 2 |
| seconds left over | seconds % 60 | 137 % 60 is 17 |
% works only with integers. Always: (a / b) * b + a % b equals a.
Seconds into minutes
Tom's Exercise 12 uses / and % together to split one number into two:
#include <stdio.h>
int main(void)
{
int total_seconds = 137;
int minutes = total_seconds / 60;
int seconds = total_seconds % 60;
printf("Minutes: %d\n", minutes);
printf("Seconds: %d\n", seconds);
return 0;
}Minutes: 2
Seconds: 17The digits of a number
The same two operators take a number apart. / 10 removes the last digit; % 10 keeps only the last digit. This is the core of lab experiment 6.
#include <stdio.h>
int main(void)
{
int number = 572;
int hundreds = number / 100;
int tens = number / 10 % 10;
int units = number % 10;
printf("Hundreds: %d\n", hundreds);
printf("Tens: %d\n", tens);
printf("Units: %d\n", units);
return 0;
}Hundreds: 5
Tens: 7
Units: 2The tens digit runs left to right: 572 / 10 is 57, and 57 % 10 is 7.
The shape of a calculation program
Every program in this unit has five parts, in this order:
- Input:
scanfreads the values. - Store: the values go into variables.
- Process: expressions calculate the results.
- Output:
printfprints them. - Verify: tests with known answers.
Declare the variables before the input, calculate after the input, print after the calculation. A successful build proves only that the syntax is right, not that the formula is. Only a test with a known answer shows that.
Tom's worked program calculates electrical power, P = V × I:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int main(void)
{
double voltage, current, power;
printf("Enter voltage and current: ");
scanf("%lf %lf", &voltage, ¤t);
power = voltage * current;
printf("Power: %.2f W\n", power);
return 0;
}Enter voltage and current: 12.5 1.2
Power: 15.00 WThe first line is for Visual Studio: without it, scanf stops the build with error C4996. Unit 3 explains scanf and printf in detail.
Debugging: right formula, wrong result
This program builds, but it prints nonsense:
int samples;
int total;
double average;
printf("Enter total and sample count: ");
scanf("%d %d", total, &samples);
average = total / samples;
printf("Average: %d\n", average);It has three bugs:
scanfneeds the address oftotal: write&total.total / samplesdivides twointvalues and loses the fraction: write(double)total / samples.%dprints anint, butaverageis adouble: write%.2f.
A fourth problem waits for unit 4: if the user types 0 samples, the program divides by zero. With the fixes and the input 7 2, the program prints Average: 3.50.
The battery receipt
Now you can write the program from the start of the unit. Read the pack ID and the duration in seconds as int, the voltage and the current as double, then:
power = voltage * current;
energy = power * duration_seconds / 3600.0;3600.0 turns watt-seconds into watt-hours, and the .0 keeps the division real. Test it with values chosen to catch different mistakes:
| Pack | Voltage | Current | Seconds | Expected |
|---|---|---|---|---|
| 73 | 12.5 | 1.2 | 90 | 15.00 W, 0.38 Wh |
| 1 | 5.0 | 0.25 | 3600 | 1.25 W, 1.25 Wh |
| 0 | 0.0 | 2.0 | 30 | 0.00 W, 0.00 Wh |
The first test checks the rounding, the second the seconds-to-hours step, the third a zero.
Key words
| English | Hebrew | Meaning |
|---|---|---|
| expression | ביטוי | a calculation that produces one value |
| operator | אופרטור | + - * / % |
| operand | אופרנד | a value an operator works on |
| precedence | קדימות | which operation runs first |
| integer division | חילוק שלמים | int / int: the fraction is cut off |
| remainder | שארית | %: what is left after integer division |
| cast | המרת טיפוס | (double)x: a copy of x as another type |
| formula | נוסחה | a rule from physics or math, written as a C expression |
| test | בדיקה | an input with a known answer |
| bug | באג | a mistake in a program |
Practice
All of Tom's exercises for this unit, with answers, are on the practice page (workbook questions 30, 27, 12 and the team mission).