Types and variables in C — practice with a calculator, the IC2 final grade and a profile with the DNI letter (and the division by zero that kills the program)

The first time I tried my C calculator I handed it to a classmate so he could “break” it. It took him ten seconds: as the second number he typed a 0. The program didn’t show any nice error message, no ZeroDivisionError like Python. The terminal printed Floating point exception (core dumped) and that was it. That’s when I understood the lesson you’ll see in today’s three programs: C does exactly what you write, with the types you write, and doesn’t protect you from anything you haven’t planned for.

In the types and variables in C theory we covered types, integer division, casts, printf and scanf. Now it’s time to use all of it in three medium-level programs that read data from the keyboard with scanf, like the ones in the IC2 labs: a calculator that shows the difference between integer and real division, the IC2 final grade with average, weighted average and rounding, and a student profile with the Spanish ID (DNI) letter worked out with a modulo. The data looks like the real thing: grades with decimals, an 8-digit ID number and a start year. Every output comes from a real run with gcc, typing the data you see.

Before you start

Make sure you’re clear on:

  • That int / int gives an int and that a (float) or a .0 on one operand makes the division real.
  • The printf specifiers (%d, %.2f, %c) and that in scanf every variable takes a &.
  • That a char is a number ('S' is 83) and that comparisons give 1 or 0.
  • How to compile and run: gcc -Wall -std=c11 calculator.c -o calculator and ./calculator.

If any of them sounds shaky, review the theory before carrying on.

Create a folder for the practice (mkdir -p ~/IC2/types && cd ~/IC2/types) and open each program with gedit calculator.c &. The & at the end keeps the terminal free to compile while gedit stays open. If your environment isn’t ready, there’s the gedit and gcc on Fedora guide.

Program 1: basic calculator with numeric types

The program asks for two integers and shows the sum, the difference, the product, the integer division, the real division, the remainder and the square of the first one. What makes it tricky isn’t the arithmetic, but the types: the same division gives 2 or 2.3333 depending on how you write it, and if the second number is 0 the program dies.

The idea

We read a and b as int with scanf. We store the division in two different variables: an int with a / b (integer division) and a float with (float)a / b (real division). That way you see both side by side. To show that the integer division and the remainder fit together, we add a check line: b * (a / b) + a % b must give a back.

Before coding, think about what type each operation has. a + b between two int is int, so it’s printed with %d. The real division is a float: %.4f. If you pair a specifier with another type, the output is garbage.

The code

#include <stdio.h>

int main(void) {
    int a, b;                /* the two numbers typed on the keyboard */
    int int_result;          /* the integer division fits here */
    float real_result;       /* and the real one, with decimals */

    printf("Enter the first number: ");
    scanf("%d", &a);         /* & = "store it at the address of a" */
    printf("Enter the second number: ");
    scanf("%d", &b);

    int_result = a / b;               /* int / int: the decimals are dropped */
    real_result = (float)a / b;       /* converts a BEFORE dividing */

    printf("\n--- Results with %d and %d ---\n", a, b);
    printf("Sum:               %d\n", a + b);
    printf("Difference:        %d\n", a - b);
    printf("Product:           %d\n", a * b);
    printf("Integer division:  %d\n", int_result);
    printf("Real division:     %.4f\n", real_result);
    printf("Remainder (mod):   %d\n", a % b);
    printf("Check:             %d * %d + %d = %d\n", b, int_result, a % b, b * int_result + a % b);
    printf("a squared:         %d\n", a * a);   /* C has no **: just multiply */
    return 0;
}

The heart of the program is these two lines. Both divide a by b, but they don’t do the same thing:

int_result = a / b;               /* int / int: the decimals are dropped */
real_result = (float)a / b;       /* converts a BEFORE dividing */

In the first one, a and b are int: C does the integer division and throws the decimals away. In the second, (float)a converts a to a decimal before dividing, and then float / int is a real division. The cast has to be attached to the operand, not to the result: (float)(a / b) would divide with integers first and give 2.0000.

This is how C works it out, step by step, with 7 and 3. In each operation it only looks at the two operands in front of it:

ExpressionStepOperand typesResultWhy
a / b7 / 3int and int2two integers: integer division, the remainder is thrown away
(float)a / b(float)7an int converted7.0the cast acts first, only on a
7.0 / 3float and int2.3333when they’re mixed, C turns the 3 into 3.0 and divides with decimals
(float)(a / b)7 / 3int and int2the brackets force the division to happen first
(float)2an int converted2.0the cast arrives when the decimals no longer exist

I checked it with gcc: 2.3333 and 2.0000. A cast doesn’t “fix” a division: it changes the type of whatever is immediately to its right.

Output

I typed 7 and 3:

Enter the first number: 7
Enter the second number: 3

--- Results with 7 and 3 ---
Sum:               10
Difference:        4
Product:           21
Integer division:  2
Real division:     2.3333
Remainder (mod):   1
Check:             3 * 2 + 1 = 7
a squared:         49

Checking by hand: 7 + 3 = 10, 7 − 3 = 4, 7 × 3 = 21. In the division, 3 fits into 7 twice with 1 left over, so 7 / 3 = 2 and 7 % 3 = 1, and the check line confirms it: 3 × 2 + 1 = 7. The real division is 7 / 3 = 2.3333… and %.4f writes it with 4 decimals. The drawing shows it with sweets:

Integer division, remainder and real division with 7 and 37 sweets in groups of 3: 2 full groups (7 / 3 = 2) and 1 left (7 % 3 = 1); with decimals, 2.3333; by 0, the program dies.7 / 3 and 7 % 3 with sweets: groups of 3group 1group 2remainder7 / 3 = 2full groups7 % 3 = 1what is left3 * 2 + 1 = 7(float)7 / 3 = 2.3333share the leftover too: 1 / 3 = 0.33337 / 0how many groups of 0? No answer: Floating point exception
Integer division counts full groups and the modulo counts what is left over.

And now what my classmate did. The same calculator, typing 7 and 0:

Enter the first number: 7
Enter the second number: 0
Floating point exception (core dumped)

Integer division by 0 has no answer, and the processor stops it with a signal (SIGFPE). The name is misleading: it says floating point even though the division is between integers. Bash prints that message and the program never gets to print even the sum.

Thinking that storing the result in a float fixes the division: float r = a / b; still gives 2.0000 with 7 and 3. What matters is the type of the operands, not of the variable.

Questions you might ask

Why not just read a float so there’s no need for the cast? You could, but then integer division and the remainder would disappear: % only works with integers. The program wants to show both divisions, and for that the data has to be int.

How do the labels stay lined up? Each label carries its spaces counted by hand inside the printf text, so all the values start in the same column. With a width like %-18s you’d get the same effect, but careful with accented letters in other languages: printf counts bytes, not letters, and an accented letter takes two bytes in UTF-8.

Why don’t I get an error message instead of the crash with 0? Because C doesn’t check anything you don’t check. To avoid it you have to look at b before dividing, and that needs an if, which comes in the next topic. For now, the lesson is knowing that it happens and recognising the message.

What happens if I type a letter instead of a number? scanf can’t convert the letter, stores nothing in a and leaves it with whatever garbage it had. The program carries on with that value without warning. scanf returns how many values it read correctly, and checking that (again with an if) is how you detect it.

Why is a squared written a * a and not a ** 2? Because C has no power operator. For big powers there’s pow in <math.h> (it works with double and needs -lm when compiling), but a square is written by multiplying.

Writing printf("Remainder: %d\n", a % b); with a or b of type float. It doesn’t compile: % only accepts integers. If you ever need the remainder of two decimals, use fmod.

What would happen if you typed 2.5 as the second number?

The calculator would work with 7 and 2 without telling you. scanf("%d", &b) takes digits until it finds something that isn’t a digit, the dot: it stores 2 in b and leaves .5 waiting in the input, where nobody reads it again. I ran it and the header says “Results with 7 and 2”: integer division 3, real division 3.5000, remainder 1 and the check 2 * 3 + 1 = 7. Everything adds up, but with a number that isn’t the one you typed.

Try it yourself

  • Add a line that shows (float)(a / b) and check that with 7 and 3 it gives 2.0000: the cast comes too late.
  • Try negative numbers, for example −7 and 2. Predict the integer division and the remainder first (hint: C truncates towards zero) and compare with the output.

Program 2: the IC2 final grade with average and rounding

The program asks for the four IC2 grades (theory, practice, test and project), and works out the sum, the average, a weighted average with example weights, the truncated average, the rounded average and whether you’ve passed and got a merit. What makes it tricky: there are decimals, conversions to integer that chop or round, and we want to know whether you pass without using an if yet.

The idea

The grades are read as float with %f. The average divides by 4.0f so the division is real. For the weighted average, each grade is multiplied by its weight (0.40, 0.30, 0.20 and 0.10, which add up to 1). To convert to integer we use two different casts: (int)average chops the decimals and (int)(average + 0.5f) rounds. And for “passed” and “merit” we store the result of a comparison directly: 1 if it holds and 0 if it doesn’t.

Before coding, think about how you’d round 7.75 by hand knowing the computer can only chop decimals. If you add 0.5, anything at x.5 or above moves to the next integer, and chopping leaves the rounded value.

The code

#include <stdio.h>

int main(void) {
    float theory, practice, test, project;   /* the four IC2 grades */

    printf("=== IC2 FINAL GRADE ===\n\n");
    printf("Theory (0-10): ");
    scanf("%f", &theory);                    /* float -> %f in scanf */
    printf("Practice (0-10): ");
    scanf("%f", &practice);
    printf("Test (0-10): ");
    scanf("%f", &test);
    printf("Project (0-10): ");
    scanf("%f", &project);

    float total = theory + practice + test + project;
    float average = total / 4.0f;            /* 4.0f: real division */
    /* example weights: 40 % theory, 30 % practice, 20 % test and 10 % project */
    float weighted = theory * 0.40f + practice * 0.30f + test * 0.20f + project * 0.10f;
    int truncated = (int)average;            /* (int) chops: 7.75 -> 7 */
    int rounded = (int)(average + 0.5f);   /* trick: add 0.5 and chop -> 8 */
    int passed = average >= 5.0f;            /* no if yet: a comparison gives 1 or 0 */
    int merit = average >= 7.0f && average < 9.0f;

    printf("\n--- Results ---\n");
    printf("Sum:                %.2f\n", total);
    printf("Average:            %.2f\n", average);
    printf("Weighted average:   %.2f\n", weighted);
    printf("Truncated average:  %d\n", truncated);
    printf("Rounded average:    %d\n", rounded);
    printf("Passed (1 = yes):   %d\n", passed);
    printf("Merit (1 = yes):    %d\n", merit);
    return 0;
}

The calculation lines deserve a zoom, because each one shows something different from the theory:

float total = theory + practice + test + project;
float average = total / 4.0f;          /* 4.0f: real division */
/* example weights: 40 % theory, 30 % practice, 20 % test and 10 % project */
float weighted = theory * 0.40f + practice * 0.30f + test * 0.20f + project * 0.10f;
int truncated = (int)average;          /* (int) chops: 7.75 -> 7 */
int rounded = (int)(average + 0.5f);   /* trick: add 0.5 and chop -> 8 */
int passed = average >= 5.0f;          /* no if yet: a comparison gives 1 or 0 */
int merit = average >= 7.0f && average < 9.0f;
  • total / 4.0f is float / float: real division. If I’d written / 4 it would also be real (because total is already a float), but 4.0f makes it clear we want decimals.
  • The weights carry an f (0.40f) so the whole calculation is float. Without the f they’d be double and C would convert the result when storing it. It works the same, but this way you don’t mix types by accident.
  • (int)average and (int)(average + 0.5f) are the two casts from the theory table: chop and round.
  • average >= 5.0f is 1 or 0 and is stored in an int. merit uses &&: both conditions at once.

Output

I typed 7.5, 8.0, 6.5 and 9.0:

=== IC2 FINAL GRADE ===

Theory (0-10): 7.5
Practice (0-10): 8.0
Test (0-10): 6.5
Project (0-10): 9.0

--- Results ---
Sum:                31.00
Average:            7.75
Weighted average:   7.60
Truncated average:  7
Rounded average:    8
Passed (1 = yes):   1
Merit (1 = yes):    1

Checking by hand: 7.5 + 8 + 6.5 + 9 = 31 and 31 / 4 = 7.75. The weighted one: 7.5 × 0.4 = 3; 8 × 0.3 = 2.4; 6.5 × 0.2 = 1.3; 9 × 0.1 = 0.9; and 3 + 2.4 + 1.3 + 0.9 = 7.6. Truncating 7.75 gives 7; rounding is chopping 7.75 + 0.5 = 8.25, which gives 8. And since 7.75 ≥ 5 and it’s between 7 and 9, passed and merit are 1.

The drawing shows why the weighted average (7.60) ends up below the plain average (7.75): the test, the lowest grade, weighs twice as much as the project, the highest.

IC2 grades, average and weighted averageBars for 7.50, 8.00, 6.50 and 9.00 with weights 40, 30, 20 and 10 %; the average is 7.75 and the weighted average 7.60; truncating gives 7 and rounding gives 8.The four grades, the average and the weighted oneTheory (40 %)7.50Practice (30 %)8.00Test (20 %)6.50Project (10 %)9.00average 7.75weighted 7.60(int)7.75→ 7chops the decimals(int)(7.75 + 0.5)= (int)8.25 → 8the rounding trick
The weighted average drops because the test (6.50) weighs more than the project (9.00).

The weights are an example for the program, not IC2’s official assessment. Swap them for the ones in your course guide and check they still add up to 1.

To really see why the weighted average goes down, compare what each grade contributes with what it would contribute in the normal average, where they all weigh 25 %:

GradeWeightContributes in the weighted oneWould contribute at 25 %DifferenceWhy
Theory 7.540 %3.0001.875+1.125it weighs more than in the normal average
Practice 8.030 %2.4002.000+0.400it also weighs a bit more
Test 6.520 %1.3001.625−0.325it weighs a bit less
Project 9.010 %0.9002.250−1.350the highest grade is the one that weighs least

The differences add up to −0.15, and 7.75 − 0.15 = 7.60. The one pulling down the most is the project: a 9 that would be worth 2.25 points in the normal average only contributes 0.90 here.

Questions you might ask

Why are the grades float and not double? For grades with one decimal, the 6 reliable digits of a float are plenty. If you used double, you’d have to read them with %lf in scanf; in printf %.2f would work the same.

Does the add-0.5 trick always work? With positive numbers, yes. With negatives it fails: −7.75 + 0.5 = −7.25, which is chopped to −7, when the right answer would be −8. For the general case there’s round in <math.h>.

This is how the trick behaves with several averages (I ran it with these values as float):

averageaverage + 0.5f(int)Why
7.758.258the decimal part was 0.5 or more: it moves up to the next integer
7.508.008exactly 0.5 also goes up
7.497.997it doesn’t reach 8, and chopping leaves it at 7
7.257.757the same: less than 0.5 goes down
−7.75−7.25−7(int) chops towards zero, so the trick fails with negatives

Why does the weighted average come out as exactly 7.60 if float is approximate? In reality the float stores something like 7.5999999 or 7.6000004, and %.2f rounds it when printing. With two decimals you don’t notice; that’s why you never compare decimals with ==.

Why is passed an int and not a bool? It could be a bool with <stdbool.h>, and it would print the same with %d (1 or 0). Using int makes it clear what happens inside: a comparison in C is a number.

How would I show “Passed” or “Failed” instead of 1 or 0? With an if or with the ternary operator (passed ? "Passed" : "Failed"), which are the first thing in conditionals in C.

Declaring the grades as int to “keep it simple”. scanf with %d would read the 7 of 7.5 and leave .5 in the input; the next %d would hit the dot, read nothing, and the following grades would be left with garbage.

What would happen if you wrote average > 5.0f instead of average >= 5.0f and got a 5 in everything?

You’d fail with a 5. With 5, 5, 5 and 5 the average is exactly 5.00, and 5.0 > 5.0 is false, so passed is 0. With >= it’s 1. I checked it by printing both versions with those grades: 1 and 0. A single character in the comparison decides the borderline case, and with grades the borderline case is exactly the one that matters most.

Try it yourself

  • Change the test grade to 4.0 and predict the average, the weighted average and the rounding first. Check that merit becomes 0.
  • Add a distinction variable that is 1 if the average is 9 or more, without using if.

Program 3: student profile with the DNI letter

The program asks for the DNI (the Spanish ID number, digits only), the initials, the age, the average grade, the credits passed and the start year, and shows a profile with the DNI letter, the initial in lowercase, the percentage of the degree and the credits left. It’s the one that mixes the most types: int, char, float and a constant with #define. This program was already in the first version of the article, and it had a bug that slipped through: a comment written with #, like in Python. In C comments are // or /* */, and a stray # in the middle of the code doesn’t compile.

The idea

We read each value with its specifier and, for the char values, with the space before %c to skip the previous Enter. With the data we do four calculations from the theory: the DNI letter with a modulo (the remainder of dividing by 23 picks a letter from a fixed string), the lowercase letter by adding 32 to the char, the percentage with a real division and the credits left with a subtraction against the DEGREE_CREDITS constant.

Before coding, look at the order of the reads: after a number comes a char. That’s where a %c without a space would grab the Enter.

The code

#include <stdio.h>
#define DEGREE_CREDITS 240      /* credits in a 4-year degree */

int main(void) {
    int dni;                    /* 8 digits fit in an int (maximum 2147483647) */
    char first_initial, surname_initial;
    int age, credits, start_year;   // no accented letters in names
    float avg_grade;

    printf("=== STUDENT PROFILE ===\n\n");
    printf("DNI (numbers only): ");
    scanf("%d", &dni);
    printf("First name initial: ");
    scanf(" %c", &first_initial);   /* space before %c: skips the Enter after the DNI */
    printf("Surname initial: ");
    scanf(" %c", &surname_initial);
    printf("Age: ");
    scanf("%d", &age);
    printf("Average grade (0-10): ");
    scanf("%f", &avg_grade);
    printf("Credits passed: ");
    scanf("%d", &credits);
    printf("Year started: ");
    scanf("%d", &start_year);

    /* the DNI letter: the remainder of dividing by 23 picks a letter from this string */
    char letter = "TRWAGMYFPDXBNJZSQVHLCKE"[dni % 23];
    char first_lower = first_initial + 32;      /* in ASCII, lowercase = uppercase + 32 */
    int years = 2026 - start_year;
    int remaining = DEGREE_CREDITS - credits;
    float percentage = credits * 100.0f / DEGREE_CREDITS;   /* 100.0f: real division */
    int passed = avg_grade >= 5.0f;

    printf("\n=============================\n");
    printf("       STUDENT PROFILE\n");
    printf("=============================\n");
    printf("DNI:          %08d-%c\n", dni, letter);
    printf("Initials:     %c.%c. (%c in lowercase)\n", first_initial, surname_initial, first_lower);
    printf("Age:          %d years\n", age);
    printf("Average:      %.2f/10 (%.1f/100)\n", avg_grade, avg_grade * 10);
    printf("Credits:      %d of %d (%.1f %%)\n", credits, DEGREE_CREDITS, percentage);
    printf("Remaining:    %d credits\n", remaining);
    printf("Started:      %d (%d year/s)\n", start_year, years);
    printf("Passed:       %d (1 = yes)\n", passed);
    printf("=============================\n");
    return 0;
}

The zoom goes to the calculations, which is where the types are:

char letter = "TRWAGMYFPDXBNJZSQVHLCKE"[dni % 23];
char first_lower = first_initial + 32;      /* in ASCII, lowercase = uppercase + 32 */
int years = 2026 - start_year;
int remaining = DEGREE_CREDITS - credits;
float percentage = credits * 100.0f / DEGREE_CREDITS;   /* 100.0f: real division */
int passed = avg_grade >= 5.0f;
  • "TRWAGMYFPDXBNJZSQVHLCKE"[dni % 23] takes the string with the 23 DNI letters and keeps the one at position dni % 23. It’s the official algorithm: the remainder, between 0 and 22, picks the letter. Strings are arrays of char, which we’ll see properly later; for now it’s enough to know that [14] is the character at position 14, counting from 0.
  • first_initial + 32 works because in ASCII the lowercase version of a letter is 32 places further on.
  • credits * 100.0f / DEGREE_CREDITS: the 100.0f makes credits * 100.0f a float and the division real. With 100 it would have given 6000 / 240 = exactly 25 in this case, but with 50 credits it would give 20 instead of 20.8.

And the reads, one by one, with the data from the output below. What you type waits in the input until a scanf takes it:

LineYou typeWhat it storesWhat is left waitingWhy
scanf("%d", &dni)12345678 + Enterdni = 12345678the Enter%d stops at the first character that isn’t a digit
scanf(" %c", &first_initial)S + Enterfirst_initial = 'S' (83)the Enterthe space skips the Enter after the DNI and %c takes the S
scanf(" %c", &surname_initial)M + Entersurname_initial = 'M' (77)the Enterthe same with the Enter after the S
scanf("%d", &age)19 + Enterage = 19the Enter%d already skips leading Enters on its own
scanf("%f", &avg_grade)7.75 + Enteravg_grade = 7.75the Enter%f accepts the decimal point

Numbers skip pending Enters on their own; %c doesn’t, and that’s why it has the space in front.

Output

I typed 12345678, S, M, 19, 7.75, 60 and 2025:

=== STUDENT PROFILE ===

DNI (numbers only): 12345678
First name initial: S
Surname initial: M
Age: 19
Average grade (0-10): 7.75
Credits passed: 60
Year started: 2025

=============================
       STUDENT PROFILE
=============================
DNI:          12345678-Z
Initials:     S.M. (s in lowercase)
Age:          19 years
Average:      7.75/10 (77.5/100)
Credits:      60 of 240 (25.0 %)
Remaining:    180 credits
Started:      2025 (1 year/s)
Passed:       1 (1 = yes)
=============================

Checking by hand: 12345678 = 23 × 536768 + 14, so the letter is the one at position 14, the Z (12345678Z is the sample DNI you see everywhere, and it matches). 'S' is 83 and 83 + 32 = 115, the s. 7.75 × 10 = 77.5. 60 × 100 / 240 = 25 %. 240 − 60 = 180 credits. And 2026 − 2025 = 1 year. The drawing shows the letter picked by the modulo and the char addition:

DNI letter and lowercase of a charThe remainder of 12345678 divided by 23 is 14 and letter 14 of TRWAGMYFPDXBNJZSQVHLCKE is Z. Below, S is 83 and adding 32 gives s, which is 115.The DNI letter is integer arithmetic12345678 % 23 = 14(12345678 = 23 * 536768 + 14)T0R1W2A3G4M5Y6F7P8D9X10B11N12J13Z14S15Q16V17H18L19C20K21E22position 14 → ZA char is a small number:‘S’ = 83‘s’ = 115+ 32
The modulo picks a position in the string: 12345678 gets the letter Z.

%08d writes the DNI with 8 digits, padding with zeros on the left. With a DNI like 01234567, the int stores 1234567 (leading zeros don’t exist in a number) and %08d puts them back when printing.

Questions you might ask

Why is the DNI an int if it’s such a long number? Because the highest possible DNI, 99999999, fits easily in an int (maximum 2147483647). A phone number with its prefix (34600123456) wouldn’t fit and would need long long… or better a string, because you don’t do maths with it.

Why can the output say anything I like, but start_year can’t have accents? Text between quotes can contain any UTF-8 character, and the Fedora terminal displays it fine. Variable names can only use English letters, digits and _: a name with an accented letter or ñ gives an error. That’s what the comment // no accented letters in names is about, and in the first version of the article it was written with # and didn’t compile.

What would happen if I removed the space from " %c"? first_initial would get the Enter after the DNI (character 10) and the program would carry on without waiting for you. The initials would come out wrong and so would the profile: it’s the bug from the theory, in a real program.

Does the lowercase trick work with any character? Only with capital letters. If the initial is already lowercase, adding 32 gives another symbol ('s' + 32 is 147, outside ASCII). To do it properly there’s tolower in <ctype.h>.

Writing comments with #, like in Python. int year; # start year doesn’t compile: gcc says stray '#' in program. In C, # only starts preprocessor directives at the beginning of a line (#include, #define).

What would happen if you removed the .0f and wrote credits * 100 / DEGREE_CREDITS?

With the 60 credits from the output you wouldn’t notice: 6000 / 240 gives exactly 25 and it prints 25.0 %. But with 50 credits, 50 * 100 is 5000, 5000 / 240 is an integer division that gives 20, and that 20 is stored in the float as 20.0. The profile says (20.0 %) when the right answer is 20.8 %, which is what you get with 100.0f. I ran both versions. It’s the same mistake as in program 1: the float on the left doesn’t rescue a division that was already done with integers.

Try it yourself

  • Try your own DNI (or any 8-digit number) and check the letter it gets.
  • Add a line that shows the surname initial in lowercase and its ASCII code with %d.

Common mistakes in this practice

  • Dividing integers and expecting decimals: a / b with two int gives an integer even if stored in a float. Put the cast on an operand.
  • Forgetting the & in scanf: it compiles with a warning and the usual result is a Segmentation fault.
  • %c without a space after a number: the Enter gets read and the following values go out of step.
  • Dividing by 0: with integers, the program dies with Floating point exception. Until we have if, there’s no way to avoid it.
  • A specifier that doesn’t match the type: %d for a float or %f for an int gives garbage. Always read the -Wall warnings.
  • Comments with #: in C they’re written with // or /* */.

Watch it step by step in Python Tutor

Python Tutor (pythontutor.com) runs C line by line and draws every variable. Choose C (gcc) in the menu and paste this version without scanf (Python Tutor doesn’t read from the keyboard), which combines the two divisions of program 1, the pass of program 2 and the DNI letter of program 3:

#include <stdio.h>

int main(void) {
    int a = 7, b = 3;
    float wrong = a / b;            /* 7 / 3 = 2 (integer) and then 2.0 */
    float right = (float)a / b;     /* 7.0 / 3 = 2.333... */
    int remainder = a % b;          /* 7 = 3 * 2 + 1 */
    int passed = right >= 5.0f;     /* 0: a comparison gives 1 or 0 */
    char letter = "TRWAGMYFPDXBNJZSQVHLCKE"[12345678 % 23];
    printf("%.2f %.4f %d %d %c\n", wrong, right, remainder, passed, letter);
    return 0;
}

Its output:

2.00 2.3333 1 0 Z

Watch for this step by step:

  1. When the wrong line runs, its box shows 2: the integer division happens before storing in the float.
  2. On the right line, the box shows 2.333…: the cast was applied before dividing.
  3. remainder is 1 and, with the 2 in wrong, satisfies 3 × 2 + 1 = 7.
  4. passed is 0 because 2.333 doesn’t reach 5: a comparison is a number.
  5. In letter the Z appears (code 90): the modulo picked position 14 of the string.

Summary

  • Division between two int is integer division; the (float) cast has to go on an operand, before dividing.
  • % gives the remainder and, together with integer division, satisfies b * (a / b) + a % b == a.
  • (int)x chops the decimals and (int)(x + 0.5f) rounds positive numbers.
  • A comparison is 1 or 0 and can be stored in an int without using if.
  • A char is a number: you can add 32 for the lowercase letter or pick a letter with a modulo.
  • In scanf, & in front of each variable and a space before %c.

Checklist: have you practised it?

  • Have you run the three programs and checked the outputs?
  • Can you explain why (float)a / b and (float)(a / b) give different results?
  • Have you seen the Floating point exception when dividing by 0?
  • Can you work out a DNI letter by hand with the modulo?
  • Have you tried the “Try it yourself” tasks without looking at the theory?
  • Do you always compile with -Wall and read the warnings?

If you answered yes to almost everything, you’re ready for the types and variables in C exercises, where I no longer hand you the code. See you there!

Next step: exercisesTypes and variables in C — exercises with shapes, BMI, number bases and a scientific calculator (and the scanf without & that ends in a Segmentation fault)

Did this article help you? Here is how you can support SergioLearns →