Adding Binary Numbers: Carries, Adders and Overflow

Every calculation a computer does comes down to adding bits. Inside the processor, a circuit called an adder adds two binary numbers column by column, just as you add on paper, but it only has room for a fixed number of bits. In this lesson you will add binary numbers by hand, see the logic gates that do it in hardware, find out what happens when the answer is too big for its register (overflow), and watch the same thing happen in C. It follows on from Power Protection and Types of Computers, and it builds on word size from Memory Types and Features.

What you will learn

  • The four rules for adding one column of bits, plus the rule for a column with a carry in.
  • How to add two 4-bit or 8-bit numbers, showing every carry, and how to check the answer in decimal.
  • How a half adder and a full adder are built from logic gates, and how full adders join to make a ripple-carry adder.
  • What overflow is, how to spot it, and the range of unsigned numbers that n bits can hold.
  • How C stores the result of adding two unsigned values, and why it can print an answer that looks wrong.

Part 1: A quick reminder about place values

In binary, each column is worth twice the column to its right: 1, 2, 4, 8, 16, 32, 64, 128 and so on. To read a binary number, add the place values of the columns that hold a 1. For example, 0110 1101 = 64 + 32 + 8 + 4 + 1 = 109. We write long binary numbers in groups of four bits so they are easier to read. (If you need more practice converting, see Decimal to binary and Binary Manipulation.)

Place value1286432168421
10901101101
5900111011

Part 2: Adding binary numbers by hand

The rules for one column

There are only two digits, so a column fills up quickly. As soon as a column adds up to 2 or more, you write down the units digit and carry 1 to the next column on the left, exactly like carrying a ten in decimal.

In the columnTotal in decimalIn binaryWriteCarry
0 + 00000
0 + 1 or 1 + 01110
1 + 121001
1 + 1 + carry 131111

The last row matters most. Every column except the rightmost one may receive a carry from the right, so it can have three bits to add. The total is never more than 3, so the carry out of a column is never more than 1.

Worked example 1: a 4-bit sum

Add 0101 (5) and 0011 (3). Write the carries above the columns as you go, starting from the right.

Carry    1 1 1
A        0 1 0 1     (5)
B      + 0 0 1 1     (3)
         -------
Sum      1 0 0 0     (8)
  1. Column 1 (value 1): 1 + 1 = 2 = binary 10. Write 0, carry 1.
  2. Column 2 (value 2): 0 + 1 + carry 1 = 2. Write 0, carry 1.
  3. Column 3 (value 4): 1 + 0 + carry 1 = 2. Write 0, carry 1.
  4. Column 4 (value 8): 0 + 0 + carry 1 = 1. Write 1, carry 0.
  5. Check: 1000 = 8, and 5 + 3 = 8. ✔

Notice how one carry can travel (“ripple”) through several columns. Keep that picture in mind: it is exactly how the hardware adder in Part 3 works.

Worked example 2: an 8-bit sum

Add 0110 1101 (109) and 0011 1011 (59).

Carry    1111 111
A        0110 1101     (109)
B      + 0011 1011     (59)
         ---------
Sum      1010 1000     (168)

Every column from the right produces a carry until the leftmost column, which has 0 + 0 + carry 1 = 1 and so carries nothing out. Check: 1010 1000 = 128 + 32 + 8 = 168, and 109 + 59 = 168. ✔ Step through this sum yourself in Try it 1, then try your own numbers.

Always check in decimal. Convert both numbers and the answer to decimal. If the decimal sum does not match, look for a column where you forgot a carry. That is the most common mistake.

Try it 1Column-by-column binary adder

Choose a size, type two whole numbers (or tap Random), then tap Next column. The adder works from the right, exactly as you would on paper, and shows every carry. Turn on Predict mode to work out each column yourself before it is shown.

Part 3: Adders in hardware

The processor’s arithmetic logic unit (ALU) adds with logic gates. If the gates are new to you, read Logic Gates – Formal Introduction first. Look back at the column rules and compare them with the gate truth tables:

  • The bit you write is 1 when exactly one of the two bits is 1. That is the XOR gate.
  • The bit you carry is 1 only when both bits are 1. That is the AND gate.

Half adder

A half adder adds two bits, A and B. It has two outputs: Sum = A XOR B, and Carry = A AND B. It is called "half" because it has no input for a carry coming from the right, so it can only be used for the rightmost column.

Half adder circuit: inputs A and B go into an XOR gate that gives S, and into an AND gate that gives C
A half adder. The XOR gate gives the sum S and the AND gate gives the carry C. Diagram: Inductiveload, public domain.
ABSum (A XOR B)Carry (A AND B)
0000
0110
1010
1101

Full adder

A full adder adds three bits: A, B and the carry in (Cin) from the column on the right. It can be built from two half adders and an OR gate:

  • Sum = A XOR B XOR Cin (the sum is 1 when an odd number of the inputs are 1).
  • Carry out = (A AND B) OR ((A XOR B) AND Cin) (the carry is 1 when at least two of the inputs are 1).
Full adder circuit: two XOR gates in series give S; two AND gates feed an OR gate that gives C out
A full adder. Two XOR gates give the sum S; two AND gates and an OR gate give the carry out. (The dashed "carry-block" label is not needed for CAPE.) Diagram: Inductiveload, public domain.
ABCinSumCout
00000
00110
01010
01101
10010
10101
11001
11111

Read each row as an ordinary sum and the table makes sense: the two outputs, Cout then Sum, are just the total of the three inputs written in binary. For example, the last row is 1 + 1 + 1 = 3 = binary 11.

Try it 2Half adder and full adder explorer

Choose the circuit, then tap the inputs to switch them between 0 and 1. The outputs, the gate-by-gate working and the matching row of the truth table update straight away.

    Ripple-carry adder

    To add two 8-bit numbers, chain 8 full adders side by side, one per column. The carry out of each adder is wired to the carry in of the adder on its left. (The rightmost adder’s carry in is set to 0, or it can be a half adder.) This is a ripple-carry adder, because a carry may have to ripple through every stage before the answer is ready. That is exactly what you saw in Worked example 2. The two numbers usually come from registers, and the answer is stored in a register, which is a row of flip-flops like the one in The SR Latch.

    Wider adders are slower, because the last column has to wait for the carry to arrive. Real processors use faster designs (such as carry-lookahead adders), but CAPE expects you to know the half adder, the full adder and how they are joined.

    Part 4: Fixed width and overflow

    A register, and an adder, has a fixed number of bits. That number is usually the processor’s word size (see Memory Types and Features). With n bits, the unsigned whole numbers you can store go from 0 to 2n − 1.

    Bits (n)Number of patterns (2n)Unsigned range
    4160 to 15
    82560 to 255
    1665,5360 to 65,535
    324,294,967,2960 to 4,294,967,295

    Adding two n-bit numbers can give an answer that needs n + 1 bits. If the register has only n bits, the extra bit (the carry out of the leftmost column) is lost. This is called overflow.

    Worked example 3: overflow in 8 bits

    Add 1100 1000 (200) and 0110 0100 (100) in an 8-bit register.

    Carry  1 1
    A        1100 1000     (200)
    B      + 0110 0100     (100)
             ---------
    Full   1 0010 1100     (300)
    Kept     0010 1100     (44)

    The true answer, 300, needs 9 bits. The register keeps only the lowest 8 bits, 0010 1100, which is 44. The 256 that the lost carry was worth has gone: 300 − 256 = 44.

    Rule for unsigned numbers: the addition overflowed if, and only if, there is a carry out of the leftmost column. A 1 in the leftmost sum bit is not overflow. For example, 0100 + 0100 = 1000 (4 + 4 = 8) fits in 4 bits.

    A look ahead. When the same bits stand for signed numbers (two’s complement, the next lesson), the rule changes: the carry out is simply thrown away, and overflow happens when two numbers with the same sign give an answer with the other sign. Try it 3 shows both readings so that you can compare them.

    Try it 3Overflow checker

    Pick a register size and two unsigned numbers. The checker shows the full sum, what the register can keep, and whether the addition overflowed. Or tap one of the examples.

    Part 5: Binary addition in C

    C variables have fixed widths too. On most computers an unsigned char has 8 bits, an unsigned short has 16 bits and an unsigned int has 32 bits. When the total of an unsigned addition is too big, C does what the hardware does: it keeps the lowest bits and drops the carry. (If printf and format specifiers are new to you, see Variables, format specifiers and printf.)

    #include <stdio.h>
    
    int main(void)
    {
        unsigned char a = 200;  /* 1100 1000 */
        unsigned char b = 100;  /* 0110 0100 */
    
        /* sum keeps only 8 bits */
        unsigned char sum = a + b;
    
        /* full has room for the carry */
        unsigned int full = a + b;
    
        printf("Full total: %u\n", full);
        printf("Kept in 8 bits: %d\n", sum);
    
        if (full > 255)
            printf("Overflow: carry lost\n");
    
        return 0;
    }
    

    Output:

    Full total: 300
    Kept in 8 bits: 44
    Overflow: carry lost

    a + b is worked out in a wider type (C first turns small types into int), so full really is 300. When the result is stored in the 8-bit sum, only the lowest 8 bits fit, so it becomes 44. That is Worked example 3 again. For unsigned types, C guarantees this wrap-around: the result is the remainder after dividing by 2n.

    Warning about signed types. If a signed int overflows, the C standard says the behaviour is undefined: the program may print a strange number, or the compiler may assume it never happens. Use unsigned types when you want wrap-around, and check ranges before you add.

    Try it 4What will C print?

    Choose an unsigned C type and two values. The program and its output change to match. Tap Add 1 to a again and again near the top of the range to watch the value wrap around, like a car’s odometer rolling over.

    
    

    Output:

    
    

    A ripple-carry adder in C

    This program adds two 8-bit numbers the way the hardware does: one column at a time, from right to left, passing the carry along. Each pass of the loop is one full adder. The bits are kept in arrays (see Arrays in C), with bit 0, the rightmost bit, stored first.

    #include <stdio.h>
    
    int main(void)
    {
        /* Bit 0 (the rightmost bit) is   */
        /* stored first, so the bits look */
        /* backwards.                     */
    
        /* 0110 1101 = 109 */
        int a[8] = {1,0,1,1,0,1,1,0};
        /* 0011 1011 = 59 */
        int b[8] = {1,1,0,1,1,1,0,0};
        int sum[8];
        int carry = 0;
        int total, i;
    
        /* one full adder per column, */
        /* from right to left         */
        for (i = 0; i < 8; i++)
        {
            /* total is 0, 1, 2 or 3 */
            total = a[i] + b[i] + carry;
            sum[i] = total % 2;  /* write */
            carry = total / 2;   /* carry */
        }
    
        printf("Sum:       ");
        for (i = 7; i >= 0; i--)
            printf("%d", sum[i]);
        printf("\nCarry out: %d\n", carry);
    
        return 0;
    }
    

    Output:

    Sum:       10101000
    Carry out: 0

    That is 168, the answer to Worked example 2. Notice that total % 2 gives the sum bit and total / 2 gives the carry, the same as reading the full adder truth table as an ordinary sum. Change the arrays to hold 200 and 100 and run it again: the carry out becomes 1, which means overflow.

    Summary

    IdeaKey points
    Column rules0+0 = 0; 0+1 = 1; 1+1 = 10 (write 0, carry 1); 1+1+1 = 11 (write 1, carry 1). Work from the right.
    CheckingConvert both numbers and the answer to decimal.
    Half adderTwo inputs. Sum = A XOR B; Carry = A AND B. No carry in.
    Full adderThree inputs (A, B, Cin). Sum = A XOR B XOR Cin; Cout = (A AND B) OR ((A XOR B) AND Cin).
    Ripple-carry addern full adders in a chain; each carry out feeds the next carry in.
    Unsigned rangen bits hold 0 to 2n − 1.
    Overflow (unsigned)A carry out of the leftmost column. The register keeps only the lowest n bits.
    CUnsigned types wrap around (the result is the remainder after dividing by 2n). Signed overflow is undefined behaviour.

    Practice questions

    1. Add 1011 0110 and 0101 1101, showing your carries. Give the answer in binary and in decimal, and say whether it fits in 8 bits.

    Show answer

    182 + 93 = 275. Full answer: 1 0001 0011 (9 bits). It does not fit in 8 bits: an 8-bit register keeps 0001 0011 = 19, so there is an overflow (275 − 256 = 19).

    2. Explain the difference between a half adder and a full adder.

    Show answer

    A half adder adds two bits and gives a sum and a carry; it has no carry input. A full adder adds three bits (A, B and a carry in from the column on the right), so it can be used for every column of a multi-bit addition.

    3. Write Boolean expressions for the Sum and Carry out of a full adder with inputs A, B and Cin.

    Show answer

    Sum = A XOR B XOR Cin. Cout = (A AND B) OR ((A XOR B) AND Cin). (Cout = AB + ACin + BCin is also correct.)

    4. How many full adders are needed in a ripple-carry adder for two 16-bit numbers? Why is it called "ripple-carry"?

    Show answer

    16 full adders (or 15 full adders and a half adder for the rightmost bit). A carry produced in one column may travel, or ripple, through every stage to the left before the final answer is ready.

    5. A 4-bit register holds 1101. The value 0101 is added to it. What does the register hold afterwards, and has overflow happened? Treat both as unsigned.

    Show answer

    13 + 5 = 18 = 1 0010. The register keeps 0010 (2). There is a carry out of the leftmost column, so an unsigned overflow has happened.

    6. State the range of unsigned whole numbers that 12 bits can hold. What is the smallest number of bits needed to store 1000?

    Show answer

    0 to 4095 (212 − 1). 1000 needs 10 bits, because 29 − 1 = 511 is too small and 210 − 1 = 1023 is big enough.

    7. In C, unsigned short s = 65535; is followed by s = s + 1;. On a computer with 16-bit shorts, what is the value of s? Explain.

    Show answer

    0. 65535 is 1111 1111 1111 1111, the largest 16-bit unsigned value. Adding 1 gives 1 0000 0000 0000 0000 (65536), which needs 17 bits. Only the lowest 16 bits are kept, which are all 0.

    8. Explain why the sum of two n-bit unsigned numbers never needs more than n + 1 bits.

    Show answer

    The largest n-bit number is 2n − 1. The biggest possible sum is 2 × (2n − 1) = 2n+1 − 2, which is less than 2n+1, so it always fits in n + 1 bits. That is why each column carries at most 1.

    Homework

    1. Make up three pairs of 8-bit numbers: one whose sum fits easily, one that only just fits (a total of exactly 255) and one that overflows. Add each pair by hand, showing the carries, then check them with Try it 1 and Try it 3.
    2. Draw a 4-bit ripple-carry adder as four boxes labelled "Full adder". Label every input and output, and show where the carries go. Then trace 0111 + 0110 through your diagram, writing the value on every wire.
    3. Copy the ripple-carry program into Code::Blocks. Change it so that it also converts the sum back to decimal and prints it. (Hint: add 2 to the power of i for every sum bit that is 1.)

    Exam tips

    • 2009 Unit 1 Paper 02, Question 1(d)(ii). This part asks you to add two 4-bit binary numbers whose total does not fit in 4 bits. It tests careful column-by-column carrying and whether you notice that the answer has grown to five bits. Show your carry row, give the full answer, and say in words that it cannot be stored in four bits. The other parts of 1(d) move on to reading binary in decimal, the largest and smallest values in four bits, and two’s complement, so revise them together. Try it yourself first, then compare with the solution on this site: 2009 U1 Q1.
    • Specimen Unit 1 Paper 01 (2021), Item 5. A multiple-choice item on what the term word size means. It tests whether you know that the word size is the number of bits the processor handles at once, which is also the width of its registers and adder and so sets the overflow limit in this lesson. Open the specimen paper and try it before you check the key.
    • Coming next: Specimen Unit 1 Paper 01 (2021), Items 1 and 2, and 2024 Unit 1 Paper 02, Question 2(c). These give an 8-bit pattern or a negative number and ask about its signed magnitude or two’s complement form, or about the range of signed values in 8 bits. They belong to the next lesson, but they rely on the fixed-width addition you practised here. See the solution 2024 U1 Q2 once you have tried it.
    • Half and full adders. Adders are named in the syllabus (Unit 1, Module 1, Specific Objective 2), but I have not found a question on them in the past papers, specimen papers or solutions on this site so far. Learn the two truth tables and the Boolean expressions anyway, and be ready to draw both circuits.
    • More worked answers are on the CS Solutions page.

    General advice (from the lesson content, not from a particular paper): always show the carry row; write binary in groups of four; check every answer in decimal; and when a question gives a number of bits, keep exactly that many bits and say clearly whether the answer overflowed.

    Previous: Power Protection and Types of Computers. Related: Memory Types and Features (word size) and The SR Latch (how a register stores bits). Next: signed numbers, two’s complement and signed overflow (coming soon in this course). For extra practice now, see Binary Manipulation and the Data Representation Homework Exercise.

    Syllabus link: CAPE Computer Science (CXC A19/U2/21), Unit 1, Module 1: Computer Architecture. Specific Objective 2: describe the basic building blocks of a computer (truth tables; logic gates; adders). Specific Objective 3: interpret the interaction among the basic building blocks of a computer (logic gates, registers). Specific Objective 4: explain how data is represented in a computer system (bits; bytes; number bases). U1 M1 SO2, SO3, SO4.

    Video search terms

    Search YouTube for: "binary addition with carries", "half adder and full adder explained", "ripple carry adder", "unsigned integer overflow".

    Try it 5Quick quiz

    Tap an answer. All eight questions are self-checks on this lesson.

    Attributions to media used in this post:

    Half adder diagram: Inductiveload, public domain, via Wikimedia Commons (File:Half Adder.svg).

    Full adder diagram: Inductiveload, public domain, via Wikimedia Commons (File:Full-adder logic diagram.svg).

    Updates

    11 Nov 2026

    - Draft created.

    © 2026 Vedesh Kungebeharry. All rights reserved.

    Binary Representation and Manipulation: A Step-by-Step Guide

    Computer Science – Number Systems and Data Representation

    Computers store integers as patterns of bits. This tutorial explains how binary works, how to perform arithmetic, and how signed magnitude and two’s complement represent negative values.

    Learning objectives

    • Convert positive decimal integers to binary and back.
    • Add and subtract binary integers.
    • Explain signed magnitude and two’s complement.
    • Represent signed integers using a specified number of bits.
    • Determine the range of integers supported by two’s complement.

    1. Understanding binary numbers

    A bit is a binary digit: 0 or 1. Decimal (base 10) uses powers of 10; binary (base 2) uses powers of 2. The place values, from right to left, are 1, 2, 4, 8, 16, 32 and so on.

    Binary place value8421
    Binary 01100110

    Convert binary to decimal

    Multiply each binary digit by its place value and add the results.

    110₂ = (1 × 4) + (1 × 2) + (0 × 1) = 6₁₀. Similarly, 11₂ = (1 × 2) + (1 × 1) = 3₁₀.

    The subscript ₂ means binary and ₁₀ means decimal.

    2. Converting decimal to binary

    Repeatedly divide the positive decimal number by 2, recording the quotient and remainder. Stop when the quotient becomes 0. Read the remainders from bottom to top.

    Worked example: Convert 13₁₀ to binary

    DivisionQuotientRemainder
    13 ÷ 261
    6 ÷ 230
    3 ÷ 211
    1 ÷ 201

    Reading the remainders upwards gives 13₁₀ = 1101₂. Check: 8 + 4 + 0 + 1 = 13.

    Try it: Convert 6, 9 and 18 to binary before reading the answers below.

    3. Binary addition

    OperationResult
    0 + 00
    0 + 11
    1 + 01
    1 + 110 (write 0, carry 1)

    Worked example: Add 6 and 3

    6₁₀ = 0110₂ and 3₁₀ = 0011₂.

        0110
      + 0011
      ------
        1001

    Therefore, 0110₂ + 0011₂ = 1001₂. Check: 6 + 3 = 9, and 1001₂ = 8 + 1 = 9. Add from the right, carrying when a column totals 2 or 3.

    4. Binary subtraction

    Subtract from right to left. When you encounter 0 − 1, borrow from the next available 1 to the left. A borrowed 1 represents binary 10 (decimal 2) in the current column.

    Worked example: Subtract 3 from 6

        0110
      - 0011
      ------
        0011

    In the rightmost column, 0 − 1 requires borrowing. The next column then also requires borrowing from the column to its left. The answer is 0011₂ = 3₁₀, as expected.

    5. Signed magnitude representation

    For signed magnitude, the most significant bit (MSB) is the sign: 0 for positive, 1 for negative. The remaining bits give the magnitude (absolute value). The number of bits must be specified.

    Decimal8-bit signed magnitude
    +600000110
    −610000110
    +300000011
    −310000011

    An 8-bit signed-magnitude system represents values from −127 to +127. It has two encodings for zero: positive zero (00000000) and negative zero (10000000).

    6. Two’s complement representation

    Two’s complement is widely used for signed integers. To represent a negative number with a fixed number of bits:

    1. Write the positive integer in binary using the required bit width.
    2. Invert every bit (0 becomes 1; 1 becomes 0).
    3. Add 1.

    Worked example: Represent −6 using 8 bits

    Step 1: +6 = 00000110

    Step 2: Invert all bits → 11111001

    Step 3: Add 1.

      11111001
    +        1
    ----------
      11111010

    Therefore, −6 = 11111010 in 8-bit two’s complement.

    Shortcut: Copy and invert

    Starting at the right, copy digits up to and including the first 1; then invert every digit further left. Applied to 00000110, this produces 11111010.

    Comparing signed magnitude and two’s complement

    DecimalSigned magnitude (8 bits)Two’s complement (8 bits)
    +60000011000000110
    −61000011011111010
    +30000001100000011
    −31000001111111101

    Important: The same bit pattern can mean different values depending on which representation is used. The MSB of a two’s complement number has a negative place value, unlike the separate sign bit in signed magnitude.

    Optional concept explanations: The next two notes go beyond the basic conversion and arithmetic procedures. They are provided for students who want to understand why two’s complement works. You may skip them on a first reading and return to them after practising the examples.

    Concept note: Why the leftmost bit is negative in two’s complement

    Reconciliation note: In a fixed-width two’s complement number, the most significant bit (MSB) carries a negative place value. It is not a separate sign bit as it is in signed magnitude. For three bits, the weights from left to right are −4, +2 and +1, instead of +4, +2 and +1.

    There are 2³ = 8 different three-bit patterns. Using two’s complement, these represent all integers from −4 through +3:

    Decimal value3-bit two’s complementUsing weights −4, +2, +1
    00000
    +10011
    +20102
    +30112 + 1
    −1111−4 + 2 + 1
    −2110−4 + 2
    −3101−4 + 1
    −4100−4

    Check the negatives: 111 = −4 + 2 + 1 = −1; 110 = −4 + 2 = −2; 101 = −4 + 1 = −3; and 100 = −4.

    Why this makes sense: A three-bit system has eight patterns but cannot represent every integer. By giving the MSB a weight of −4, two’s complement uses those patterns to represent four non-negative values (0 to +3) and four negative values (−1 to −4), with only one representation of zero. This is a mathematical interpretation of the two’s complement system, not a historical claim about its invention.

    One subtlety: In binary pattern order, 011 is followed by 100. As signed three-bit values, those mean +3 and −4. Adding 1 to +3 therefore overflows the signed range; it does not mean +3 + 1 equals −4 in ordinary mathematics.

    Concept note: Why do we add 1 in two’s complement?

    First, an important distinction: It is one’s complement (and signed magnitude), not two’s complement, that has both positive zero and negative zero. In one’s complement, changing a positive value to its negative requires only flipping every bit. For example, in 3 bits, 000 is +0 and 111 is −0.

    Two’s complement uses invert the bits, then add 1. That extra 1 changes the negative-number patterns so 111 becomes −1 instead of −0, while 000 is the only zero. The freed-up bit pattern 100 represents −4, giving the 3-bit two’s complement range −4 to +3.

    Compare every possible 3-bit pattern:

    3-bit patternOne’s complement valueTwo’s complement value
    000+00
    001+1+1
    010+2+2
    011+3+3
    100−3−4
    101−2−3
    110−1−2
    111−0−1

    Worked example: Find −2 using 3-bit two’s complement. Start with +2 = 010. Flip its bits to obtain 101 (this is −2 in one’s complement). Add 1: 101 + 001 = 110. In two’s complement, 110 is −2 because (1 × −4) + (1 × 2) + (0 × 1) = −2.

    What happens to negative zero? Invert 000 to get 111, then add 1: 111 + 001 = 1000. With only 3 bits, discard the carry beyond the third bit, leaving 000. So negative zero becomes the same bit pattern as zero: no separate −0.

    Why the arithmetic works: step by step (optional)

    Step 1 — There are eight patterns. With 3 bits, there are 2³ = 8 possible patterns, from 000 to 111. The largest unsigned 3-bit value is 7 (111).

    Step 2 — Flipping bits gives the complement to 7, not to 8. Let us start with +2, written as 010. When we flip every bit, we obtain 101, which is 5 if read as an unsigned number. Notice that 2 + 5 = 7 (binary 111), not 8. This is why simply inverting the bits gives one’s complement.

    Step 3 — Adding 1 completes the full eight. Add 1 to 101 to get 110 (6 as an unsigned value). Now 2 + 6 = 8, which is 1000 in binary. In a fixed-width 3-bit operation, the leftmost carry is discarded, leaving 000. Thus 110 acts as −2 when added to +2 using 3-bit arithmetic.

      010   (+2)
    + 110   (−2 in 3-bit two’s complement)
    -----
     1000   (discard the carry beyond 3 bits)
      000   (zero)

    Step 4 — That lets subtraction use addition. To calculate 3 − 2, write +3 as 011 and −2 as 110. Add them as ordinary binary numbers: 011 + 110 = 1001. Keep the lowest 3 bits, 001, which equals +1. Therefore, 3 + (−2) = 1.

    General rule: With n bits, flipping the bits of a number x produces (2n − 1) − x. Adding 1 produces 2n − x. Consequently, x + (2n − x) = 2n, whose lowest n bits are all zero. This is the mathematical reason for the “+1”. It gives an additive inverse using fixed-width binary arithmetic and also eliminates the separate negative-zero representation found in one’s complement.

    Important limitation: This works for results representable within the chosen signed bit width. A calculation outside the range (−4 to +3 for three bits) causes signed overflow, so discarding a carry must not be mistaken for a valid result in every case.

    7. Subtraction using two’s complement

    Subtraction can be rewritten as addition: 6 − 3 = 6 + (−3).

    Represent +6 as 00000110 and −3 as 11111101 in 8-bit two’s complement.

        00000110  (+6)
      + 11111101  (−3)
      ----------
      1 00000011

    Discard the carry beyond the eighth bit. The 8-bit result is 00000011 = +3. In signed arithmetic, also check whether the true result fits the selected bit width; discarding the carry alone does not guarantee that overflow has not occurred.

    8. Finding the largest and smallest two’s complement integers

    For an n-bit two’s complement system, the largest integer is 2n−1 − 1 and the smallest is −2n−1.

    Worked example: A 4-bit system

    Largest: 2³ − 1 = +7. Smallest: −2³ = −8.

    4-bit two’s complementDecimal
    0111+7
    00000
    1111−1
    1000−8

    The 4-bit two’s complement range is −8 to +7, whereas 4-bit signed magnitude represents −7 to +7.

    9. Common mistakes to avoid

    MistakeCorrect approach
    Reading division remainders from the topRead them from the bottom to the top.
    Forgetting to carry in binary additionCarry 1 when a column totals binary 10 or 11.
    Changing only the sign bit for two’s complementInvert all bits and add 1.
    Using an inconsistent number of bitsKeep a fixed, stated bit width for signed calculations.
    Assuming every discarded carry means a valid signed resultCheck for signed overflow as well.
    Assuming the greatest 4-bit signed integer is 15It is +7 in 4-bit two’s complement.

    10. Practice exercises

    1. Convert 19₁₀ to binary.
    2. Convert 101101₂ to decimal.
    3. Add 1011₂ and 0110₂.
    4. Subtract 0101₂ from 1100₂ using ordinary binary subtraction.
    5. Represent −9 in 8-bit two’s complement.
    6. Calculate 7 − 6 using 8-bit two’s complement addition.
    7. State the lowest and highest integers that 6-bit two’s complement can represent.

    Answers

    QuestionAnswer
    110011₂
    245₁₀
    310001₂ (17₁₀)
    40111₂ (7₁₀)
    511110111
    600000001 (+1)
    7−32 to +31

    11. Related lessons and further practice

    Final takeaway

    Binary representation is more than memorising strings of zeros and ones. Understanding place values, carrying, borrowing, signed magnitude and two’s complement helps explain how computers store and manipulate integer data. Verify answers by converting back to decimal whenever possible.

    © 2026 Vedesh Kungebeharry. All rights reserved.

    The SR Latch

    A latch is a small circuit that can remember one bit. In this lesson you will build the simplest one, the SR latch, from two NOR gates, test it, break it, and then build it again from NAND gates. Every section has a Try it box so you can work the circuit yourself, on a computer or on your phone.

    Background reading: this lesson sits alongside two earlier posts. Flip Flops gives the definitions of combinational and sequential circuits and the Stallings reading, and The SR Flip-Flop – Practical Introduction walks through the class demonstration step by step, with a timing diagram.

    Why do we need memory?

    Every gate you have met so far is combinational: its output depends only on its inputs right now. If you take your finger off the input, the output goes back. You saw this in Truth Tables – An application of abstraction to physical circuits and Logic Gates – Formal Introduction: one row of the truth table for each set of inputs, and nothing else matters.

    A computer needs more than that. It has to keep a value after the input has gone: the number you typed, the next instruction to run, the result of a sum. A circuit whose output depends on its inputs and on what it was doing before is called a sequential circuit. The trick that makes it work is feedback: the output of a gate is wired back into the input of another gate.

    Build it: two cross-coupled NOR gates

    Recall the NOR gate. Its output is 1 only when both inputs are 0. One useful way to remember it: any 1 into a NOR gate forces its output to 0.

    ABA NOR B
    001
    010
    100
    110

    Now take two NOR gates, G1 and G2, and cross-couple them: the output of each one goes into an input of the other. That leaves one free input on each gate. These are the latch inputs, S (Set) and R (Reset). The outputs are Q and Q (read “Q-bar”, sometimes written Q’), which should always be opposites.

    • G1 has inputs R and Q. Its output is Q, so Q = NOR(R, Q).
    • G2 has inputs S and Q. Its output is Q, so Q = NOR(S, Q).

    Notice that R goes into the gate that makes Q. That looks back-to-front at first, but it makes sense: R = 1 forces that gate to output 0, and Reset means Q = 0.

    The simulator below is the one from The SR Flip-Flop – Practical Introduction. It writes Q as Q’ (Q-prime), which means the same thing. Use the switches (or tap the S and R circles), try Step by step mode to watch one gate at a time, and follow the guided tour of the class scenarios.

    Try it 1Play with the SR latch

    This is the latch described above: two NOR gates, with the top gate (G1) making Q and the bottom gate (G2) making Q’. Each output is fed back into the other gate. Flip S (Set) and R (Reset) and watch what happens.

    Key: wire = 1 (high)   wire = 0 (low)   unknown (?)

    SR latch made from two cross-coupled NOR gates G1NOR G2NOR R S 0 1 0 0 R Q’ Q S Q = 0 Q’ = 1 Q Q’ Feedback: Q goes back into G2, Q’ goes back into G1
    Mode:
    NOR gate reference
    ABA NOR BUsed by
    001
    010
    100
    110

    G1: A = R, B = Q’
    G2: A = S, B = Q

    What the signals are doing:
      Current state

      Hold

      SR latch truth table (NOR version)
      SRQ (next)Q’ (next)State
      00Q (no change)Q’ (no change)Hold (memory)
      0101Reset
      1010Set
      1100Invalid (forbidden)

      The highlighted row matches the switches right now.

      Guided tour: the class scenarios

      Tip: switch to Step by step mode first, then press Next to watch each gate work in turn.

      Timing diagram

      Every time the switches change, a new time slot is added. Drag the slider (or tap a slot) to move the cursor: the circuit above jumps to that moment.

      How to read a timing diagram
      • Time runs left to right. Each column (t0, t1, t2…) is one moment, one after the other.
      • High means 1, low means 0. When a line is at the top of its row the signal is 1; at the bottom it is 0.
      • Read straight down. Pick one column (or use the cursor) and read down the S, R, Q and Q’ rows to see every signal at that same moment.
      • Edges are changes. A vertical jump in a line is an edge: going up is a 0 → 1 change (rising edge), going down is 1 → 0 (falling edge).
      • Q only changes when S or R tells it to. Look for an S pulse (Q goes high) or an R pulse (Q goes low). When S and R are both 0, Q stays flat: that flat line is the latch’s memory.
      • Normally Q’ is the mirror image of Q. Wherever the two lines are NOT opposites, something is wrong.
      • Spot the invalid region. The red-shaded slot is where S = 1 and R = 1: Q and Q’ are both 0. The amber slot after it is the race when both are released together: the result is unpredictable.
      The SR latch characteristic table

      A NOR gate’s truth table only needs its two inputs. A latch is different: it is a memory element, so what happens next depends on the inputs and on what it is already storing. A characteristic table shows this. It lists S, R and the present state Q(t) (the value of Q before the change) and gives the next state Q+ (the value of Q after the latch settles).

      SRQ(t)Q+ (t+1)Action
      0000Hold
      0011Hold
      0100Reset
      0110Reset
      1001Set
      1011Set
      110XInvalid
      111XInvalid

      • How to read a row: pick the S and R values, then the value Q had before. The Q+ column tells you what Q will be next. For example, the row S = 0, R = 1, Q(t) = 1 says: “Q was 1, we pressed Reset, so Q becomes 0.” The highlighted row follows the switches above (and the timing cursor).
      • Why S = 0, R = 0 gives Q+ = Q: with no Set or Reset signal, each gate is kept where it is by the output fed back from the other gate. So Q+ simply copies Q(t): if it was 1 it stays 1, if it was 0 it stays 0. That is the latch’s memory (Hold).
      • Why S = 1, R = 1 is marked X: both NOR gates are forced to 0, so Q = Q’ = 0, which breaks the rule that Q’ is the opposite of Q. And when both inputs are released together the gates race, so the next Q cannot be predicted. We mark it X (forbidden) and never use it.
      • Where the equation comes from: look at the rows where Q+ = 1. Either S = 1 (Set), or S = 0, R = 0 and Q(t) = 1 (Hold a 1). Ignoring the forbidden rows, Q+ is 1 when “S is 1, OR R is 0 AND Q is 1”. Written in Boolean algebra that is Q+ = S + R’Q, with the rule SR = 0 (S and R are never both 1).

      Q+ = S + R’Q (with SR = 0)

      Quick check

      Challenges

      Use the switches above. Before each press, predict what Q will be, then check! The ticks fill in by themselves.

      • ✓Set the latch (Q = 1), then turn S back to 0 and show that Q remembers 1.
      • ✓Reset the latch (Q = 0), then turn R back to 0 and show that Q remembers 0.
      • ✓Go into the forbidden state (S = 1, R = 1), then press Release S and R together and watch the race. Try it a few times: is Q always the same?

      Challenge question: looking at your timing diagram, can you find a time slot where S = 0 and R = 0 but Q = 1? Explain why that can happen.

      Things to try in the box above:

      1. Make S = 1, then put it back to 0. Q stays 1 even though S is back to 0. That is memory.
      2. Now make R = 1, then put it back to 0. Q stays 0.
      3. With S = 0 and R = 0, the latch can be showing Q = 0 or Q = 1. The inputs are the same, so the only thing deciding the output is what happened before.

      Predict, then test

      Here is the full behaviour of the NOR latch. "Q (next)" means the value of Q after the gates have settled.

      SRQ (next)Q (next)What it does
      00Q (no change)Q (no change)Hold (memory)
      0101Reset
      1010Set
      1100Forbidden (not allowed)

      Do not just learn the table. Work out each row from the NOR rule. In the box below you are given a stored value and a pair of inputs. Make a prediction first, then check it.

      Try it 2Predict, then test

      Read the scenario. Choose what you think Q and Q̄ will be, then press Check. Each answer fills in a row of the truth table below.

      Q will be:
      Q̄ will be:

      Your truth table (NOR latch)

      SRQ (next)Q̄ (next)
      00??
      01??
      10??
      11??

      Hint: start with whichever gate has a 1 on its external input. That gate must output 0. Then use that 0 to work out the other gate.

      The forbidden state: S = 1 and R = 1

      What happens when S = 1 and R = 1? Each gate has a 1 on its input, so both gates output 0: Q = 0 and Q = 0. That breaks the rule that Q is the opposite of Q, which is the first problem.

      The second problem is worse. Suppose S and R both go back to 0 at exactly the same moment:

      1. Each gate now sees 0 and 0, so both try to output 1.
      2. Then each gate sees a 1 coming back from the other, so both try to output 0.
      3. The outputs can flicker like this, and the latch settles only when one gate happens to be a little faster than the other. This is called a race condition.
      4. Which gate wins depends on tiny differences in the real components, so the final value of Q cannot be predicted.

      If the two inputs are let go one at a time, the result is predictable: whichever input is still 1 at the end wins. That is why designers simply say S = 1, R = 1 is not allowed for an SR latch. Try it 1 lets you release both together. The lab below lets you compare all three ways of letting go, and keeps count:

      Try it 3The forbidden state lab

      Step 1: put the latch into S = 1, R = 1. Step 2: choose how to let go. Do it several times and watch the tally.

      Now: S = 0, R = 0
      Q
      Q̄

        Tally of final Q values

        How you let goQ ended 0Q ended 1
        Both together00
        R first, then S00
        S first, then R00

        About this simulator: real gates are never exactly the same speed, but we cannot know which one is faster. The simulator stands in for that with a coin toss, which is why "both together" gives a different answer from run to run.

        The NAND version (active-low inputs)

        You can also build a latch from two NAND gates. The NAND rule is the mirror image of the NOR rule: any 0 into a NAND gate forces its output to 1. So in a NAND latch it is a 0 on an input that does the work. We say the inputs are active-low, and we write them with a bar: S and R.

        • G1 has inputs S and Q. Its output is Q, so Q = NAND(S, Q).
        • G2 has inputs R and Q. Its output is Q, so Q = NAND(R, Q).
        SRQ (next)Q (next)What it does
        11Q (no change)Q (no change)Hold (memory)
        0110Set
        1001Reset
        0011Forbidden (not allowed)

        Compare this with the NOR latch. The resting inputs are now 1 and 1, not 0 and 0. The forbidden inputs are 0 and 0, and they make both outputs 1 (not 0). Also, the Set input goes into the gate that makes Q, which is the opposite of the NOR latch.

        The simulator below works just like Try it 1, but with NAND gates. It writes the inputs as S’ and R’ (S-bar and R-bar). First choose the wiring, then test whether your Set input really sets.

        Try it 4Wire and test the NAND latch

        The same simulator, now built from two NAND gates. The inputs are active-low: S’ (read "S-bar") and R’ ("R-bar") rest at 1 and do their job when you pull them down to 0.

        Step 1: wire it. Choose which input goes into G1, the top gate whose output is Q. Step 2: test it. Pulse each input (switch it to 0 and back to 1), or press Test my wiring.

        Into G1 (makes Q):

        Key: wire = 1 (high)   wire = 0 (low)

        SR latch made from two cross-coupled NAND gates G1NAND G2NAND S’ R’ 1 1 0 1 S’ Q’ Q R’ Q = 0 Q’ = 1 Q Q’ Feedback: Q goes back into G2, Q’ goes back into G1
        Mode:
        NAND gate reference
        ABA NAND BUsed by
        001
        011
        101
        110

        G1: A = S’, B = Q’
        G2: A = R’, B = Q

        What the signals are doing:
          Current state

          Hold

          SR latch truth table (NAND version)
          S’R’Q (next)Q’ (next)State
          11Q (no change)Q’ (no change)Hold (memory)
          0110Set
          1001Reset
          0011Invalid (forbidden)

          The highlighted row matches the switches right now (with the correct wiring).

          Timing diagram

          Every time the switches change, a new time slot is added. Drag the slider (or tap a slot) to move the cursor: the circuit above jumps to that moment.

          Where it leads

          The SR latch is the starting point for nearly every memory circuit in a computer. These are the ideas that come next in this course (posts to follow):

          • Gated latches and the D (Data) flip-flop. An extra input, usually a clock or enable signal, decides when the latch is allowed to change. The D flip-flop also has a single data input D, so S and R can never both be 1 and the forbidden state cannot happen.
          • The JK flip-flop. It is built so that the input combination J = 1, K = 1 is useful instead of forbidden: the output toggles (changes to the opposite value).
          • Registers. A register is a group of flip-flops, one for each bit, that store a binary word together. An 8-bit register uses 8 flip-flops.
          • Counters. Flip-flops connected in a chain can count. See The Ripple Counter Explained (Animation), which uses clocked JK flip-flops.
          • Memory. Thousands or millions of 1-bit storage cells arranged in rows and columns give you memory that the processor can read and write.

          The same idea in C: a variable holds a value

          When you write C programs you use the same idea all the time. A variable keeps its value until your program changes it, just as a latch keeps Q until S or R changes it. (If you have not met variables in C yet, see Variables and Format Specifiers: Printing Values with %d and Adding 2 numbers – Declaring integer variables, Watching Variables.)

          #include <stdio.h>
          
          int main()
          {
              int q = 0;          /* like a latch that starts reset   */
          
              q = 1;              /* like a pulse on S: set q to 1    */
                                  /* nothing else changes q here...   */
          
              printf("%d\n", q);  /* ...so it still prints 1 (hold)   */
              return 0;
          }
          

          The comparison is only a picture to help you remember. The C language does not tell you what kind of circuit stores q. What you can say is that each bit of a stored value has to be kept by some storage element, and a latch is the simplest example of one.

          Review questions

          Try it 5Review questions

          Tap an answer. You get feedback straight away, and you can try again, but only your first try counts towards the score.

          Now try these in your notebook before you open the answers.

          1. Explain the difference between a combinational circuit and a sequential circuit. Give one example of each.

          Show answer

          In a combinational circuit the output depends only on the present inputs (for example a single AND gate). In a sequential circuit the output depends on the present inputs and on the previous output (for example an SR latch or a flip-flop).

          2. What does "cross-coupled" mean, and why is it needed for memory?

          Show answer

          The output of each gate is fed back into an input of the other gate. This feedback lets the circuit keep its output when the inputs return to their resting values, so it can store a bit.

          3. Write Boolean expressions for Q and Q in the NOR latch.

          Show answer

          Q = NOR(R, Q) = NOT(R OR Q). Q = NOR(S, Q) = NOT(S OR Q).

          4. A NOR latch starts with Q = 0. The inputs then go through these values in order: (S, R) = (1, 0), (0, 0), (0, 1), (0, 0). Write down Q after each step.

          Show answer

          1 (set), 1 (hold), 0 (reset), 0 (hold).

          5. A flip-flop is often called a storage element. Give two features of a flip-flop that explain why.

          Show answer

          For example: it always settles in one of two stable states (it is bistable), so each state can stand for 0 or 1; it keeps that state after the input that set it is removed, so the bit is remembered. That is why flip-flops are used to build registers, memory cells and counters.

          6. A CPU has 16-bit registers. How many flip-flops does one register need, and why?

          Show answer

          16. Each flip-flop stores one bit, so a 16-bit register is a group of 16 flip-flops that hold the 16 bits of a word side by side and are loaded together.

          Self-check: S = 1, R = 1 and the NAND wiring

          7. For a NOR latch, describe what happens to Q and Q when S = 1 and R = 1, and then what happens when (a) both inputs return to 0 at the same time, (b) R returns to 0 before S.

          Show answer

          With S = 1 and R = 1 both NOR gates output 0, so Q = 0 and Q = 0 (they are no longer opposites). (a) Both gates try to switch to 1 at the same moment and race; the final Q could be 0 or 1 and cannot be predicted. (b) With S still 1 and R = 0 the latch is set (Q = 1), and when S returns to 0 it holds Q = 1.

          8. Describe how to draw an SR latch using NAND gates. Label every input and output.

          Show answer

          Draw two NAND gates. The top gate has inputs S and Q and its output is Q. The bottom gate has inputs R and Q and its output is Q. Draw the two feedback wires: Q goes back into the bottom gate and Q goes back into the top gate. Mark the inputs as active-low (S and R): 1 and 1 holds, S = 0 sets, R = 0 resets, and 0 and 0 is forbidden (Q = Q = 1).

          Homework

          1. Explain, using the NOR truth table, what happens for each output of the SR latch when S = 1 and R = 1. Then explain what can happen when both inputs return to 0.
          2. Draw an SR latch using NAND gates. Label the inputs (active-low) and both outputs, and write its truth table underneath.

          The half adder (circuit and truth table) has its own lesson later in this course.

          Mastery quiz: SR Latch

          Your course badges: loading saved progress…

          View badges

            No course badges earned yet. Score 8/10 in a lesson quiz to earn its badge.

            Saved in this browser on this device. Clearing browser data may remove your badges.

            Answer all 10 questions. Earn this lesson’s badge at 8/10 or higher. Read the explanations, revisit the Try it activities and retry as often as you need. These are self-study badges, not formal grades.

            1. What allows an SR latch to remember a bit after a Set pulse ends?
            2. For a NOR SR latch, S = 1 and R = 0. What is Q after settling?
            3. A NOR SR latch stores Q = 1. Both S and R are now 0. What happens?
            4. For a NOR SR latch, S = 0 and R = 1. Which output pair is correct?
            5. Why is S = 1, R = 1 forbidden in the NOR SR latch?
            6. After the forbidden NOR state, S and R are released together. What should you conclude?
            7. A correctly wired NAND SR latch has active-low inputs S-bar = 1 and R-bar = 1. What is its action?
            8. For that NAND latch, S-bar = 0 and R-bar = 1. What happens?
            9. Which input combination is forbidden for the active-low NAND SR latch?
            10. How does a sequential circuit differ from a combinational circuit?

            Exam tips

            • Specimen Unit 1 Paper 01 (2021), Item 11. A multiple-choice item about what flip-flops are and what they are used for (syllabus reference 1.3, Module 1). It tests whether you know that a flip-flop is bistable and stores one bit, and how flip-flops are used inside the CPU. When an item asks which statements are true, judge each statement on its own first: one false statement rules out every option that contains it. Open the specimen paper and try the item before you check the answer key.
            • 2013 Unit 1 Paper 02, Question 1(a)(iii). This part is about the characteristics of a flip-flop. It tests whether you can say, in a few short sentences, how a flip-flop behaves and what it is used for. Give each characteristic as its own sentence (two stable states, keeps its state so it stores a bit) and add a use, such as memory or counters. Try the question yourself first, then compare with the solution on this site: 2013 U1 Q1.
            • 2009 Unit 1 Paper 02, Question 1. This question has no latch part, but it brings together gate truth tables, building one gate from others, a multiplexer and binary numbers in one long question. It shows that the building blocks are examined together, so you need the gate truth tables you use to explain a latch at your fingertips. Try it, then check the solution on this site: 2009 U1 Q1.
            • More worked answers are on the CS Solutions page.

            General advice for latch questions (from the lesson content, not from a particular paper): always give both outputs, Q and Q; say which input combination is forbidden and why; for a NAND latch say clearly that the inputs are active-low; and label every wire on a diagram.

            Previous: Logic Gates – Formal Introduction. Background: Flip Flops and The SR Flip-Flop – Practical Introduction. Next: D and JK flip-flops (coming soon in this course).

            Syllabus link: CAPE Computer Science (CXC A19/U2/21), Unit 1, Module 1: Computer Architecture. Specific Objective 2: describe the basic building blocks of a computer (flip flops: Data, JK and SR; registers; counters). Specific Objective 3: interpret the interaction among the basic building blocks of a computer (Data flip flops, registers).

            Updates

            7 Nov 2026: Added the shared course badge summary and lesson mastery quiz, with feedback, retries and browser-saved progress.

            26 Oct 2026

            - Draft created.

            27 Oct 2026

            - Reused the original SR flip-flop simulator for the Try-it circuits.

            28 Oct 2026

            - Exam references reworded and quiz questions rewritten.

            © 2026 Vedesh Kungebeharry. All rights reserved.

            Memory Types and Features

            Memory (also called main memory or primary memory) is the part of a computer that holds the instructions and data the CPU is working with. The CPU reads from it and, for some types, writes to it, using an address for each location. In this lesson we look at the memory types (RAM, ROM, EPROM and EEPROM) and the features used to compare them (speed, size, word size and volatility).

            If you did CSEC, Inside the Computer: Input, Processing, Memory, Storage and Output (IPOS) is a short refresher on RAM and ROM. Here we go further.

            Where the bits are kept

            Every memory chip is a grid of tiny cells, and each cell stores one bit (a 0 or a 1). You have already met a circuit that can do this: the flip-flop. A flip-flop has two stable states, so once it is set or reset it keeps that bit for as long as it has power. See Flip Flops, The SR Flip-Flop – Practical Introduction and The SR Latch.

            • Static RAM (SRAM) stores each bit in a flip-flop. It is fast and does not need refreshing, but each cell needs several transistors, so it costs more and holds less. Cache memory is made of SRAM.
            • Dynamic RAM (DRAM) stores each bit as a charge on a tiny capacitor. The charge leaks away, so the cells must be refreshed thousands of times a second. DRAM is cheaper and holds more, so it is used for the main RAM in PCs and phones.
            • The registers inside the CPU are also groups of flip-flops, one per bit. An 8-bit register is 8 flip-flops side by side.

            Either way, when the power goes, the flip-flops and capacitors lose their state. That is why RAM is volatile.

            Memory types

            RAM (Random Access Memory)

            RAM is read/write memory. It holds the operating system, the programs that are open and the data they are using. Random access means any location can be reached directly by its address, in the same time, wherever it is. RAM is fast, but it is volatile: its contents are lost when the power is switched off.

            ROM (Read Only Memory)

            ROM is written once, when the chip is made, and after that it can only be read. It is non-volatile, so its contents are still there when the power comes back on. ROM is used for programs that must never change, such as the control program in a washing machine or microwave, and, in older computers, the start-up (boot) program.

            EPROM (Erasable Programmable ROM)

            An EPROM can be programmed, erased and programmed again. To erase it, the chip is taken out of the circuit and ultraviolet (UV) light is shone through a small quartz window on top of it, usually for several minutes. This erases the whole chip. A device called a programmer then writes the new contents. EPROM is non-volatile.

            Close-up of an EPROM chip with a round quartz window in the middle of its package
            An EPROM chip from 1986. The window lets UV light reach the memory cells to erase them.

            Image: EPROM AM27C256DC by Anonimski, CC BY-SA 3.0, via Wikimedia Commons.

            EEPROM (Electrically Erasable Programmable ROM)

            An EEPROM is erased and rewritten electrically, so it can be changed while it stays in the circuit, one byte at a time. Writing is much slower than writing to RAM, and each cell can only be rewritten a limited number of times, so it is used for data that changes now and then, like settings. EEPROM is non-volatile.

            Flash memory is a type of EEPROM that erases in blocks instead of single bytes, which makes it faster to rewrite. It is used for the BIOS/UEFI firmware on motherboards, USB flash drives, memory cards, SSDs and phone storage.

            TypeRead/write?Volatile?How it is erased or changed
            RAMRead and writeYesOverwritten by the CPU at any time
            ROMRead onlyNoCannot be changed (written when made)
            EPROMRead only in normal useNoUV light erases the whole chip; then reprogrammed
            EEPROMRead; rewritten now and thenNoElectrically, in the circuit, a byte at a time (flash: in blocks)

            Try it 1Which memory type?

            Read the scenario and tap the memory type it describes. Wrong answers give you a hint, so you can try again.

            Try it 2Compare the memory types

            Tap one or more features. The table keeps only the memory types that have all the features you chose.

            TypeVolatile?How can it be changed?Typical use
            RAMYesRead and written freely by the CPU, very fastOperating system, open programs and their data
            ROMNoCannot be changed. Written when the chip is madeFixed programs in appliances, start-up code
            EPROMNoTake it out, erase the whole chip with UV light, reprogram it in a programmerOlder firmware, prototypes
            EEPROMNoErased and rewritten electrically in the circuit, a byte at a time (slow)Settings and small amounts of data that change now and then
            Flash (a type of EEPROM)NoErased electrically in blocks, so faster than byte-by-byte EEPROMBIOS/UEFI firmware, USB drives, SSDs, phone storage

            Memory features

            Volatility

            Volatile memory needs power to keep its contents; non-volatile memory keeps them with the power off. RAM is volatile. ROM, EPROM, EEPROM and flash are non-volatile. This is why you must save your work to storage, and why the first instructions a computer runs at power on have to come from ROM or flash: RAM is empty at that moment.

            Try it 3Pull the plug

            Store a few values, then switch the power off and on again. Watch which memory keeps its contents.

            RAM
            ROM
            EEPROM (flash)

            Power: ON

            What happened (newest first):

              The ROM values are just an example of a fixed start-up program.

              Speed

              Speed is how quickly data can be read from or written to memory, often given as the access time. Electronic memory has no moving parts, so its access time is measured in nanoseconds. A hard disk has to move its read/write head and wait for the disk to spin, so its access time is measured in milliseconds. In general, the closer the memory is to the CPU, the faster and smaller (and more expensive per byte) it is: registers, then cache, then RAM, then secondary storage.

              Try it 4Fastest to slowest

              Tap the items in order, from the fastest to access to the slowest. Then press Check.

              Your order:

                  Size (capacity)

                  Size is how much the memory can hold, measured in bytes (KB, MB, GB). Each location has its own address. With n address lines there are 2n different addresses, so:

                  capacity = number of locations × word size

                  For example, 10 address lines give 210 = 1,024 locations. If each location holds an 8-bit word, the capacity is 1,024 bytes, which is 1 KB.

                  Word size

                  The word size is how many bits the CPU works on in a single operation. It is usually the size of the CPU’s registers and the amount of data moved to or from memory in one go. Most computers and phones today are 64-bit; small microcontrollers may be 8-bit or 16-bit. A larger word size lets the CPU work on bigger numbers in one step and move more data per memory access.

                  Try it 5Capacity calculator

                  Choose the number of address lines and the word size. The calculator shows how many locations there are and the total capacity (1 KB = 1024 bytes).

                  Address lines:10
                  Word size:

                  Your turn: a memory has 16 address lines and a word size of 8 bits. What is its capacity?

                  Variables live in RAM: a C example

                  When your C program runs, it is loaded into RAM, and every variable you declare is given some bytes of RAM at an address. The program below declares an int, then prints its value, how many bytes it uses (sizeof) and its address (%p). The & in &x means "the address of x". (Recap: Variables, Format Specifiers and printf (%d), and for addresses, C Pointers.)

                  #include <stdio.h>
                  
                  int main()
                  {
                      int x = 5;
                  
                      printf("Value: %d\n", x);
                      printf("Bytes: %d\n", (int) sizeof(x));
                      printf("Address: %p\n", (void *) &x);
                  
                      return 0;
                  }
                  

                  Run it in Code::Blocks. The first line will show Value: 5. The number of bytes depends on your compiler (on most desktop compilers an int is 4 bytes, which is 32 bits). The address is printed in hexadecimal and will be different on your computer, and it may change each time you run the program, because the operating system decides where in RAM the program goes. When the program ends, or the power goes, that RAM is given back and the value of x is gone: volatility in action.

                  You can also watch variables change while a program runs in the debugger: see Adding 2 numbers, declaring integer variables, watching variables.

                  Practice questions

                  1. Give two differences between ROM and RAM.

                  Show answer

                  ROM is read only and non-volatile: its contents are fixed and are kept when the power is off. RAM can be read from and written to, and it is volatile: its contents are lost when the power is switched off.

                  2. EPROM and EEPROM are both non-volatile. Explain how each one is erased, and why this makes EEPROM easier to update inside a finished device.

                  Show answer

                  An EPROM is taken out of the circuit and the whole chip is erased with ultraviolet light, then reprogrammed in a programmer. An EEPROM is erased electrically and can be rewritten while it stays in the circuit, so a device can update it (for example a firmware update) without being opened.

                  3. Explain what is meant by the term volatile, and give one example of volatile and one of non-volatile memory.

                  Show answer

                  Volatile memory loses its contents when the power is removed. RAM is volatile; ROM (or EPROM, EEPROM, flash) is non-volatile.

                  4. A phone is advertised as having a 64-bit processor. Explain what this tells you about its word size.

                  Show answer

                  Its word size is 64 bits: the CPU works on 64 bits of data in a single operation, and its registers are 64 bits wide.

                  5. A memory has 20 address lines and a word size of 8 bits. Calculate its capacity in MB.

                  Show answer

                  220 = 1,048,576 locations × 1 byte = 1,048,576 bytes = 1 MB.

                  6. Explain why the start-up program of a computer is stored in ROM or flash memory and not in RAM.

                  Show answer

                  RAM is volatile, so it is empty when the computer is switched on. The start-up program must already be in memory at power on, so it is kept in non-volatile memory (ROM or flash), which keeps its contents without power.

                  7. Explain how static RAM and dynamic RAM store a bit, and why cache memory uses static RAM.

                  Show answer

                  Static RAM stores each bit in a flip-flop; dynamic RAM stores it as a charge on a capacitor that must be refreshed. Static RAM is faster (no refresh), which is what cache needs, even though it costs more per bit.

                  Homework

                  1. Make a table that compares RAM, ROM, EPROM and EEPROM under these headings: read/write, volatility, how it is erased, one use.
                  2. Find the RAM size and the word size (32-bit or 64-bit) of a computer or phone at home. Write down where you found the information.

                  Mastery quiz: Memory Types and Features

                  Your course badges: loading saved progress…

                  View badges

                    No course badges earned yet. Score 8/10 in a lesson quiz to earn its badge.

                    Saved in this browser on this device. Clearing browser data may remove your badges.

                    Answer all 10 questions. Earn this lesson’s badge at 8/10 or higher. Read the explanations, revisit the Try it activities and retry as often as you need. These are self-study badges, not formal grades.

                    1. An unsaved document exists only in RAM when power fails. What is most likely?
                    2. Which memory is normally used for the working data of a running program?
                    3. Which statement describes conventional ROM as used in this lesson?
                    4. How is a traditional windowed EPROM erased?
                    5. A device must update a few stored settings electrically without removing the memory. Which is most suitable?
                    6. Why does DRAM require refreshing?
                    7. Which pairing matches the lesson?
                    8. A memory has 10 address lines and 8 bits at each address. Using 1 KiB = 1024 bytes, what is its capacity?
                    9. A memory has 12 address lines and 16 bits per location. What is its capacity?
                    10. Memory A has an access time of 10 ns; B has 50 ns. Which accesses data faster?

                    Exam tips

                    • Specimen Unit 1 Paper 01 (2021), Items 4, 5, 7 and 8. Four multiple-choice items on this lesson, all with syllabus reference 1.1 (Module 1). Item 4 is about what cache memory is for, Item 5 is about the meaning of word size, Item 7 is about which memory family flash memory belongs to, and Item 8 is about which memory or storage device is slowest to access. They test whether you know the definitions exactly and can rank devices by speed (registers, cache, RAM, then storage). Read every option before you choose, because a wrong option is often a true statement about a different part of the computer. Open the specimen paper and try all four items before you check the answer key.
                    • Specimen Unit 1 Paper 02 (2021), Question 2(a). This part asks you to tell two pairs of memory types apart, ROM and RAM, then EPROM and EEPROM, with 2 marks for each pair. It tests whether you can make a clear contrast. Make one point about each item, on the same feature (for example whether it can be written to, or how it is erased), so that each half of your contrast can earn a mark. A point about only one of the two items cannot earn both marks. Try it on paper, then compare with practice questions 1 and 2 above.
                    • 2024 Unit 1 Paper 02, Question 1(b). Two parts that compare devices on named features: a hard disk with RAM (access method and access speed), and RAM with a flash drive (volatility and portability), 3 marks each. It tests whether you can apply the memory features to real devices. Cover every named feature for both devices, use the feature words in your answer, and give a reason (for example, moving parts make a hard disk slower). Try it first, then read the solution on this site: 2024 U1 Q1. See also Serial, Sequential, Direct (Random) Access.
                    • More worked answers are on the CS Solutions page.

                    Try it 6Quick quiz

                    Tap an answer. All the questions are self-checks on this lesson.

                    Background: Flip Flops, The SR Flip-Flop – Practical Introduction and The SR Latch. Next: registers and the CPU (coming soon in this course). For a first look at how the CPU uses its registers to fetch instructions from memory, see 2009 U1 Q2 Part C and part (a) of 2024 U1 Q1.

                    Syllabus link: CAPE Computer Science (CXC A19/U2/21), Unit 1, Module 1: Computer Architecture. Specific Objective 1: state the purpose of the main components of a computer system (memory types: ROM, RAM, EPROM, EEPROM; memory features: speed, size, word size, volatility). U1 M1 SO1.

                    Attributions to media used in this post:

                    EPROM chip photo: Anonimski, CC BY-SA 3.0, via Wikimedia Commons (File:EPROM AM27C256DC.jpg).

                    Updates

                    7 Nov 2026: Added the shared course badge summary and lesson mastery quiz, with feedback, retries and browser-saved progress.

                    27 Oct 2026

                    - Draft created.

                    28 Oct 2026

                    - Exam references reworded and quiz questions rewritten.

                    © 2026 Vedesh Kungebeharry. All rights reserved.

                    Storage Devices

                    A storage device (also called secondary storage or backing storage) keeps programs and data permanently, even when the power is off. Your files, your apps and the operating system itself all live on storage until they are needed, and then they are copied into RAM so the CPU can work on them. We compare storage devices using four features: capacity, access speed, access method and portability.

                    This lesson follows on from Memory Types and Features. If you did CSEC, Inside the Computer: Input, Processing, Memory, Storage and Output (IPOS) is a short refresher.

                    Storage and memory are not the same

                    Main memory (RAM)Storage (e.g. hard disk, SSD)
                    Volatile?Yes: lost when the power goesNo: kept with the power off
                    CapacitySmaller (e.g. 8 to 32 GB in a laptop)Much larger (e.g. 512 GB to several TB)
                    SpeedVery fast (nanoseconds)Slower (microseconds to milliseconds)
                    Used forWhat the CPU is working on nowKeeping files and programs for later

                    The four features

                    Capacity

                    Capacity is how much data the device can hold, measured in bytes: MB, GB and TB. Remember 1 KB = 1024 bytes, 1 MB = 1024 KB, 1 GB = 1024 MB and 1 TB = 1024 GB. (Drive makers often use 1000 instead of 1024, which is why a new “1 TB” drive shows a little less space on a computer.)

                    Access speed

                    Access speed is how quickly data can be found and read or written. Two measures are used:

                    • Access time: how long it takes to find the data. On a hard disk this is the seek time (moving the head to the right track) plus the rotational delay (waiting for the right sector to spin under the head).
                    • Data transfer rate: how much data can be moved per second once it has been found, e.g. 150 MB/s.

                    Devices with moving parts (tape, hard disk, optical disc) are slower to access than solid state devices, which find data electronically.

                    Access method

                    The access method is the way the device gets to a particular piece of data:

                    • Sequential (serial) access: the data is read in order from the start, so to reach a record, every record before it must be passed. Magnetic tape works this way.
                    • Direct (random) access: the device can go straight to the data using its address. Disks (magnetic and optical) and solid state devices work this way. A hard disk is sometimes called semi-random, because the head goes straight to the track but then waits for the sector to come round.

                    More on this in Serial, Sequential, Direct (Random) Access and File Organisation and Access Methods.

                    Try it 1Sequential vs direct access

                    The same 20 records are stored on a tape and on a disk. Choose a record and watch how each device gets to it. Yellow = passed over (read), green = found.

                    Magnetic tape (sequential access) – records read: 0
                    Disk (direct access) – records read: 0

                    Portability

                    Portability is how easily the device (and its data) can be carried and used on another computer. Small size, low weight, no separate power supply, a common connector such as USB, and the ability to survive knocks all make a device more portable. A USB flash drive is very portable; an internal hard disk is not meant to be moved.

                    Types of storage devices

                    Magnetic storage: hard disk and tape

                    A hard disk drive (HDD) stores data magnetically on spinning metal or glass platters. Each platter surface is divided into circular tracks, and each track into sectors. A read/write head on an actuator arm moves across the platter to the right track. Hard disks give a large capacity at a low cost per GB and allow direct access, but because of the moving parts they are slower than SSDs, use more power and can be damaged if dropped while running.

                    Labelled diagram of a hard disk drive showing the platter, spindle, read/write head, actuator arm, actuator axis and actuator, and the power and IDE connectors
                    The parts of a hard disk drive. The head moves across the spinning platter to reach a track.

                    Image: Hard drive.svg by Surachit, CC BY-SA 3.0, via Wikimedia Commons.

                    Magnetic tape stores data on a long plastic tape coated with magnetic material, wound inside a cartridge. Access is sequential, so finding one file can take a long time. But a tape cartridge holds a huge amount of data (18 TB or more) very cheaply and lasts for years, so tape is used by banks, businesses and data centres for backups and archives, where the data is written and read in order anyway.

                    Optical storage: CD, DVD and Blu-ray

                    Optical discs store data as tiny pits and flat areas (lands) along one long spiral track. A laser shines on the track and the drive detects how the light is reflected. Blu-ray uses a blue-violet laser with a shorter wavelength than the red laser of a DVD, so the pits can be smaller and packed closer together, giving more capacity.

                    • CD: about 700 MB. DVD: 4.7 GB (8.5 GB dual layer). Blu-ray: 25 GB per layer (50 GB dual layer).
                    • -ROM discs are pressed at the factory and are read only; -R discs can be written once; -RW discs can be erased and rewritten.
                    • Optical discs allow direct access but are slow, and they are cheap, light and very portable. They are used for distributing films, music and software, and for small backups, but they are much less common now than flash drives and the cloud.

                    Solid state storage: SSD, flash drive and memory card

                    Solid state devices store data in flash memory chips, a type of EEPROM (see Memory Types and Features). There are no moving parts, so they find data very quickly, use little power, are silent and survive knocks better than hard disks. They cost more per GB than hard disks, and each cell can only be rewritten a limited number of times.

                    • Solid state drive (SSD): replaces the hard disk inside most laptops and many desktops, so the computer starts and opens programs much faster.
                    • USB flash drive: pocket-sized, plugs into a USB port, ideal for carrying files between computers.
                    • Memory card (SD, microSD): tiny, used in cameras, phones, drones and game consoles.

                    Cloud storage

                    Cloud storage keeps your files on a provider’s servers (for example Google Drive or OneDrive), which you reach over the Internet. The real storage devices are hard disks and SSDs in the provider’s data centres. Capacity depends on your plan, there is nothing to carry, and your files are backed up off site. But you need an Internet connection, the speed depends on that connection, and you are trusting the provider with your data. See Cloud Storage vs Local Storage.

                    Try it 2Compare the storage devices

                    Tap one or more features. The table keeps only the devices that have all the features you chose. Capacities are typical values in 2026.

                    DeviceTypical capacityAccess speedAccess methodPortability
                    Hard disk (HDD)About 1 TB to over 20 TBMedium: access time of a few milliseconds (moving head, spinning platters)DirectUsually internal; external drives can be carried but are easily damaged if dropped
                    Magnetic tape18 TB or more per cartridgeSlow to find one item (seconds to minutes), fast once reading in orderSequentialCartridges are removed and stored off site
                    CD700 MBSlowDirectVery portable, light and cheap
                    DVD4.7 GB (8.5 GB dual layer)SlowDirectVery portable
                    Blu-ray25 GB per layer (50 GB dual layer)Slow, but faster than DVDDirectVery portable
                    SSDAbout 256 GB to 4 TB or moreVery fast: access time well under a millisecondDirect (random)Usually internal; external SSDs are small and tough
                    USB flash driveAbout 16 GB to 1 TBFast to find data; copying speed varies a lot between drivesDirect (random)Very portable: pocket size, USB plug, no separate power
                    Memory card (SD, microSD)About 32 GB to 1 TBFast to find data; speed class printed on the cardDirect (random)Very portable, tiny; needs a card slot or reader
                    Cloud storageDepends on the plan, from a few GB free to several TBDepends on your Internet connectionDirect, over a networkNothing to carry: reach it from any device with Internet

                    Try it 3Choose the right device

                    Read the scenario and tap the most suitable storage. A wrong answer gives you a hint, so you can try again.

                    Capacity and copying time

                    To check whether data fits, compare its size with the capacity, using the same unit. To estimate the copying time, divide the size by the transfer rate:

                    time (seconds) = size (MB) ÷ transfer rate (MB/s)

                    For example, a 4 GB video is 4 × 1024 = 4096 MB. At 100 MB/s it takes 4096 ÷ 100 ≈ 41 seconds. Watch the units: Internet speeds are given in megabits per second (Mbps), and there are 8 bits in a byte, so a 10 Mbps upload is only 10 ÷ 8 = 1.25 MB/s.

                    Try it 4Will it fit, and how long will it take?

                    Choose how much data to copy and a device. The calculator checks whether it fits and estimates the copying time. Speeds are examples only; real devices vary. 1 GB = 1024 MB.

                    Data:4 GB
                    Unit:
                    Device:

                    Try 4 GB on a DVD-R, then on the cloud. Then try 30 GB on a Blu-ray.

                    Files live on storage: a C example

                    In Memory Types and Features we saw that a variable lives in RAM and is lost when the program ends. To keep a value, a program must write it to a file on a storage device. The first program below saves the value of score to a file with fopen and fwrite. The second program, run later (even after a restart), reads it back with fread.

                    #include <stdio.h>
                    
                    int main()
                    {
                        int score = 95;
                        FILE *f = fopen("score.dat", "wb");
                    
                        if (f == NULL)
                        {
                            printf("Could not open file\n");
                            return 1;
                        }
                    
                        fwrite(&score, sizeof(score), 1, f);
                        fclose(f);
                        printf("Saved %d\n", score);
                    
                        return 0;
                    }
                    
                    #include <stdio.h>
                    
                    int main()
                    {
                        int score = 0;
                        FILE *f = fopen("score.dat", "rb");
                    
                        if (f == NULL)
                        {
                            printf("Could not open file\n");
                            return 1;
                        }
                    
                        fread(&score, sizeof(score), 1, f);
                        fclose(f);
                        printf("Read %d\n", score);
                    
                        return 0;
                    }
                    

                    "wb" means write in binary mode and "rb" means read in binary mode. fwrite copies the bytes of score from RAM to the file, and fread copies them from the file back into RAM. Notice that the second program starts with score = 0, so any other value it prints must have come from storage. If you would rather store data as readable text, see Tutorial: Storing and loading data in a plain textfile.

                    Practice questions

                    1. Explain the difference between sequential access and direct access. Give one storage device that uses each.

                    Show answer

                    With sequential access the data is read in order from the start, so all the data before the item must be passed (magnetic tape). With direct access the device goes straight to the item using its address (hard disk, SSD, DVD).

                    2. Why can an SSD find a file much faster than a hard disk can?

                    Show answer

                    A hard disk must move its head to the track (seek time) and wait for the sector to rotate under it (rotational delay), so its access time is milliseconds. An SSD has no moving parts and finds data electronically, so its access time is far shorter and it is much faster.

                    3. A company backs up 40 TB of data every night and keeps the backups for seven years. Suggest a suitable storage medium and justify your choice.

                    Show answer

                    Magnetic tape: it has a very large capacity at a low cost per GB, cartridges last for years and can be stored off site, and since a backup is written and restored in order, sequential access is not a problem.

                    4. State two features that make a USB flash drive more portable than an internal hard disk.

                    Show answer

                    For example: it is small and light; it plugs into any USB port and needs no separate power; it has no moving parts, so it is not damaged easily if dropped.

                    5. Explain why a Blu-ray disc can hold more data than a DVD.

                    Show answer

                    Blu-ray uses a blue-violet laser with a shorter wavelength, so the pits can be smaller and the tracks closer together. More pits fit on the disc, so it holds more data (25 GB per layer compared with 4.7 GB).

                    6. A 2 GB file is uploaded to cloud storage over a 16 Mbps connection. Estimate the time taken. (1 GB = 1024 MB)

                    Show answer

                    16 Mbps ÷ 8 = 2 MB/s. 2 GB = 2048 MB. 2048 ÷ 2 = 1024 seconds, about 17 minutes.

                    7. Give one advantage and one disadvantage of cloud storage compared with a local hard disk.

                    Show answer

                    Advantage, for example: files can be reached from any device with Internet, and they are backed up off site. Disadvantage, for example: it needs an Internet connection and the speed depends on it; you rely on the provider to keep your data safe and private.

                    Homework

                    1. Copy the comparison table from Try it 2 into your notebook. Add a column "One suitable use" and fill it in for each device.
                    2. Find the storage on a computer or phone at home: the type (HDD, SSD or flash), the capacity and how much is free. Write down where you found the information.

                    Mastery quiz: Storage Devices

                    Your course badges: loading saved progress…

                    View badges

                      No course badges earned yet. Score 8/10 in a lesson quiz to earn its badge.

                      Saved in this browser on this device. Clearing browser data may remove your badges.

                      Answer all 10 questions. Earn this lesson’s badge at 8/10 or higher. Read the explanations, revisit the Try it activities and retry as often as you need. These are self-study badges, not formal grades.

                      1. Which statement best distinguishes storage from RAM?
                      2. Which device normally requires sequential access to reach a particular record?
                      3. Which feature helps an SSD access data faster than a mechanical hard disk?
                      4. A student needs to carry a small file between computers with compatible USB ports and no Internet. Which device fits?
                      5. What reads the recorded data on an optical disc?
                      6. A company wants low-cost long-term archives that are normally read in sequence. Which option is suitable?
                      7. A 600 MB file copies at a steady 30 MB/s. Ignoring overhead, how long does it take?
                      8. A connection uploads at 16 megabits per second. Ignoring overhead, what is that in megabytes per second?
                      9. Cloud storage keeps the only copy of a file remotely. What is needed to fetch it on a new device?
                      10. A C program must retain a score after it exits. What should it do?

                      Exam tips

                      • Specimen Unit 1 Paper 01 (2021), Item 8. A multiple-choice item on comparing how quickly different memory and storage devices give access to data (syllabus reference 1.1, Module 1). It tests whether you can rank electronic memory against storage devices, including older removable media you may not have used yourself. Put the options in order of speed in your head (registers, cache, RAM, then storage, with moving parts slowest) before you choose. Open the specimen paper and try it before you check the answer key.
                      • 2024 Unit 1 Paper 02, Question 1(b). Two parts that compare a storage device with RAM: a hard disk against RAM on access method and access speed, and RAM against a flash drive on volatility and portability, 3 marks each. It tests whether you can use the storage features from this lesson to explain a difference. For each named feature, say something about both devices and give a reason, for example the head has to move to the track and wait for the sector, so hard disk access is measured in milliseconds. Try it first, then compare with the solution on this site: 2024 U1 Q1.
                      • 2017 and 2018 Unit 2 Paper 02, Question 5. Storage comes back in Unit 2 with virtual memory, where pages of processes that do not fit in RAM are kept on the hard disk. Try the questions, then see the solutions on this site: 2017 U2 Q5 and 2018 U2 Q5.
                      • More worked answers are on the CS Solutions page.

                      General advice for storage questions (from the lesson content, not from a particular paper): when asked to choose a device, name it and justify it using the four features, capacity, access speed, access method and portability, linked to the scenario.

                      Try it 5Quick quiz

                      Tap an answer. All the questions are self-checks on this lesson.

                      Previous: Memory Types and Features. Next: the processor (CPU) and how it fetches instructions and data from memory (coming soon in this course; for now see 2009 U1 Q2 Part C). After that, data representation: how the bits on these devices stand for numbers and characters (Decimal to binary, Binary Manipulation).

                      Syllabus link: CAPE Computer Science (CXC A19/U2/21), Unit 1, Module 1: Computer Architecture. Specific Objective 1: state the purpose of the main components of a computer system (storage devices: capacity, access speed, access method, portability). U1 M1 SO1.

                      Attributions to media used in this post:

                      Hard disk diagram: Surachit, CC BY-SA 3.0, via Wikimedia Commons (File:Hard drive.svg).

                      Updates

                      7 Nov 2026: Added the shared course badge summary and lesson mastery quiz, with feedback, retries and browser-saved progress.

                      27 Oct 2026

                      - Draft created.

                      28 Oct 2026

                      - Exam references reworded and quiz questions rewritten.

                      © 2026 Vedesh Kungebeharry. All rights reserved.

                      Input and Output Devices

                      An input device sends data and instructions into a computer, for example a keyboard, mouse, microphone, scanner or sensor. An output device takes the results of processing out of the computer in a form people (or other machines) can use, for example a monitor, printer or speakers. Some devices, such as a touch screen, do both. When we compare input and output devices we look at port connectivity (how they connect), speed and the quality of output.

                      This is the third lesson on the parts of a computer, after Memory Types and Features and Storage Devices. If you did CSEC, Choosing the Right Input and Output Devices is a short refresher.

                      Try it 1Input, output or both?

                      Tap a device, then tap where it belongs. A device is input if data goes into the computer, output if data comes out of the computer, and both if it does both.

                      Input
                        Output
                          Both

                            Port connectivity

                            A port is a socket on the computer where a device is connected. The port decides what the cable can carry (data, power, video, sound or a network) and how fast. Many devices now connect wirelessly instead, using Bluetooth or Wi-Fi. When a device is connected, the operating system uses a small program called a device driver to talk to it.

                            Port or connectionWhat it is used forSpeed (typical maximum)
                            USB-AKeyboards, mice, flash drives, printers. Flat rectangular plug, one way up.USB 2.0: 480 Mbit/s. USB 3.x: 5 to 10 Gbit/s.
                            USB-CPhones, laptops, external drives, monitors. Small oval plug that fits either way up; can carry power, data and video.Up to 10 Gbit/s on USB 3.2; 40 Gbit/s or more on USB4 and Thunderbolt.
                            HDMIMonitors, TVs and projectors: digital video and sound in one cable.HDMI 2.0: 18 Gbit/s. HDMI 2.1: 48 Gbit/s.
                            VGAOlder monitors and projectors: analogue video only, no sound.Analogue; the picture gets less sharp at high resolutions.
                            3.5 mm audio jackHeadphones, speakers and microphones (analogue sound).Analogue sound only.
                            Ethernet (RJ-45)A wired connection to a network.Usually 1 Gbit/s.
                            BluetoothWireless earbuds, keyboards, mice and speakers, over a short range (about 10 m).A few Mbit/s: enough for sound and typing, slow for big files.
                            Wi-FiWireless printers and network connections.Hundreds of Mbit/s, depending on the router and distance.

                            Things to think about when choosing a connection: does the computer have that port; is the port fast enough for the device (a webcam or external SSD needs more speed than a mouse); does the cable also need to carry power or sound; and would wireless be more convenient (no cable), or is wired better (faster, more reliable, no batteries to charge)?

                            Try it 2Match the port

                            Read how the device connects and tap the port or connection it uses. A wrong answer gives you a hint.

                            Speed

                            Speed means different things for different devices:

                            • Input speed: how quickly data can be entered. A keyboard is limited by how fast a person types. A barcode reader, or the MICR reader that reads the magnetic ink numbers on bank cheques, enters data much faster and with fewer errors, because no one types it.
                            • Printer speed is measured in pages per minute (ppm). Laser printers are usually faster than inkjet printers for large amounts of text.
                            • Monitor speed is the refresh rate in hertz (Hz): how many times a second the picture is redrawn. 60 Hz is normal; gaming monitors use 144 Hz or more for smoother movement.
                            • Connection speed: the port or wireless link must be fast enough for the data (see the table above).

                            Quality of output

                            The quality of output is how good the result looks or sounds.

                            • Screens: the resolution is the number of pixels across and down, for example 1920 × 1080 (Full HD) or 3840 × 2160 (4K). More pixels give a sharper picture. The colour depth is the number of bits used for each pixel’s colour: 24 bits gives 224, about 16.7 million colours.
                            • Printers: quality is measured in dots per inch (dpi). A laser printer gives sharp text (typically 600 dpi or more) and is cheap per page for large jobs. An inkjet printer gives good colour photos and is cheap to buy, but the ink is expensive per page. A dot-matrix (impact) printer is noisy and gives low quality, but it can print on multi-part forms, where a copy is made by pressing through the sheets.
                            • Sound: better speakers and headphones give clearer sound with less distortion.

                            Higher quality costs something: more pixels and more colours mean bigger files, more memory and more data to send through the port.

                            Try it 3Resolution and quality explorer

                            The same picture is drawn with fewer or more pixels, and with fewer or more colours. Watch the quality change, and the number of bytes it costs.

                            Pixels across:
                            Colour depth:

                            Printer resolution:

                            Try 8 pixels with 1 bit, then 256 pixels with 24 bits. Which looks like a real photo?

                            Specialised devices

                            The syllabus names four specialised devices. Each one solves a particular problem.

                            Braille keyboard

                            A braille keyboard lets a blind or visually impaired person type by touch. Some are ordinary keyboards with raised braille dots on the keys. Others have six main keys, one for each dot of a braille cell, as on a Perkins Brailler: you press the keys for the dots together to make one letter. Braille users often also use a refreshable braille display (an output device whose pins rise and fall to show text as braille) and a screen reader, software that reads the screen aloud.

                            Diagram of the keys of a Perkins brailler, showing which braille dot each key makes
                            On a six-key braille keyboard, each key makes one of the six dots in a braille cell. Keys pressed together make one character.

                            Image: Perkins brailler keyboard layout by Emflazie, CC0 (public domain), via Wikimedia Commons.

                            Sensors

                            A sensor is an input device that measures a physical quantity, such as temperature, light, moisture, pressure, humidity or movement. Most sensors give an analogue signal, so an analogue-to-digital converter (ADC) turns it into a binary number the computer can process. Sensors are used in monitoring and control systems, for example greenhouses, security alarms, traffic lights and car parking sensors. They take readings automatically and continuously, day and night, and are more accurate than a person.

                            In a control system, the computer compares each reading with a set value called the threshold. If the reading crosses it, the computer sends a signal to an actuator (a motor, fan, pump, lamp or alarm) to switch on or off.

                            Try it 4Sensor and threshold

                            A computer reads a sensor over and over. When the reading crosses the threshold, it switches a device on or off. No person is needed.


                            Reading:
                            Threshold:

                            Switch log:

                              Touch screen

                              A touch screen is both an output device (the display) and an input device (it detects where it is touched). A resistive touch screen detects pressure, so it works with a stylus or gloves. A capacitive touch screen detects the small electrical charge of a finger, is more sensitive and supports multi-touch, such as pinching to zoom. Touch screens are used on phones, tablets, ATMs, airport kiosks and shop tills. They are easy to learn and need no keyboard or mouse, but they get fingerprints, are slow for typing a lot of text, and small buttons are hard to hit. That is why the buttons on this page are at least 48 pixels tall.

                              Concept keyboard

                              A concept keyboard is a flat board divided into areas. Each area stands for a whole item or idea, not a single letter, and is shown by a picture or word on an overlay. The areas can be programmed for each use. Concept keyboards are used on fast-food tills (one press for "large fries"), and by young children and people with learning difficulties. Data entry is fast with few errors, and the sealed surface is easy to wipe clean and resists spills. The drawback is that only a fixed set of choices can be entered.

                              Try it 5Which specialised device?

                              Read the scenario and tap the most suitable device. A wrong answer gives you a hint, so you can try again.

                              Summary

                              DeviceTypeTypical use
                              Keyboard, mouseInputTyping and pointing on a desktop or laptop
                              Scanner, microphoneInputTurning paper images and sound into data
                              Braille keyboardInputTyping by touch for blind or visually impaired users
                              SensorInputAutomatic measurements in monitoring and control systems
                              Concept keyboardInputFast tills, young children, users with learning difficulties
                              Monitor, projectorOutputShowing text, images and video
                              PrinterOutputHard copy on paper (laser, inkjet, dot-matrix)
                              Speakers, headphonesOutputSound
                              Touch screenBothPhones, tablets, ATMs, kiosks

                              Input and output in C

                              In C, scanf reads input (normally from the keyboard) and printf sends output (normally to the screen). Your program does not need to know which keyboard or monitor is attached: the operating system and its device drivers deal with the actual devices.

                              #include <stdio.h>
                              
                              int main()
                              {
                                  int age;
                              
                                  printf("Enter your age: ");
                                  scanf("%d", &age);
                                  printf("Next year: %d\n", age + 1);
                              
                                  return 0;
                              }
                              

                              Whatever whole number the user types is stored in the variable age in RAM, and the program prints one more than it. More on this in Variables, format specifiers and printf and Adding 2 numbers: outputting the result with printf().

                              Practice questions

                              1. Define an input device and an output device, and give TWO examples of each.

                              Show answer

                              An input device sends data and instructions into the computer, e.g. keyboard, scanner. An output device presents the results of processing from the computer, e.g. monitor, printer.

                              2. Explain why a touch screen is called both an input device and an output device.

                              Show answer

                              It displays information like a monitor (output), and it also detects where the user touches and sends that to the computer (input).

                              3. A teacher wants to show a video with sound from a laptop on the classroom TV. Suggest a suitable port and justify your answer.

                              Show answer

                              HDMI: it carries high-definition digital video and the sound in one cable, and most TVs and laptops have it. (VGA would carry no sound.)

                              4. Give TWO ways the quality of output of a printer and of a monitor can be compared.

                              Show answer

                              Printer: resolution in dots per inch (dpi); colour or black only. Monitor: resolution (pixels, e.g. 1920 × 1080); colour depth (bits per pixel); refresh rate for smooth movement.

                              5. A farmer wants the greenhouse fan to switch on automatically when it gets too hot. Explain how a sensor is used.

                              Show answer

                              A temperature sensor takes readings continuously. An ADC converts each analogue reading to digital. The computer compares the reading with a threshold, e.g. 30 °C; if it is above, it sends a signal to switch the fan on, and switches it off when the reading falls below again.

                              6. State TWO reasons a fast-food restaurant might use a concept keyboard at its tills.

                              Show answer

                              For example: one press enters a whole item, so orders are entered quickly; pictures make it easy for new staff, with fewer errors; the sealed surface is easy to clean and resists spills.

                              7. Describe how a braille keyboard helps a visually impaired user.

                              Show answer

                              It lets the user type by touch, either with raised braille dots on the keys or with six keys that each make one dot of a braille cell, pressed together to make a character.

                              8. An image is 1920 × 1080 pixels with a colour depth of 24 bits. Calculate its uncompressed size in MB.

                              Show answer

                              1920 × 1080 = 2,073,600 pixels. 24 bits = 3 bytes, so 2,073,600 × 3 = 6,220,800 bytes. 6,220,800 ÷ 1024 ÷ 1024 ≈ 5.9 MB.

                              Homework

                              1. Look at the ports on a computer or laptop at home or at school. List each port, say what it is (use the table above), and name one device you could connect to it.
                              2. On a Windows computer, open Device Manager and list the input and output devices installed (keyboards, mice, monitors, audio). The CAPE syllabus suggests this activity.
                              3. Choose one specialised device from this lesson. Write a short paragraph on who uses it, what problem it solves, and one advantage and one disadvantage.

                              Mastery quiz: Input and Output Devices

                              Your course badges: loading saved progress…

                              View badges

                                No course badges earned yet. Score 8/10 in a lesson quiz to earn its badge.

                                Saved in this browser on this device. Clearing browser data may remove your badges.

                                Answer all 10 questions. Earn this lesson’s badge at 8/10 or higher. Read the explanations, revisit the Try it activities and retry as often as you need. These are self-study badges, not formal grades.

                                1. Which device sends sound into a computer?
                                2. Why is a touch screen both an input and an output device?
                                3. A laptop and TV both have compatible HDMI ports. Why choose HDMI for a video with sound?
                                4. A printer produces 30 pages per minute. What does this measure?
                                5. Which measurement is used to compare printer resolution?
                                6. A greenhouse needs automatic temperature readings. Which input device is suitable?
                                7. An analogue sensor is connected to a digital computer. What converts its readings into digital values?
                                8. Why can a concept keyboard help staff at a restaurant till?
                                9. What does a six-key braille keyboard allow a user to do?
                                10. An uncompressed 100 by 100 pixel image uses 24 bits per pixel. Ignoring headers, how many bytes are needed?

                                Exam tips

                                • Use the syllabus headings. For this objective the syllabus compares input and output devices by port connectivity, speed and quality of output, and names four specialised devices: the braille keyboard, sensors, the touch screen and the concept keyboard. When you compare devices in an answer, organise it under those headings.
                                • 2024 Unit 1 Paper 02, Question 2(b). Sensors turn up inside a logic question here: several sensors in a security system have to share one line, and you are asked how a multiplexer makes that possible. It tests whether you can link input devices to the building blocks from Module 1. Explain which inputs the sensors connect to, what the select lines do, and how each sensor gets the line in turn. Try it, then compare with the solution on this site: 2024 U1 Q2. See also Multiplexers.
                                • 2024 Unit 1 Paper 02, Question 1(b)(ii). This part compares RAM with a flash drive on volatility and portability. It tests whether you can explain portability in terms of the device itself, and the port it uses is part of that answer. The solution on this site points out that a flash drive plugs into a USB port. Try the part first, then compare.
                                • Specimen Unit 1 Paper 02 (2021), Question 2(b)(ii). This part is about the kinds of instruction a CPU has in its instruction set. One kind moves data, including to and from input and output devices, which is where this lesson meets the processor. For each kind you name, give a short description and an example. Try it when you study the CPU, then check the mark scheme.
                                • Specimen Unit 2 Paper 01 (2021), Item 45. A multiple-choice item on what happens to a running process while it waits for input from a device, and when that input arrives. It belongs to Unit 2 (operating systems: process states, device drivers, polling, buffering and spooling), so it is only a preview here. When you get there, draw the process state diagram before you choose an answer. Open the specimen paper and try it then.
                                • More worked answers are on the CS Solutions page.

                                General advice (from the lesson content, not from a particular paper): when asked to choose a device for a scenario, name the device, then justify it with the features in the question, such as who the user is, the port or connection, the speed needed and the quality of output.

                                Try it 6Quick quiz

                                Tap an answer. All the questions are self-checks on this lesson.

                                Previous: Storage Devices (and before that, Memory Types and Features). Next: the processor (CPU), and how it moves data between memory and the input and output devices (coming soon in this course; for now see 2009 U1 Q2 Part C). Sensor readings become binary numbers, so data representation follows: see Decimal to binary. For how users interact with a computer, see User Interfaces: Command Line, Menus, Graphical and Touch.

                                Syllabus link: CAPE Computer Science (CXC A19/U2/21), Unit 1, Module 1: Computer Architecture. Specific Objective 1: state the purpose of the main components of a computer system (input/output devices: port connectivity, speed, quality of output; specialised devices: braille keyboard, sensors, touch screen, concept keyboard). U1 M1 SO1.

                                Attributions to media used in this post:

                                Braille keyboard diagram: Emflazie, CC0 1.0 (public domain), via Wikimedia Commons (File:Perkins brailler keyboard layout.png).

                                Updates

                                7 Nov 2026: Added the shared course badge summary and lesson mastery quiz, with feedback, retries and browser-saved progress.

                                28 Oct 2026

                                - Draft created.

                                - Exam references reworded and quiz questions rewritten.

                                © 2026 Vedesh Kungebeharry. All rights reserved.

                                Power Protection and Types of Computers

                                Computers need a steady supply of electricity, and they come in very different sizes, from a phone in your pocket to a supercomputer that fills a hall. This lesson covers both: how to protect a computer from power problems, and the main types of computer. It is the last part of Unit 1, Module 1, Specific Objective 1, after Memory Types and Features, Storage Devices and Input and Output Devices.

                                What you will learn

                                • The common power problems: spikes, surges, sags (brownouts), over-voltage and blackouts.
                                • What a surge protector, a voltage regulator and an uninterruptible power supply (UPS) do, and when to use each.
                                • How to estimate how long a UPS can run a computer.
                                • The main types of computer: supercomputer, server, microcomputer (desktop) and mobile devices.
                                • How to choose a suitable type of computer for a task.

                                Part 1: Device power protection

                                Why power matters

                                In Trinidad and Tobago, and many other Caribbean islands, the mains supply is about 115 volts (V). A computer’s power supply turns this into the small, steady voltages the parts inside need. If the mains voltage jumps, drops or stops, the computer can restart, lose the data in RAM (RAM is volatile, as you saw in Memory Types and Features), damage files being written, or even be destroyed.

                                Power problems

                                ProblemWhat happensHow longCommon causes
                                SpikeThe voltage shoots very high (it can be thousands of volts)A tiny fraction of a secondLightning, large motors switching
                                SurgeThe voltage rises above normalA short time, usually less than a second or a few secondsPower returning after an outage, heavy equipment switching off
                                Sag (brownout)The voltage drops below normalSeconds to hoursToo many loads on the supply, faults, evening demand
                                Over-voltageThe voltage stays above normalMinutes to hoursSupply faults, poor wiring
                                BlackoutNo power at allSeconds to hours or daysStorms, faults, load shedding

                                Surge protector

                                A surge protector (surge suppressor) looks like a power strip, but inside it has parts (usually metal oxide varistors, MOVs) that send extra voltage to the earth wire when a spike or surge arrives. This protects the equipment plugged into it.

                                • It is rated in joules: the higher the joule rating, the more energy it can absorb before it wears out.
                                • It does not help with sags or blackouts.
                                • After a big strike it may need replacing. Many have a light that shows whether protection is still working.
                                • A plain power strip without surge protection gives no protection at all.

                                Voltage regulator

                                A voltage regulator (automatic voltage regulator, AVR) keeps the output voltage at a steady level. When the mains sags it boosts the voltage, and when the mains runs too high it lowers it. Use one where the supply often runs too low or too high for long periods.

                                • It fixes sags, brownouts and over-voltage.
                                • It does not help in a blackout: with no input power, there is nothing to regulate.

                                Uninterruptible power supply (UPS)

                                A UPS has a battery and an inverter (which turns the battery’s direct current back into alternating current). When the mains fails, the UPS switches to battery at once, so the computer keeps running. The aim is usually not to work for hours, but to give enough time to save work and shut down properly, or to keep a server running until a generator starts.

                                • Standby (offline) UPS: the cheapest. Equipment runs from the mains until it fails, then the UPS switches to battery in a few milliseconds.
                                • Line-interactive UPS: also has a voltage regulator, so it fixes sags and over-voltage without using the battery.
                                • Online (double-conversion) UPS: the equipment always runs from the inverter, so there is no switch-over gap at all. It is used for servers and medical equipment, and costs the most.
                                • Most UPS units include surge protection too.
                                • Many can tell the computer, through a USB cable, to shut down by itself when the battery is low.

                                Ratings. A UPS is rated in volt-amperes (VA) and in watts (W). For example, a 650 VA UPS might supply at most 390 W. Always compare the total power your devices use, in watts, with the watt rating. The battery stores energy, measured in watt-hours (Wh). A rough runtime is:

                                runtime in minutes ≈ battery Wh × 0.8 ÷ load in W × 60

                                The 0.8 allows for energy lost in the inverter and battery. For a PC and monitor using 175 W on an 86 Wh battery: 86 × 0.8 ÷ 175 × 60 ≈ 24 minutes.

                                Which device for which problem?

                                DeviceSpike or surgeSag or over-voltageBlackout
                                Surge protectorYesNoNo
                                Voltage regulator (AVR)Some models onlyYesNo
                                UPSYes (most models)Line-interactive and online modelsYes, for a limited time

                                Try it 1Match the power problem to the device

                                Read each scenario and tap the device that best solves the problem.

                                Try it 2UPS runtime estimator

                                Choose a UPS, then tap the devices plugged into its battery side. The estimate uses: minutes = battery Wh × 0.8 ÷ load W × 60. The figures are typical values, and real runtimes vary with battery age and load.

                                The same sum in C. If you are new to float and printf, see Variables, format specifiers and printf.

                                #include <stdio.h>
                                
                                int main(void)
                                {
                                    float battery_wh = 86;   /* energy stored in the UPS battery */
                                    float load_w = 175;      /* PC 150 W + monitor 25 W */
                                    float minutes;
                                
                                    minutes = battery_wh * 0.8 / load_w * 60;   /* about 80% is usable */
                                    printf("Runtime: about %.0f minutes\n", minutes);
                                
                                    return 0;
                                }
                                

                                Output: Runtime: about 24 minutes. Change load_w to 390 and run it again: the runtime falls to about 11 minutes.

                                Good care of your computer also includes keeping vents clear and backing up: see Taking Care of Your Computer and Backing Up and Restoring Your Work. A UPS protects against losing a few minutes of work; only a backup protects against losing everything.

                                Part 2: Types of computers

                                Computers are grouped by size, processing power, cost and how many people use them at once. The CAPE syllabus names four types. (You may also meet older names such as mainframe, a large computer used by banks and governments to process huge numbers of transactions for many users, and minicomputer, a mid-sized machine that servers have largely replaced. For a CSEC-level refresher, see Types of Computer Systems.)

                                Supercomputer

                                The fastest and most expensive type. A supercomputer links thousands of processors so that they work on parts of one huge problem at the same time (parallel processing). Its speed is measured in FLOPS (floating-point operations per second); the fastest machines in 2026 manage more than 1018 FLOPS (exascale). It needs a large room, a lot of electricity and powerful cooling.

                                • Uses: weather and climate models, medicine and materials research, simulating car crashes or earthquakes, space science.
                                • Users: research teams who submit jobs to it, often over the Internet.
                                Rows of black cabinets of the Frontier supercomputer in a large hall
                                The Frontier supercomputer at Oak Ridge National Laboratory, USA. Each black cabinet holds many processors. Photo: OLCF at ORNL, CC BY 2.0.

                                Server

                                A server is a computer that provides a service to other computers (clients) over a network: web pages, email, shared files, databases or printing. Servers are built to run all day, every day, and often have two power supplies, spare disks (RAID) and a UPS. Many are mounted in racks in a cooled server room or data centre. You will meet servers again in networks: see Types of Computer Networks.

                                Microcomputer (desktop)

                                A microcomputer is a computer built around a single microprocessor, for one user at a time. The desktop PC is the usual example: it sits on a desk, has a separate monitor, keyboard and mouse, is cheap for the power it gives, and is easy to repair and upgrade. Laptops are microcomputers too, but because they are portable they are often grouped with mobile devices.

                                Mobile devices

                                Mobile devices are small, light and battery powered, so they can be used on the move: laptops, tablets, smartphones and wearables such as smartwatches. They usually have a touch screen, wireless connections (Wi-Fi, Bluetooth, mobile data), GPS and cameras. The trade-offs are battery life, smaller screens, less upgradability, and being easy to lose or steal.

                                Try it 3Compare the types of computer

                                Tap one or more features. The table keeps only the computers that have all the features you chose. Costs are rough 2026 values in US dollars.

                                TypeSizeProcessing powerUsersTypical usesRough cost
                                SupercomputerRows of cabinets filling a large hallThe fastest: thousands of processors working in parallelResearchers share it by sending jobsScientific simulations, climate and medicine research, code breakingHundreds of millions of dollars
                                ServerA box or a rack unit; often many racks in a data centreHigh, built to run non-stopMany clients at the same time over a networkWebsites, email, files, databases, printingFrom about $1,000 to many thousands
                                DesktopSits on or under a deskGood for one personOne user at a timeOffice work, school work, games, designAbout $400 to $2,000
                                LaptopFolds shut; about 1 to 3 kgGood, a little less than a similar desktopOne userWork and study on the moveAbout $300 to $2,000
                                TabletThin slab, under 1 kgModerateOne userReading, browsing, drawing, records in the fieldAbout $100 to $1,500
                                SmartphoneFits in a pocketModerate, but improving fastOne userCalls, messages, photos, apps, mapsAbout $100 to $1,500

                                Choosing a type of computer

                                Ask: How much processing does the task need? How many users at once? Must it be carried? What is the budget? Then justify your choice with those facts. There is more practice in Choosing a Suitable Computer System for a Purpose.

                                Try it 4Choose the right computer

                                Read each scenario and tap the type of computer that suits it best.

                                Summary

                                TopicKey points
                                Surge protectorStops spikes and surges by sending extra voltage to earth. Rated in joules. No help in a blackout.
                                Voltage regulatorKeeps voltage steady during sags and over-voltage. No help in a blackout.
                                UPSBattery and inverter. Keeps equipment running in a blackout long enough to save and shut down. Check the watt rating.
                                SupercomputerFastest; thousands of processors in parallel; huge scientific jobs.
                                ServerProvides services to many clients over a network; runs non-stop.
                                Microcomputer (desktop)One user; one microprocessor; cheap, upgradeable.
                                Mobile devicesPortable, battery powered, wireless; laptops, tablets, smartphones, wearables.

                                Practice questions

                                1. Explain the difference between a surge and a sag.

                                Show answer

                                A surge is a short rise in voltage above normal. A sag (brownout) is a drop in voltage below normal, which can last from seconds to hours.

                                2. A school lab in an area with frequent lightning and frequent power cuts wants to protect its PCs. Recommend one device and justify it.

                                Show answer

                                A UPS (ideally line-interactive). Most UPS units include surge protection against lightning spikes, and the battery keeps the PCs running during a power cut long enough for students to save their work and shut down properly.

                                3. Why does a surge protector not help during a blackout?

                                Show answer

                                It only removes extra voltage. In a blackout there is no voltage at all, so the computer still switches off. Only a device with a battery (a UPS) can supply power.

                                4. A UPS has a 173 Wh battery and a 600 W rating. Estimate the runtime for a 250 W server. Could it also run a 500 W laser printer at the same time?

                                Show answer

                                173 × 0.8 ÷ 250 × 60 ≈ 33 minutes. No: 250 + 500 = 750 W, which is more than the 600 W rating, so the UPS would be overloaded.

                                5. State two differences between a supercomputer and a server.

                                Show answer

                                Any two: a supercomputer works on one huge calculation using thousands of processors in parallel, while a server provides services (files, web pages, email) to many clients; a supercomputer costs far more; a supercomputer is used by research teams submitting jobs, a server answers many users at once over a network.

                                6. Give two advantages and one disadvantage of a tablet compared with a desktop for a nurse on a hospital ward.

                                Show answer

                                Advantages: portable and light, so it can be carried to each bed; battery powered; touch screen is quick to use. Disadvantage: less powerful or harder to upgrade, a smaller screen, limited battery life, or easier to lose or steal.

                                Homework

                                1. Find the power protection used at home or school (power strips, surge protectors, voltage regulators, UPS units). Read the label of one and write down its rating (joules, VA or W).
                                2. List the devices you would plug into a UPS at home, look up or estimate their watts, and use the estimator above to choose a UPS.
                                3. For each of the four types of computer, name one real organisation in the Caribbean or elsewhere that would use it, and say why.

                                Mastery quiz: Power Protection and Computer Types

                                Your course badges: loading saved progress…

                                View badges

                                  No course badges earned yet. Score 8/10 in a lesson quiz to earn its badge.

                                  Saved in this browser on this device. Clearing browser data may remove your badges.

                                  Answer all 10 questions. Earn this lesson’s badge at 8/10 or higher. Read the explanations, revisit the Try it activities and retry as often as you need. These are self-study badges, not formal grades.

                                  1. Which device supplies battery power long enough to save work during a blackout?
                                  2. The mains voltage repeatedly stays too low. Which device is designed to regulate it?
                                  3. Why does a surge protector alone not keep a PC running in a blackout?
                                  4. Which situation describes a sag or brownout?
                                  5. A UPS can supply at most 400 W. A PC and monitor together need 250 W. Adding a 200 W device would do what?
                                  6. Using runtime = Wh times 0.8 divided by W times 60, estimate a 100 Wh battery powering a 200 W load.
                                  7. Which task most strongly calls for a supercomputer?
                                  8. Which computer provides shared files to many clients over a network?
                                  9. A field worker must carry a device and use it away from mains power. Which choice best meets those needs?
                                  10. Why are backups still needed even when a computer has a UPS?

                                  Exam tips

                                  • Specimen Unit 1 Paper 01 (2021), Item 14. A multiple-choice item that describes an organisation with a very demanding scientific task and asks which type of computer suits it best. It tests whether you can link the size of a processing job to the right type of computer. Some options are older categories that are not in the syllabus list, so know briefly what a mainframe and a minicomputer are. Look for clues about the amount of calculation and the number of users. Open the specimen paper, try it, then check the key.
                                  • Specimen Unit 2 Paper 01 (2021), Item 42. A multiple-choice item on a network diagram, where you identify labelled parts such as a server. It belongs to Unit 2 (networks), so it is only a preview here, but it shows why you must know what a server does. Try it when you study networks.
                                  • Power protection. I have not found a question on surge protectors, voltage regulators or UPS units in the specimen papers or in the solutions on this site so far, but they are on the syllabus list, so learn them.
                                  • More worked answers are on the CS Solutions page.

                                  General advice (from the lesson content, not from a particular paper): when asked to recommend a device or a type of computer, name it, then justify it with facts from the scenario. For power protection, say which power problem it deals with (spike, surge, sag, over-voltage or blackout). For a UPS, say that it gives time to save work and shut down properly. For a computer type, mention processing power, number of users, portability and cost.

                                  Previous: Input and Output Devices (and before that, Storage Devices and Memory Types and Features). Next: the processor (CPU), the part that does the processing in every one of these computers (coming soon in this course; for now see 2009 U1 Q2 Part C).

                                  Syllabus link: CAPE Computer Science (CXC A19/U2/21), Unit 1, Module 1: Computer Architecture. Specific Objective 1: state the purpose of the main components of a computer system (device power protection: surge protectors, voltage regulators, Uninterruptible Power Supplies (UPS); types of computers: supercomputer, server, microcomputer (desktop), mobile devices). U1 M1 SO1.

                                  Video search terms

                                  Search YouTube for: "how a UPS works", "surge protector explained", "automatic voltage regulator explained", "what is a supercomputer", "what is a server".

                                  Try it 5Quick quiz

                                  Tap an answer. All the questions are self-checks on this lesson.

                                  Attributions to media used in this post:

                                  Frontier supercomputer photo: OLCF at ORNL, CC BY 2.0, via Wikimedia Commons (File:Frontier Supercomputer (2).jpg).

                                  Updates

                                  7 Nov 2026: Added the shared course badge summary and lesson mastery quiz, with feedback, retries and browser-saved progress.

                                  4 Nov 2026

                                  - Draft created.

                                  © 2026 Vedesh Kungebeharry. All rights reserved.

                                  Adding Binary Numbers

                                  Adding two binary numbers uses the same columns as decimal addition, but each column only has the digits 0 and 1. When a column totals 2 or more, you write 0 or 1 in that place and carry 1 to the next place on the left. In this lesson you will switch bits, watch the carries move, and add the same numbers in a short C program.

                                  Syllabus link: CAPE Computer Science Unit 1, Module 1, specific objective 4 (how data is represented, including number bases).

                                  The place values 1, 2, 4 and 8 are the columns you add. The older notes on decimal to binary show one way to convert. You met integers in Variables, format specifiers, printf %d. Continue with Binary Representation and Manipulation for signed magnitude and two’s complement. The SR Latch lesson shows how a circuit can remember one bit.

                                  What you will learn

                                  • Add unsigned binary numbers from right to left, showing every carry.
                                  • Explain why a column total of 2 or 3 produces a carry.
                                  • Distinguish the full answer from the result kept in a fixed number of bits.
                                  • Connect binary addition to the + operator in C and the computer’s ALU.

                                  The addition rules for one column

                                  Each column has three inputs: the bit from the first number, the bit from the second number, and a carry in from the place on the right. Their total is 0, 1, 2 or 3. The sum bit for this place is the remainder when that total is divided by 2. The carry out is 1 when the total is 2 or 3, and 0 otherwise. That carry out becomes the carry in for the place on the left.

                                  A + B + carry inSum bitCarry out
                                  000
                                  110
                                  201
                                  311

                                  Start at the rightmost place. Its carry in is always 0. Write the sum bit, pass the carry out left, and repeat. If the final carry out is 1, the sum needs one extra bit on the left.

                                  Binary addition grid with carries shown above the columns
                                  Figure 1. Binary addition with carries. The small digits above the columns are the carries coming from the place on the right. Phlsph7, CC0 1.0, via Wikimedia Commons.

                                  Add two 4-bit numbers

                                  Tap a place in A or in B to include it or leave it out. The sum bits and the carries update at once. Places from the left are 8, 4, 2 and 1. Try the stacked sum below before you read the worked example.

                                     1011
                                  +  0110
                                    -----
                                        ?

                                  Try it 1Switch the bits and add

                                  Orange means the place is on. Grey means it is off. A is the top row, B is the bottom row. Places left to right: 8, 4, 2, 1.

                                  Carries: none yet

                                  0000

                                  0

                                  
                                  

                                  Worked example: follow the carries

                                  1011 is 8 + 2 + 1 = 11. 0110 is 4 + 2 = 6. Add column by column from the right. The carry in to the units place is 0.

                                     1011
                                  +  0110
                                    -----
                                    10001

                                  Units place: 1 + 0 + 0 = 1. Write 1, carry out 0.

                                  Twos place: 1 + 1 + 0 = 2. Write 0, carry out 1.

                                  Fours place: 0 + 1 + 1 = 2. Write 0, carry out 1.

                                  Eights place: 1 + 0 + 1 = 2. Write 0, carry out 1.

                                  The final carry out is 1, so the full pattern is 10001. That is 16 + 1 = 17. 11 + 6 = 17. Set the top row A to 1011 and the bottom row B to 0110 on Try it 1 and confirm the sum.

                                  168421
                                  10001

                                  Fixed-width check: four unsigned bits can store 0 to 15. The full answer here is 17 and needs five bits. If only the lowest four bits are kept, the stored pattern is 0001 and the final carry is lost. This is unsigned overflow; signed overflow uses a different test.

                                  One column at a time

                                  The rules fit in one column. Tap the three inputs. The sum bit and the carry out update. This is the step the 4-bit adder repeats from right to left.

                                  Try it 2One column

                                  Tap A, B or carry in to switch them. See the sum bit and the carry out for that column only.

                                  Sum bit: 0

                                  Carry out: 0

                                  The same addition in C

                                  This program adds the same two numbers in decimal. The computer still does the addition in binary inside the ALU. Type it in Code::Blocks and run it. The result matches the decimal total from Try it 1.

                                  #include <stdio.h>
                                  
                                  int main(void) {
                                      int a = 11; /* binary 1011 */
                                      int b = 6;  /* binary 0110 */
                                      int sum = a + b;
                                      printf("The sum is %d\n", sum);
                                      return 0;
                                  }
                                  

                                  Check yourself

                                  Answer from the columns and the carries, not from memory of a paper. Your first try is the one that counts.

                                  Try it 3Three questions

                                  1. What are the four sum bits for this addition?

                                     1010
                                  +  0101
                                    -----
                                        ?

                                  2. In a column the total is 2. What do you write in that place, and what do you carry?

                                  3. What is the decimal total, including the final carry?

                                     1111
                                  +  0001
                                    -----
                                        ?

                                  Exam tips

                                  Write each operand on its own line, align the place values and start at the right. Show the carries and state whether your answer includes an extra carry bit. Check the full result in decimal. For practice with exam solutions, use the CS Solutions index and open the paper named in each solution. The questions here are original practice.

                                  Practice questions

                                  1. Add the numbers below. Show every carry. What is the decimal total?

                                     1101
                                  +  0011
                                    -----
                                        ?
                                  Show answer

                                  Units: 1+1=0 carry 1. Twos: 0+1+1=0 carry 1. Fours: 1+0+1=0 carry 1. Eights: 1+0+1=0 carry 1. Sum 10000, which is 16. 13 + 3 = 16.

                                     1101
                                  +  0011
                                    -----
                                    10000

                                  2. A column has A=1, B=1, carry in=1. What sum bit and carry out do you produce?

                                  Show answer

                                  1+1+1=3. Sum bit 1, carry out 1.

                                  3. Why does the rightmost column always start with carry in = 0?

                                  Show answer

                                  There is no place to the right of the units place, so nothing can carry into it.

                                  4. In the C program, change a to 7 and b to 9. What does it print, and what are those numbers in 4-bit binary?

                                  Show answer

                                  It prints 16. 7 is 0111, 9 is 1001, The full binary sum needs five bits.

                                     0111
                                  +  1001
                                    -----
                                    10000

                                  Homework

                                  Work these out on paper before using Try it 1. Keep the numbers on separate lines and show each carry.

                                  1. Find the full sum, then state the four stored bits and the carry out.

                                     1101
                                  +  1011
                                    -----
                                        ?

                                  2. Repeat for the next pair. Explain why this answer fits into four bits.

                                     0101
                                  +  0010
                                    -----
                                        ?
                                  Check after working

                                  1. The full answer is 11000 (24); four stored bits 1000, carry out 1.

                                     1101
                                  +  1011
                                    -----
                                    11000

                                  2. The answer is 0111 (7); carry out 0.

                                     0101
                                  +  0010
                                    -----
                                     0111

                                  Mastery quiz: Binary Addition

                                  Your course badges: loading saved progress…

                                  View badges

                                    No course badges earned yet. Score 8/10 in a lesson quiz to earn its badge.

                                    Saved in this browser on this device. Clearing browser data may remove your badges.

                                    Answer all 10 questions. Earn this lesson’s badge at 8/10 or higher. Read the explanations, revisit the Try it activities and retry as often as you need. These are self-study badges, not formal grades.

                                    1. Add these unsigned binary numbers.
                                       0101
                                    +  0011
                                      -----
                                          ?
                                    2. A column contains A = 1, B = 1 and carry in = 0. Which pair is correct?
                                    3. A column contains A = 1, B = 1 and carry in = 1. Which pair is correct?
                                    4. Find the full unsigned sum, keeping the final carry.
                                       1111
                                    +  0001
                                      -----
                                          ?
                                    5. For this unsigned addition, what remains in a four-bit register, and what is the carry out?
                                       1010
                                    +  1001
                                      -----
                                          ?
                                    6. When adding two numbers with no carry supplied from an earlier operation, why is carry in to the rightmost column 0?
                                    7. A student gets 1001 for this addition. What is the correct full sum?
                                       0111
                                    +  0001
                                      -----
                                          ?
                                    8. What does this C program print?
                                    int a = 6;
                                    int b = 5;
                                    printf("%d", a + b);
                                    9. Which unsigned addition fits in four bits without a final carry out? Work each pair in columns.
                                    10. Find the full sum, then give its decimal value.
                                       1100
                                    +  0110
                                      -----
                                          ?

                                    Next, connect the patterns to signed numbers in Binary Representation and Manipulation, or revisit Memory Types and Features to see where bits are held.

                                    Attributions to media used in this post:

                                    Phlsph7, CC0 1.0 Universal Public Domain Dedication, via Wikimedia Commons.

                                    Updates

                                    7 Nov 2026: Added the shared course badge summary and lesson mastery quiz, with feedback, retries and browser-saved progress.

                                    7 Nov 2026: Added a 10-question Binary Addition mastery quiz with feedback, retries and a browser-saved badge at 8/10.
                                    6 Nov 2026: First version. Image linked directly from Wikimedia Commons.
                                    6 Nov 2026: Matched the earlier CAPE CS lesson styling; stacked binary sums in aligned columns, added learning outcomes, fixed-width overflow guidance, homework and links to related lessons.

                                    © 2026 Vedesh Kungebeharry. All rights reserved.

                                    C Programming Tutorial: Student Records Using an Array of Structures and Binary Files

                                    This lesson continues our binary-file student-records tutorial. Previously, we stored names, Mathematics marks, and English marks in three separate parallel arrays. We will now group the fields belonging to one student into a structure, then use an array of structures. The Add, Display, Save, and Exit menu stays familiar.

                                    Learning objectives

                                    By the end, you should be able to declare a struct, create an array of structures, access fields using the dot operator, compare structures with parallel arrays, and save and load an array of student structures using binary files.

                                    1. Why use a structure?

                                    With parallel arrays, the same student is stored at the same index in three places: names[i], maths[i], and english[i]. A structure groups these related fields into one record. This makes it easier to keep each student’s information together.

                                    struct Student {
                                        char name[50];
                                        int maths;
                                        int english;
                                    };

                                    Here Student is the structure tag, and name, maths, and english are its members. The semicolon after the closing brace is required. This declaration describes a type; it does not yet create the 100 student records.

                                    2. Create an array of structures

                                    struct Student students[MAX];
                                    int n = 0;

                                    Instead of three arrays, students is one array with up to MAX student records. students[0] represents the first student, students[1] the second, and so on. As before, n counts how many records are actually in use.

                                    3. Access members using the dot operator

                                    students[0].maths = 75;
                                    students[0].english = 80;
                                    printf("%d\n", students[0].maths);

                                    The dot operator . selects a member of a structure. Compare maths[i] in the old program with students[i].maths in the new program. For a student name, use students[i].name. The array index chooses the student; the dot chooses a field within that student.

                                    4. Modify addStudent() and displayData()

                                    printf("Enter name: ");
                                    scanf("%49s", students[n].name);
                                    printf("Enter Maths mark: ");
                                    scanf("%d", &students[n].maths);
                                    printf("Enter English mark: ");
                                    scanf("%d", &students[n].english);
                                    n++;

                                    The program stores all three values in students[n] before increasing n. When displaying records, a for loop prints students[i].name, students[i].maths, and students[i].english. We still use one-word names in this introductory program.

                                    5. Save an entire structure in a binary file

                                    FILE *fp = fopen("students_struct.dat", "wb");
                                    fwrite(&n, sizeof(n), 1, fp);
                                    for (int i = 0; i < n; i++) {
                                        fwrite(&students[i], sizeof(students[i]), 1, fp);
                                    }
                                    fclose(fp);

                                    We first save n. Then each call to fwrite() saves the bytes occupied by one struct Student. This replaces the three separate writes per student from the previous tutorial. sizeof(students[i]) gives the complete structure size, which may include extra padding bytes inserted by the compiler.

                                    6. Load the structures in the same order

                                    FILE *fp = fopen("students_struct.dat", "rb");
                                    int count;
                                    fread(&count, sizeof(count), 1, fp);
                                    for (int i = 0; i < count; i++) {
                                        fread(&students[i], sizeof(students[i]), 1, fp);
                                    }
                                    fclose(fp);

                                    The saved count comes first, followed by the student structures. The full program below checks the count, file opening, and read results before accepting records. It also ensures that the last character of each name is the string terminator \0.

                                    We use a new file name, students_struct.dat, because this structure-based file layout is different from the previous binary tutorial’s layout. The new program does not automatically convert students.dat. Raw structures are suitable for learning, but their padding, integer sizes, and byte order can vary across systems; they are not a portable file format.

                                    7. Complete C program: array of structures

                                    Copy this program into a new Code::Blocks C project. Compare its struct Student, addStudent(), displayData(), saveData(), and loadData() functions with the previous tutorial.

                                    #include <stdio.h>
                                    #define MAX 100
                                    
                                    struct Student {
                                        char name[50];
                                        int maths;
                                        int english;
                                    };
                                    
                                    struct Student students[MAX];
                                    int n = 0;
                                    
                                    void loadData() {
                                        FILE *fp = fopen("students_struct.dat", "rb");
                                        if (fp == NULL) return;
                                    
                                        int count;
                                        if (fread(&count, sizeof(count), 1, fp) != 1 ||
                                            count < 0 || count > MAX) {
                                            printf("Invalid data file.\n");
                                            fclose(fp);
                                            return;
                                        }
                                    
                                        for (int i = 0; i < count; i++) {
                                            if (fread(&students[i], sizeof(students[i]), 1, fp) != 1) {
                                                printf("Incomplete record in data file.\n");
                                                n = i;
                                                fclose(fp);
                                                return;
                                            }
                                            students[i].name[49] = '\0';
                                            n++;
                                        }
                                        fclose(fp);
                                    }
                                    
                                    void saveData() {
                                        FILE *fp = fopen("students_struct.dat", "wb");
                                        if (fp == NULL) {
                                            printf("Cannot open file for writing.\n");
                                            return;
                                        }
                                    
                                        int ok = (fwrite(&n, sizeof(n), 1, fp) == 1);
                                        for (int i = 0; i < n && ok; i++) {
                                            if (fwrite(&students[i], sizeof(students[i]), 1, fp) != 1)
                                                ok = 0;
                                        }
                                        if (fclose(fp) != 0) ok = 0;
                                        if (ok) printf("Records saved.\n");
                                        else printf("Error while saving.\n");
                                    }
                                    
                                    void addStudent() {
                                        if (n >= MAX) {
                                            printf("Student array is full.\n");
                                            return;
                                        }
                                    
                                        printf("Enter name (one word): ");
                                        if (scanf("%49s", students[n].name) != 1) return;
                                        printf("Enter Maths mark: ");
                                        if (scanf("%d", &students[n].maths) != 1) return;
                                        printf("Enter English mark: ");
                                        if (scanf("%d", &students[n].english) != 1) return;
                                        n++;
                                    }
                                    
                                    void displayData() {
                                        printf("\nName\tMaths\tEnglish\n");
                                        for (int i = 0; i < n; i++) {
                                            printf("%s\t%d\t%d\n",
                                                   students[i].name,
                                                   students[i].maths,
                                                   students[i].english);
                                        }
                                    }
                                    
                                    int main() {
                                        int choice;
                                        loadData();
                                        do {
                                            printf("\n1. Add Student\n2. Display Students\n3. Save Data\n4. Exit\nEnter choice: ");
                                            if (scanf("%d", &choice) != 1) {
                                                printf("Please enter a number.\n");
                                                break;
                                            }
                                            switch (choice) {
                                                case 1: addStudent(); break;
                                                case 2: displayData(); break;
                                                case 3: saveData(); break;
                                                case 4: printf("Goodbye!\n"); break;
                                                default: printf("Invalid choice.\n");
                                            }
                                        } while (choice != 4);
                                        return 0;
                                    }

                                    8. Practical activity

                                    1. Run the program. Add John (75, 80), Mary (90, 85), and Peter (65, 70). Display the records.
                                    2. Save the records. Locate students_struct.dat in the working directory.
                                    3. Exit, run the program again, and verify that the same three students load.
                                    4. Add Sarah (88, 92), save, restart, and check that four students appear.
                                    5. Identify each occurrence of students[i].name, students[i].maths, and students[i].english. Explain what the index and dot operator do.

                                    9. Check your understanding

                                    1. What is a structure in C?
                                    2. How is an array of structures different from three parallel arrays?
                                    3. What does struct Student students[MAX]; declare?
                                    4. In students[2].maths, what does [2] select and what does .maths select?
                                    5. Why do we use &students[i] with fwrite()?
                                    6. What does sizeof(students[i]) measure?
                                    7. Why must the loading function read the count before the records?
                                    8. Why does this tutorial use students_struct.dat instead of the previous students.dat?

                                    10. Programming challenges

                                    1. Add a computerScience mark to struct Student, then update the input and display functions. Use a new file name after changing the structure layout.
                                    2. Write a function that calculates each student’s average mark.
                                    3. Write a function that finds the student with the highest Mathematics mark.
                                    4. Modify the menu so Exit automatically calls saveData().
                                    5. Investigate the difference between saving an entire structure and saving each member separately. Which method would be easier to exchange between different computers?

                                    Summary

                                    Parallel arrays store each field in a separate array. An array of structures stores related fields together as student records. The dot operator selects members, and fwrite()/fread() can save and load a complete structure in one operation. The same record-count and menu ideas from earlier lessons still apply.

                                    © 2024 Vedesh Kungebeharry. All rights reserved.

                                    C Programming Tutorial: Saving and Loading Student Records in a Binary File

                                    In the previous tutorial, we saved student records to students.txt using fprintf() and loaded them using fscanf(). This lesson modifies that same parallel-array program to use a binary file. We will keep the menu, arrays, and record count, but change the file-handling functions.

                                    Learning objectives

                                    By the end of this lesson, you should be able to distinguish text files from binary files, use fopen() with "wb" and "rb", write values using fwrite(), read them using fread(), and explain why binary records must be read in the same order they were written.

                                    1. What changes from the text-file program?

                                    Our arrays stay the same: names[MAX][50], maths[MAX], english[MAX], and n. The menu still offers Add, Display, Save, and Exit. Only the file name and file-reading/writing code change.

                                    1. Change students.txt to students.dat.
                                    2. Open the file using "wb" to write binary data or "rb" to read it.
                                    3. Replace fprintf() with fwrite().
                                    4. Replace fscanf() with fread().
                                    5. Keep the same order of fields when saving and loading.

                                    2. Text files compared with binary files

                                    In students.txt, the number 75 appears as the characters 7 and 5. A binary file stores the bytes of the C value itself. A text file is easy to inspect in a text editor; students.dat is not intended to be read as ordinary text. Both files store information after the program exits.

                                    The new file is not interchangeable with the old text file. Running this program will not automatically convert students.txt. Keep the old file for comparison; the new program uses students.dat.

                                    3. Understand fwrite() and fread()

                                    fwrite(&n, sizeof(n), 1, fp);
                                    fread(&count, sizeof(count), 1, fp);

                                    The arguments mean: address of the data, size of one item in bytes, number of items, and file pointer. The functions return the number of complete items written or read. A result of 1 means one requested item was processed successfully.

                                    The & operator gives the address of an integer. For a character array such as names[i], the array name already refers to the beginning of its storage. sizeof(names[i]) is 50 bytes, so we save a fixed-length name field.

                                    4. Save the student records as binary data

                                    FILE *fp = fopen("students.dat", "wb");
                                    fwrite(&n, sizeof(n), 1, fp);
                                    for (int i = 0; i < n; i++) {
                                        fwrite(names[i], sizeof(names[i]), 1, fp);
                                        fwrite(&maths[i], sizeof(maths[i]), 1, fp);
                                        fwrite(&english[i], sizeof(english[i]), 1, fp);
                                    }
                                    fclose(fp);

                                    The first value written is n, the number of students. The loop then writes each student’s 50-byte name field, Mathematics mark, and English mark. "wb" creates or overwrites the binary file. The complete program below also checks whether writes succeeded.

                                    5. Load the student records

                                    FILE *fp = fopen("students.dat", "rb");
                                    if (fp == NULL) return;
                                    int count;
                                    if (fread(&count, sizeof(count), 1, fp) != 1) {
                                        fclose(fp);
                                        return;
                                    }

                                    The program first tries to open the file. If it does not exist, it starts with zero students. Otherwise it reads the saved count and checks that the count is between 0 and MAX. It then reads the records in the exact same order used when saving. If the file ends unexpectedly, the program stops loading.

                                    6. Understand the binary file layout

                                    The file begins with the binary representation of the integer count. Each student then occupies 50 + sizeof(int) + sizeof(int) bytes: 50 bytes for the name, followed by two integer marks. For example, on a system where int occupies 4 bytes, that is 58 bytes per student. The count itself would occupy 4 bytes on that system.

                                    This introductory file format is designed for the same program and computer environment. Binary integer size and byte order can differ between systems, so it is not a portable interchange format. We are also storing fixed-length, single-word names.

                                    7. Complete modified C program

                                    Create a new C source file in Code::Blocks. Compare the two versions, especially loadData() and saveData().

                                    #include <stdio.h>
                                    #define MAX 100
                                    
                                    char names[MAX][50];
                                    int maths[MAX], english[MAX];
                                    int n = 0;
                                    
                                    void loadData() {
                                        FILE *fp = fopen("students.dat", "rb");
                                        if (fp == NULL) return;
                                    
                                        int count;
                                        if (fread(&count, sizeof(count), 1, fp) != 1 ||
                                            count < 0 || count > MAX) {
                                            printf("Invalid or incomplete data file.\n");
                                            fclose(fp);
                                            return;
                                        }
                                    
                                        for (int i = 0; i < count; i++) {
                                            if (fread(names[i], sizeof(names[i]), 1, fp) != 1 ||
                                                fread(&maths[i], sizeof(maths[i]), 1, fp) != 1 ||
                                                fread(&english[i], sizeof(english[i]), 1, fp) != 1) {
                                                printf("Incomplete record in data file.\n");
                                                n = i;
                                                fclose(fp);
                                                return;
                                            }
                                            names[i][49] = '\0';
                                            n++;
                                        }
                                        fclose(fp);
                                    }
                                    
                                    void saveData() {
                                        FILE *fp = fopen("students.dat", "wb");
                                        if (fp == NULL) {
                                            printf("Cannot open binary file for writing.\n");
                                            return;
                                        }
                                    
                                        int ok = (fwrite(&n, sizeof(n), 1, fp) == 1);
                                        for (int i = 0; i < n && ok; i++) {
                                            if (fwrite(names[i], sizeof(names[i]), 1, fp) != 1 ||
                                                fwrite(&maths[i], sizeof(maths[i]), 1, fp) != 1 ||
                                                fwrite(&english[i], sizeof(english[i]), 1, fp) != 1)
                                                ok = 0;
                                        }
                                        if (fclose(fp) != 0) ok = 0;
                                        if (ok) printf("Binary data saved.\n");
                                        else printf("Error while saving data.\n");
                                    }
                                    
                                    void addStudent() {
                                        if (n >= MAX) {
                                            printf("Arrays are full.\n");
                                            return;
                                        }
                                        printf("Enter name (one word): ");
                                        if (scanf("%49s", names[n]) != 1) return;
                                        printf("Enter Maths mark: ");
                                        if (scanf("%d", &maths[n]) != 1) return;
                                        printf("Enter English mark: ");
                                        if (scanf("%d", &english[n]) != 1) return;
                                        n++;
                                    }
                                    
                                    void displayData() {
                                        printf("\nName\tMaths\tEnglish\n");
                                        for (int i = 0; i < n; i++)
                                            printf("%s\t%d\t%d\n", names[i], maths[i], english[i]);
                                    }
                                    
                                    int main() {
                                        int choice;
                                        loadData();
                                        do {
                                            printf("\n1. Add Student\n2. Display Students\n3. Save Data\n4. Exit\nEnter choice: ");
                                            if (scanf("%d", &choice) != 1) {
                                                printf("Please enter a number.\n");
                                                break;
                                            }
                                            switch (choice) {
                                                case 1: addStudent(); break;
                                                case 2: displayData(); break;
                                                case 3: saveData(); break;
                                                case 4: printf("Goodbye!\n"); break;
                                                default: printf("Invalid choice.\n");
                                            }
                                        } while (choice != 4);
                                        return 0;
                                    }

                                    8. Practical activity

                                    1. Run the binary version. Add John (75, 80), Mary (90, 85), and Peter (65, 70). Select Display.
                                    2. Select Save. Find students.dat in the program’s working directory. Notice that it is not a readable list of names and marks in a text editor.
                                    3. Exit and run the program again. Select Display and verify that the three records were loaded.
                                    4. Add Sarah (88, 92), save, restart, and confirm that all four records appear.
                                    5. Compare the text and binary programs: identify the file modes and the functions used to write and read.

                                    9. Check your understanding

                                    1. Why do we use "wb" instead of "w" when writing the binary file?
                                    2. What is the purpose of fwrite()?
                                    3. What does sizeof(maths[i]) tell the program?
                                    4. Why must fread() use the same field order as fwrite()?
                                    5. Why do we save n before the student records?
                                    6. What happens if students.dat does not exist when the program starts?
                                    7. Why should you not expect to read students.dat as ordinary text?
                                    8. Does this program automatically read the old students.txt file? Explain.

                                    10. Programming challenges

                                    1. Modify the program so it saves automatically when the user selects Exit.
                                    2. Add a Computer Science mark to the parallel arrays and update both binary file functions.
                                    3. Display each student’s average mark without changing the file format.
                                    4. Investigate what happens when you try to load a damaged or incomplete students.dat file. Make a backup first.

                                    Summary

                                    The student records are still held in parallel arrays while the program runs. The difference is how they are saved: fprintf() and fscanf() handle formatted text, whereas fwrite() and fread() handle bytes. Saving and loading must agree on the record layout.

                                    © 2024 Vedesh Kungebeharry. All rights reserved.