90 min

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.375

The five arithmetic operators

OperatorMeaningWith a = 17, b = 5
+additiona + b is 22
-subtractiona - b is 12
*multiplicationa * b is 85
/divisiona / 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:

  1. ( ) parentheses
  2. * / %, from left to right
  3. + -, from left to right
  4. = assignment, last
2 + 3 * 4     = 2 + 12  = 14
(2 + 3) * 4   = 5 * 4   = 20
20 / 5 * 2    = 4 * 2   = 8

The 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.

Tom's Exercise 3: six expressions. Work them out on paper, then tap each one to see the operation that runs first and the value.Open full screen

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.9

Think 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.

Right side first: 7 / 2 is already 3 before the value reaches result.Open full screen

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.

Tom's three lines. wrong divides two ints; fixed1 casts sum first; fixed2 divides by a double constant.Open full screen

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:

JobExpressionExample
last digit of a numbernumber % 10572 % 10 is 2
full minutesseconds / 60137 / 60 is 2
seconds left overseconds % 60137 % 60 is 17

% works only with integers. Always: (a / b) * b + a % b equals a.

The division lab: change a and b and watch the dots group. a / b counts the full groups, a % b counts the dots left over.Open full screen

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: 17

The 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: 2

The 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:

  1. Input: scanf reads the values.
  2. Store: the values go into variables.
  3. Process: expressions calculate the results.
  4. Output: printf prints them.
  5. 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, &current);
    power = voltage * current;
    printf("Power: %.2f W\n", power);
    return 0;
}
Enter voltage and current: 12.5 1.2
Power: 15.00 W

The first line is for Visual Studio: without it, scanf stops the build with error C4996. Unit 3 explains scanf and printf in detail.

The program line by line: the three boxes start as ?, the input fills voltage and current, line 8 calculates power.Open full screen

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:

  1. scanf needs the address of total: write &total.
  2. total / samples divides two int values and loses the fraction: write (double)total / samples.
  3. %d prints an int, but average is a double: 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:

PackVoltageCurrentSecondsExpected
7312.51.29015.00 W, 0.38 Wh
15.00.2536001.25 W, 1.25 Wh
00.02.0300.00 W, 0.00 Wh

The first test checks the rounding, the second the seconds-to-hours step, the third a zero.

Key words

EnglishHebrewMeaning
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).