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.
Table of Contents
Before you start
Make sure you’re clear on:
- That
int / intgives anintand that a(float)or a.0on one operand makes the division real. - The printf specifiers (
%d,%.2f,%c) and that in scanf every variable takes a&. - That a
charis a number ('S'is 83) and that comparisons give 1 or 0. - How to compile and run:
gcc -Wall -std=c11 calculator.c -o calculatorand./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:
| Expression | Step | Operand types | Result | Why |
|---|---|---|---|---|
a / b | 7 / 3 | int and int | 2 | two integers: integer division, the remainder is thrown away |
(float)a / b | (float)7 | an int converted | 7.0 | the cast acts first, only on a |
7.0 / 3 | float and int | 2.3333 | when they’re mixed, C turns the 3 into 3.0 and divides with decimals | |
(float)(a / b) | 7 / 3 | int and int | 2 | the brackets force the division to happen first |
(float)2 | an int converted | 2.0 | the 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:
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.0fisfloat / float: real division. If I’d written/ 4it would also be real (becausetotalis already afloat), but4.0fmakes it clear we want decimals.- The weights carry an
f(0.40f) so the whole calculation isfloat. Without thefthey’d bedoubleand C would convert the result when storing it. It works the same, but this way you don’t mix types by accident. (int)averageand(int)(average + 0.5f)are the two casts from the theory table: chop and round.average >= 5.0fis 1 or 0 and is stored in anint.merituses&&: 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.
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 %:
| Grade | Weight | Contributes in the weighted one | Would contribute at 25 % | Difference | Why |
|---|---|---|---|---|---|
| Theory 7.5 | 40 % | 3.000 | 1.875 | +1.125 | it weighs more than in the normal average |
| Practice 8.0 | 30 % | 2.400 | 2.000 | +0.400 | it also weighs a bit more |
| Test 6.5 | 20 % | 1.300 | 1.625 | −0.325 | it weighs a bit less |
| Project 9.0 | 10 % | 0.900 | 2.250 | −1.350 | the 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):
average | average + 0.5f | (int) | Why |
|---|---|---|---|
| 7.75 | 8.25 | 8 | the decimal part was 0.5 or more: it moves up to the next integer |
| 7.50 | 8.00 | 8 | exactly 0.5 also goes up |
| 7.49 | 7.99 | 7 | it doesn’t reach 8, and chopping leaves it at 7 |
| 7.25 | 7.75 | 7 | the 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
meritbecomes 0. - Add a
distinctionvariable that is 1 if the average is 9 or more, without usingif.
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 positiondni % 23. It’s the official algorithm: the remainder, between 0 and 22, picks the letter. Strings are arrays ofchar, 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 + 32works because in ASCII the lowercase version of a letter is 32 places further on.credits * 100.0f / DEGREE_CREDITS: the100.0fmakescredits * 100.0fafloatand the division real. With100it 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:
| Line | You type | What it stores | What is left waiting | Why |
|---|---|---|---|---|
scanf("%d", &dni) | 12345678 + Enter | dni = 12345678 | the Enter | %d stops at the first character that isn’t a digit |
scanf(" %c", &first_initial) | S + Enter | first_initial = 'S' (83) | the Enter | the space skips the Enter after the DNI and %c takes the S |
scanf(" %c", &surname_initial) | M + Enter | surname_initial = 'M' (77) | the Enter | the same with the Enter after the S |
scanf("%d", &age) | 19 + Enter | age = 19 | the Enter | %d already skips leading Enters on its own |
scanf("%f", &avg_grade) | 7.75 + Enter | avg_grade = 7.75 | the 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:
%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 / bwith twointgives an integer even if stored in afloat. Put the cast on an operand. - Forgetting the
&in scanf: it compiles with a warning and the usual result is aSegmentation fault. %cwithout 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 haveif, there’s no way to avoid it. - A specifier that doesn’t match the type:
%dfor afloator%ffor anintgives garbage. Always read the-Wallwarnings. - 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:
- When the
wrongline runs, its box shows 2: the integer division happens before storing in thefloat. - On the
rightline, the box shows 2.333…: the cast was applied before dividing. remainderis 1 and, with the 2 inwrong, satisfies 3 × 2 + 1 = 7.passedis 0 because 2.333 doesn’t reach 5: a comparison is a number.- In
letterthe Z appears (code 90): the modulo picked position 14 of the string.
Summary
- Division between two
intis integer division; the(float)cast has to go on an operand, before dividing. %gives the remainder and, together with integer division, satisfiesb * (a / b) + a % b == a.(int)xchops the decimals and(int)(x + 0.5f)rounds positive numbers.- A comparison is 1 or 0 and can be stored in an
intwithout usingif. - A
charis 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 / band(float)(a / b)give different results? - Have you seen the
Floating point exceptionwhen 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
-Walland 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 →



