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.

    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.

                                    Storing Records with Parallel Arrays: Names, Ages, and Marks

                                    In Strings in C: char Arrays, %s, fgets, and strlen you stored a name in a char array, and in the arrays lesson before it you stored five scores in an int array. A real class list needs both, and more: for every student, a name, an age and an average mark. In this lesson you keep a small class list in three arrays that work together, print it as a neat table, type the records in, look one up, find the top mark, and then scramble the records on purpose.

                                    In this lesson you will

                                    • Describe a student as a record made of fields: name, age and average mark
                                    • Store the records in parallel arrays, where the same index in every array is one record
                                    • Print a lined-up table with printf widths such as %-10s, %3d and %6.1f
                                    • Enter records with fgets and scanf, and deal with the leftover Enter
                                    • Look up one record by its number, and find the record with the highest mark
                                    • Break it on purpose: mismatch an index, and reorder one array but not the others

                                    Start a new project for this lesson. Copy 005-StringsCProgram to a new folder named 006-RecordsCProgram, save the project under the new name, and update its title and output filename, as before. Then replace main.c with each program below in turn.

                                    Records and fields

                                    The thing we keep data about, here a student, is called an entity. All the data about one student is a record, and each item in the record is a field. Our records have three fields: a name (text), an age (a whole number) and an average mark (a decimal number). Because the fields have different types, they cannot share one array. Instead we use one array per field:

                                        char names[5][20];   /* 5 names, each up to 19 characters */
                                        int ages[5];
                                        float marks[5];
                                    

                                    char names[5][20] is an array of 5 strings, and each string is itself a char array of 20. Read it as “5 rows of 20 characters”. names[0] is the first name, and you use it anywhere you used name in the strings lesson. The key idea is that the three arrays are parallel: the same index in each array belongs to the same student. Record 2 is names[2], ages[2] and marks[2], together:

                                    Record (index i)Name: names[i]Age: ages[i]Average mark: marks[i]
                                    0"Ken"1672.5
                                    1"Aaliyah"1788.0
                                    2"Ravi"1664.5
                                    3"Shania"1891.5
                                    4"Marcus"1779.0

                                    Each row is one record. Each column is one field, stored in its own array. Nothing in C ties the three arrays together: the only link between "Ravi", 16 and 64.5 is that they all sit at index 2. Keep that in mind for the break-it sections.

                                    Try it: print the class list

                                    Start with the data typed into the program, using initialiser lists. An array of strings takes a list of string literals:

                                    #include <stdio.h>
                                    #include <stdlib.h>
                                    
                                    int main()
                                    {
                                        char names[5][20] = {"Ken", "Aaliyah", "Ravi", "Shania", "Marcus"};
                                        int ages[5] = {16, 17, 16, 18, 17};
                                        float marks[5] = {72.5, 88.0, 64.5, 91.5, 79.0};
                                        int i;
                                    
                                        printf("%-3s %-10s %3s %6s\n", "No", "Name", "Age", "Mark");
                                        for (i = 0; i < 5; i++)
                                        {
                                            printf("%-3d %-10s %3d %6.1f\n", i, names[i], ages[i], marks[i]);
                                        }
                                        return 0;
                                    }
                                    
                                    No  Name       Age   Mark
                                    0   Ken         16   72.5
                                    1   Aaliyah     17   88.0
                                    2   Ravi        16   64.5
                                    3   Shania      18   91.5
                                    4   Marcus      17   79.0

                                    The loop is the same for (i = 0; i < 5; i++) pattern from the arrays lesson. On each pass, one printf prints field after field of record i, so one pass is one row of the table.

                                    What just happened: printf widths

                                    A number between the % and the letter is a width: the least number of characters the value takes up. Shorter values are padded with spaces, which is what lines the columns up:

                                    • %-10s: a string in 10 characters. The - means left-aligned, padded on the right. Ken becomes Ken plus 7 spaces.
                                    • %3d: an int in 3 characters, right-aligned (no -), so 16 becomes a space and 16.
                                    • %6.1f: a float in 6 characters with 1 decimal place. You already know .1 from %.2f; the 6 is the width.
                                    • %-3d: the record number, left-aligned in 3 characters.

                                    The heading line uses the same widths with %s for every column, so the titles sit above their columns. Try changing %-10s to %10s in both lines and run again: the names line up on the right instead. Change it back. A value longer than its width is never cut off; it just pushes the rest of the line along.

                                    #include <stdio.h>
                                    #include <stdlib.h>
                                    
                                    int main()
                                    {
                                        char names[5][20] = {"Ken", "Aaliyah", "Ravi", "Shania", "Marcus"};
                                        int ages[5] = {16, 17, 16, 18, 17};
                                        float marks[5] = {72.5, 88.0, 64.5, 91.5, 79.0};
                                        int i;
                                    
                                        printf("%-3s %-10s %3s %6s\n", "No", "Name", "Age", "Mark");
                                        for (i = 0; i < 5; i++)
                                        {
                                            printf("%-3d %-10s %3d %6.1f\n", i, names[i], ages[i + 1], marks[i]);
                                        }
                                        return 0;
                                    }
                                    

                                    Break it on purpose: mix up the index

                                    In the loop, change ages[i] to ages[i + 1] and leave the other two as they are. The program is shown above. Build and run. There is no error. On our test computer it printed:

                                    No  Name       Age   Mark
                                    0   Ken         17   72.5
                                    1   Aaliyah     16   88.0
                                    2   Ravi        18   64.5
                                    3   Shania      17   91.5
                                    4   Marcus       0   79.0

                                    Every age is now from the next student: Ken has Aaliyah’s age, Aaliyah has Ravi’s, and so on. Each row looks perfectly sensible, which is what makes this mistake dangerous: the compiler cannot know which age belongs to whom. The last row is worse. For i = 4 it reads ages[5], which is out of bounds, so the 0 is just whatever was in memory there (undefined behaviour, as in the arrays lesson); yours may differ. The rule for parallel arrays: one record, one index, the same in every array. Change it back to ages[i].

                                    Try it: type the records in

                                    Now let the user enter each student. Names can contain a space (Ken Ali), so read them with fgets and remove the Enter, as in the strings lesson. names[i] is a char array, so it needs no &; ages[i] and marks[i] are single numbers, so they do. Here is a first try:

                                    #include <stdio.h>
                                    #include <stdlib.h>
                                    #include <string.h>
                                    
                                    int main()
                                    {
                                        char names[5][20] = {""};
                                        int ages[5] = {0};
                                        float marks[5] = {0};
                                        int i;
                                    
                                        for (i = 0; i < 5; i++)
                                        {
                                            printf("Record %d name: ", i);
                                            fgets(names[i], sizeof(names[i]), stdin);
                                            names[i][strcspn(names[i], "\n")] = '\0';   /* remove the Enter */
                                            printf("Age: ");
                                            scanf("%d", &ages[i]);
                                            printf("Average mark: ");
                                            scanf("%f", &marks[i]);
                                        }
                                    
                                        printf("%-3s %-10s %3s %6s\n", "No", "Name", "Age", "Mark");
                                        for (i = 0; i < 5; i++)
                                        {
                                            printf("%-3d %-10s %3d %6.1f\n", i, names[i], ages[i], marks[i]);
                                        }
                                        return 0;
                                    }
                                    

                                    Break it on purpose: forget the leftover Enter

                                    Build and run. Type Ken Ali, 16 and 72.5, pressing Enter after each. Observe: the program never waits for the second name. It jumps straight to Age::

                                    Record 0 name: Ken Ali
                                    Age: 16
                                    Average mark: 72.5
                                    Record 1 name: Age: 

                                    Keep typing the same answers in the same order (Aaliyah Mohammed, 17, 88, and so on) wherever the program stops. On our test computer, the table at the end came out like this:

                                    No  Name       Age   Mark
                                    0   Ken Ali     16   72.5
                                    1                0    0.0
                                    2   Aaliyah Mohammed  17   88.0
                                    3                0    0.0
                                    4   Ravi Singh  16   64.5

                                    Records 1 and 3 are empty and everyone else has shifted down. This is the input buffer again. scanf("%f") read 72.5 and stopped, leaving your Enter waiting. The next fgets read that Enter as a complete, empty line, so record 1 got an empty name. Then scanf("%d") met the letters of Aaliyah, could not read them as a number, and left them (and ages[1], still 0) alone, so the next fgets picked up the name one record late. One leftover Enter threw every record after it out of line.

                                    The fix is to take that one leftover Enter out of the buffer before the next fgets. getchar(), from stdio.h, reads exactly one character. Add it straight after the scanf for the mark:

                                            scanf("%f", &marks[i]);
                                            getchar();   /* eat the Enter left after the mark */
                                    

                                    Build and run again, and enter all five students:

                                    Record 0 name: Ken Ali
                                    Age: 16
                                    Average mark: 72.5
                                    Record 1 name: Aaliyah Mohammed
                                    Age: 17
                                    Average mark: 88
                                    Record 2 name: Ravi Singh
                                    Age: 16
                                    Average mark: 64.5
                                    Record 3 name: Shania Joseph
                                    Age: 18
                                    Average mark: 91.5
                                    Record 4 name: Marcus Lee
                                    Age: 17
                                    Average mark: 79
                                    No  Name       Age   Mark
                                    0   Ken Ali     16   72.5
                                    1   Aaliyah Mohammed  17   88.0
                                    2   Ravi Singh  16   64.5
                                    3   Shania Joseph  18   91.5
                                    4   Marcus Lee  17   79.0

                                    Every record is right. Notice rows 1 and 3: Aaliyah Mohammed and Shania Joseph are longer than 10 characters, so, as promised, %-10s does not cut them off and the rest of the row is pushed along. Widen the name column to %-18s in both printf lines and the table lines up again. Remember too that each name holds at most 19 characters; fgets stops there, safely.

                                    Try it: look up one record

                                    Because a record is just an index, finding a student by number is one scanf. Go back to the typed-in data and replace main with this:

                                    #include <stdio.h>
                                    #include <stdlib.h>
                                    
                                    int main()
                                    {
                                        char names[5][20] = {"Ken", "Aaliyah", "Ravi", "Shania", "Marcus"};
                                        int ages[5] = {16, 17, 16, 18, 17};
                                        float marks[5] = {72.5, 88.0, 64.5, 91.5, 79.0};
                                    
                                        int n = 0;
                                    
                                        printf("Which record (0 to 4)? ");
                                        scanf("%d", &n);
                                    
                                        printf("Name: %s\n", names[n]);
                                        printf("Age: %d\n", ages[n]);
                                        printf("Average mark: %.1f\n", marks[n]);
                                        return 0;
                                    }
                                    

                                    Run it and type 3:

                                    Which record (0 to 4)? 3
                                    Name: Shania
                                    Age: 18
                                    Average mark: 91.5

                                    The single number n picks out all three fields of record 3. Now run it again and type 7. There are only 5 records, so names[7], ages[7] and marks[7] are all out of bounds: you may get garbage, an empty name, or a crash. The program cannot refuse a bad number yet, because that needs an if, which you meet properly in a later lesson.

                                    Try it: who has the top mark?

                                    To find the best student, look at every mark and remember the index of the highest so far. This needs one new idea, the if statement, shown here only lightly: if (condition) { ... } runs the statements in the braces only when the condition is true. You will learn it properly later.

                                    #include <stdio.h>
                                    #include <stdlib.h>
                                    
                                    int main()
                                    {
                                        char names[5][20] = {"Ken", "Aaliyah", "Ravi", "Shania", "Marcus"};
                                        int ages[5] = {16, 17, 16, 18, 17};
                                        float marks[5] = {72.5, 88.0, 64.5, 91.5, 79.0};
                                        int i;
                                    
                                        int best = 0;   /* index of the best record so far */
                                    
                                        for (i = 1; i < 5; i++)
                                        {
                                            if (marks[i] > marks[best])
                                            {
                                                best = i;
                                            }
                                        }
                                    
                                        printf("Top mark: %s, age %d, with %.1f\n", names[best], ages[best], marks[best]);
                                        return 0;
                                    }
                                    
                                    Top mark: Shania, age 18, with 91.5

                                    best starts at 0, assuming the first student is the best so far, so the loop starts from index 1. On each pass, marks[i] > marks[best] asks “is this mark higher than the best so far?” If it is, best becomes i. Trace it: 88.0 beats 72.5 (best = 1), 64.5 does not, 91.5 beats 88.0 (best = 3), 79.0 does not. Because best is an index, not a mark, it finds the whole record: the name and age come along for free. Try it: change > to < and the program finds the lowest mark instead. What does it print?

                                    #include <stdio.h>
                                    #include <stdlib.h>
                                    
                                    int main()
                                    {
                                        char names[5][20] = {"Ken", "Aaliyah", "Ravi", "Shania", "Marcus"};
                                        int ages[5] = {16, 17, 16, 18, 17};
                                        float marks[5] = {91.5, 88.0, 79.0, 72.5, 64.5};
                                        int i;
                                    
                                        printf("%-3s %-10s %3s %6s\n", "No", "Name", "Age", "Mark");
                                        for (i = 0; i < 5; i++)
                                        {
                                            printf("%-3d %-10s %3d %6.1f\n", i, names[i], ages[i], marks[i]);
                                        }
                                        return 0;
                                    }
                                    

                                    Break it on purpose: sort one array and not the others

                                    A teacher wants the list from highest mark to lowest. A thought experiment: what if you sort only marks? Go back to the table program and change just the marks list to {91.5, 88.0, 79.0, 72.5, 64.5}, the same five marks in order, leaving names and ages alone. The program is shown above. Build and run:

                                    No  Name       Age   Mark
                                    0   Ken         16   91.5
                                    1   Aaliyah     17   88.0
                                    2   Ravi        16   79.0
                                    3   Shania      18   72.5
                                    4   Marcus      17   64.5

                                    The marks are sorted, but now Ken has Shania’s 91.5 and Shania has Ken’s 72.5. Every mark still exists, but most are attached to the wrong student. With parallel arrays, any reordering must move all the fields of a record together: whenever you move marks[i], you must move names[i] and ages[i] in exactly the same way. Forget one array once, and the records are scrambled for good.

                                    That is the weakness of parallel arrays: the fields of one record are spread across separate arrays, held together only by your care with the index. C has a better tool, the struct, which groups a record’s fields into one variable, so a student’s name, age and mark travel together. Structs are coming in a later lesson.

                                    Common mistakes

                                    • Using different indexes for the same record, such as names[i] with ages[i + 1].
                                    • Reordering, adding or deleting in one array but not the others.
                                    • Forgetting getchar() after scanf, so the next fgets reads an empty line.
                                    • Putting & in front of names[i] (a string), or leaving it off &ages[i] (a number).
                                    • Looking up a record number outside 0 to 4.

                                    Key terms

                                    • Entity: the thing you store data about, here a student.
                                    • Record: all the data about one entity, such as one student’s name, age and mark.
                                    • Field: one item in a record, such as the age.
                                    • Parallel arrays: separate arrays, one per field, where the same index in each array is one record.
                                    • Array of strings: a two-dimensional char array such as char names[5][20]: 5 strings of up to 19 characters.
                                    • Field width: the number in a format specifier, such as the 10 in %-10s, giving the least number of characters to print. - means left-aligned.
                                    • getchar(): reads one character from the input; used here to remove a leftover Enter.
                                    • if: runs a block of statements only when a condition is true (a full lesson comes later).
                                    • struct: a C type that groups the fields of a record together (coming in a later lesson).

                                    Quick check

                                    1. In the class list, which three elements make up record 4?

                                      Show answer

                                      names[4], ages[4] and marks[4]: Marcus, 17, 79.0.

                                    2. What does printf("[%-6s][%4d]", "Ana", 15); print?

                                      Show answer

                                      [Ana ][ 15]: Ana left-aligned in 6 characters, 15 right-aligned in 4.

                                    3. A program reads a mark with scanf("%f", &marks[i]); and then the next name with fgets, but every name after the first is empty. Why, and what is the fix?

                                      Show answer

                                      scanf leaves the Enter in the input buffer, and fgets reads it as an empty line. Add getchar(); after the scanf.

                                    4. Why does the top-mark program remember best as an index rather than the mark itself?

                                      Show answer

                                      An index identifies the whole record, so names[best] and ages[best] give the name and age that go with the mark.

                                    5. You sort names into alphabetical order but leave ages and marks alone. What goes wrong?

                                      Show answer

                                      The records are scrambled: names no longer line up with their ages and marks, because each record is held together only by its index.

                                    Part of the Introduction to C series. Next: Storing Data in Files (Plain Text and Binary)

                                    Arrays in C: Storing Many Values Under One Name

                                    Every variable so far has held exactly one value. In Using Library Functions: #include, getch(), and the Input Buffer you used functions that other people wrote; in this lesson you learn to keep a whole list of values under one name. You start with five test scores in five separate variables, feel how quickly that gets painful, then store them in one array, visit every score with a short loop, work out the average, and break it on purpose by reaching past the end.

                                    In this lesson you will

                                    • See why five separate variables (score1 to score5) do not scale
                                    • Declare an array, give it a size, and read and write its elements by index, counting from 0
                                    • Fill an array in one line with an initialiser list { }
                                    • Meet a first for loop, just enough to visit every index, and use it to print, total and average the scores
                                    • Read values into the array with scanf
                                    • Break it on purpose: go past the end, forget the size, copy with =, and use <= in the loop

                                    Start a new project for this lesson. Copy 003-FunctionDemoCProgram to a new folder named 004-ArraysCProgram, save the project under the new name, and update its title and output filename, as before. Then replace main.c with each program below in turn.

                                    Try it: five scores, five variables

                                    Suppose a teacher wants the total of five test scores. With what you know so far, you need one variable per score:

                                    #include <stdio.h>
                                    #include <stdlib.h>
                                    
                                    int main()
                                    {
                                        int score1 = 72;
                                        int score2 = 85;
                                        int score3 = 64;
                                        int score4 = 90;
                                        int score5 = 58;
                                    
                                        int total = score1 + score2 + score3 + score4 + score5;
                                        printf("Total: %d\n", total);
                                        return 0;
                                    }
                                    
                                    Total: 369

                                    It works, but imagine the class has 30 students. That is 30 declarations, and a sum line with 30 names in it. Miss one and the total is wrong with no error. Every new score means editing the program in several places. What we want is one name for the whole list of scores, and a number that says which score we mean.

                                    Try it: one array, five boxes

                                    Replace main with this:

                                    #include <stdio.h>
                                    #include <stdlib.h>
                                    
                                    int main()
                                    {
                                        int scores[5];
                                    
                                        scores[0] = 72;
                                        scores[1] = 85;
                                        scores[2] = 64;
                                        scores[3] = 90;
                                        scores[4] = 58;
                                    
                                        printf("First score: %d\n", scores[0]);
                                        printf("Last score: %d\n", scores[4]);
                                    
                                        scores[2] = 70;
                                        printf("Third score, corrected: %d\n", scores[2]);
                                        return 0;
                                    }
                                    
                                    First score: 72
                                    Last score: 58
                                    Third score, corrected: 70

                                    What just happened

                                    int scores[5]; declares an array of 5 int variables side by side in memory, all called scores. The number in square brackets in the declaration is the size: how many elements (boxes) the array has. After that, a number in square brackets is an index: which box you mean. scores[0] = 72; writes to a box, and scores[0] inside printf reads from it. Each element behaves exactly like an ordinary int variable.

                                    Counting starts at 0. An array of size 5 has indexes 0, 1, 2, 3 and 4. There is no scores[5]. In memory it looks like this:

                                    Elementscores[0]scores[1]scores[2]scores[3]scores[4]
                                    Index01234
                                    Contents7285709058
                                    Which score1st2nd3rd4th5th

                                    Notice that the 1st score is at index 0 and the 5th is at index 4: the index is always one less than the position. Changing scores[2] to 70 changed one box and left the others alone.

                                    Try it: fill it in one line

                                    Writing each element on its own line is still long. You can fill an array as you declare it with an initialiser list: the values in curly braces, separated by commas, in index order:

                                    #include <stdio.h>
                                    #include <stdlib.h>
                                    
                                    int main()
                                    {
                                        int scores[5] = {72, 85, 64, 90, 58};
                                    
                                        printf("Second score: %d\n", scores[1]);
                                        printf("Fourth score: %d\n", scores[3]);
                                        return 0;
                                    }
                                    
                                    Second score: 85
                                    Fourth score: 90

                                    The first value goes into scores[0], the next into scores[1], and so on. If you give fewer values than the size, the rest are set to 0, so int scores[5] = {0}; is a handy way to start with every box at 0, just like the defensive initialisation in the scanf lesson.

                                    Now break the declaration:

                                    #include <stdio.h>
                                    #include <stdlib.h>
                                    
                                    int main()
                                    {
                                        int scores[];
                                    
                                        printf("Second score: %d\n", scores[1]);
                                        printf("Fourth score: %d\n", scores[3]);
                                        return 0;
                                    }
                                    

                                    Break it on purpose: forget the size

                                    Change the declaration to int scores[];, with no size and no initialiser list. Build it. The build stops with:

                                    main.c:6:9: error: array size missing in 'scores'

                                    C must know how many boxes to set aside before the program runs. Either put the size in the brackets, or give an initialiser list so the compiler can count the values: int scores[] = {72, 85, 64, 90, 58}; makes an array of 5. Put the 5 and the list back.

                                    Try it: visit every index with a for loop

                                    Printing each score with its own printf is no better than five variables. The point of an index is that it can be a variable: scores[i] means “the box whose number is in i”. A for loop lets i take the values 0, 1, 2, 3, 4 in turn. Loops get a lesson of their own later. For now, learn this one pattern:

                                    #include <stdio.h>
                                    #include <stdlib.h>
                                    
                                    int main()
                                    {
                                        int scores[5] = {72, 85, 64, 90, 58};
                                        int i;
                                    
                                        for (i = 0; i < 5; i++)
                                        {
                                            printf("scores[%d] = %d\n", i, scores[i]);
                                        }
                                        return 0;
                                    }
                                    
                                    scores[0] = 72
                                    scores[1] = 85
                                    scores[2] = 64
                                    scores[3] = 90
                                    scores[4] = 58

                                    Read for (i = 0; i < 5; i++) in three parts, separated by semicolons:

                                    • i = 0: start with i at 0, the first index.
                                    • i < 5: keep going while i is less than 5, the size. When i reaches 5 the loop stops.
                                    • i++: after each pass, add 1 to i. It is short for i = i + 1.

                                    The statements in the curly braces run once for each value of i. Change the 5 to 3 and only the first three scores print. Change it back. With 30 students, you would change the array size and the 5 in the loop, and nothing else.

                                    #include <stdio.h>
                                    #include <stdlib.h>
                                    
                                    int main()
                                    {
                                        int scores[5] = {72, 85, 64, 90, 58};
                                        int i;
                                    
                                        for (i = 0; i <= 5; i++)
                                        {
                                            printf("scores[%d] = %d\n", i, scores[i]);
                                        }
                                        return 0;
                                    }
                                    

                                    Break it on purpose: use <= in the loop

                                    Change i < 5 to i <= 5 (“less than or equal to”). Build and run. There is no error and no warning. On our test computer it printed:

                                    scores[0] = 72
                                    scores[1] = 85
                                    scores[2] = 64
                                    scores[3] = 90
                                    scores[4] = 58
                                    scores[5] = 0

                                    Six lines from a five-box array. With <=, the loop also runs when i is 5, and reads scores[5], a box that does not exist. The value you see is whatever happens to be in the memory just after the array, so your number may be different, and it may change from run to run. This is called an off-by-one error. For an array of size 5, the loop test is i < 5, never i <= 5. Change it back.

                                    Try it: total and average

                                    The loop can do more than print. Here it adds each score to a running total, then divides by 5:

                                    #include <stdio.h>
                                    #include <stdlib.h>
                                    
                                    int main()
                                    {
                                        int scores[5] = {72, 85, 64, 90, 58};
                                        int i;
                                        int total = 0;
                                        float average = 0;
                                    
                                        for (i = 0; i < 5; i++)
                                        {
                                            total = total + scores[i];
                                        }
                                    
                                        average = total / 5;
                                    
                                        printf("Total: %d\n", total);
                                        printf("Average: %.2f\n", average);
                                        return 0;
                                    }
                                    
                                    Total: 369
                                    Average: 73.00

                                    The total is right, but 369 ÷ 5 is 73.8, not 73.00. You have seen this before in the int vs float lesson. total and 5 are both int, so C does whole-number division and truncates the answer to 73 before it is stored in the float. Storing it in a float afterwards cannot bring the .8 back. Make one side of the division a decimal number:

                                        average = total / 5.0;
                                    
                                    Total: 369
                                    Average: 73.80

                                    Trace the loop once by hand: total starts at 0, then becomes 72, 157, 221, 311 and finally 369. If you want to watch it happen, set a breakpoint on the total = total + scores[i]; line and add i and total as watches, as in the debugging lesson.

                                    Try it: read the scores in

                                    Now let the user type the scores. Each element is an ordinary int, so scanf needs its location, with &, just like &x in the scanf lesson:

                                    #include <stdio.h>
                                    #include <stdlib.h>
                                    
                                    int main()
                                    {
                                        int scores[5] = {0};
                                        int i;
                                        int total = 0;
                                    
                                        for (i = 0; i < 5; i++)
                                        {
                                            printf("Enter score %d: ", i + 1);
                                            scanf("%d", &scores[i]);
                                        }
                                    
                                        for (i = 0; i < 5; i++)
                                        {
                                            total = total + scores[i];
                                        }
                                    
                                        printf("You entered: %d %d %d %d %d\n", scores[0], scores[1], scores[2], scores[3], scores[4]);
                                        printf("Average: %.2f\n", total / 5.0);
                                        return 0;
                                    }
                                    

                                    Build and run. Type each score and press Enter:

                                    Enter score 1: 72
                                    Enter score 2: 85
                                    Enter score 3: 64
                                    Enter score 4: 90
                                    Enter score 5: 58
                                    You entered: 72 85 64 90 58
                                    Average: 73.80

                                    &scores[i] means “the location of box i”. Each element is one int box, so scanf needs the & in front of it, exactly as for a single variable. The prompt shows i + 1 so that people see 1 to 5, while the program uses indexes 0 to 4.

                                    Try it: one past the end

                                    Replace main with this short program, which asks for the element after the last one:

                                    #include <stdio.h>
                                    #include <stdlib.h>
                                    
                                    int main()
                                    {
                                        int scores[5] = {72, 85, 64, 90, 58};
                                    
                                        printf("scores[4] = %d\n", scores[4]);
                                        printf("scores[5] = %d\n", scores[5]);
                                        return 0;
                                    }
                                    

                                    Break it on purpose: ask for scores[5]

                                    Build and run. On our test computer, GCC gave no error and no warning (even with -Wall), and printed:

                                    scores[4] = 58
                                    scores[5] = 0

                                    C does not check indexes. It works out where box 5 would be and reads that memory, even though it is not part of the array. This is out of bounds access, and the C standard calls the result undefined behaviour: it may print a garbage number, it may print 0 and look fine, it may give a different answer on another computer, or the program may crash. Writing out of bounds, such as scores[5] = 99;, is worse, because it can change some other variable without warning. Keeping every index between 0 and size − 1 is your job, not the compiler’s.

                                    Try it: copy one array into another

                                    Suppose you want a backup of the scores before changing them:

                                    #include <stdio.h>
                                    #include <stdlib.h>
                                    
                                    int main()
                                    {
                                        int scores[5] = {72, 85, 64, 90, 58};
                                        int backup[5];
                                    
                                        backup = scores;
                                        printf("backup[0] = %d\n", backup[0]);
                                        return 0;
                                    }
                                    

                                    Break it on purpose: copy an array with =

                                    Build it. The build stops with:

                                    main.c:9:12: error: assignment to expression with array type

                                    After it is declared, a whole array cannot be assigned with =. Instead, copy the elements one at a time with the loop.

                                    Replace the backup = scores; line with a loop (and declare int i; with the other variables):

                                        for (i = 0; i < 5; i++)
                                        {
                                            backup[i] = scores[i];
                                        }
                                    
                                    backup[0] = 72

                                    Common mistakes

                                    • Using index 5 in an array of size 5. The last index is always size − 1.
                                    • Writing i <= 5 instead of i < 5 in the loop.
                                    • Forgetting that total / 5 with two ints truncates. Use 5.0.
                                    • Leaving out the & in scanf("%d", &scores[i]);.
                                    • Trying to copy or assign a whole array with =.

                                    Key terms

                                    • Array: a row of variables of the same type under one name, such as int scores[5].
                                    • Element: one box in an array, such as scores[2].
                                    • Size: the number of elements, given in the declaration. It cannot change while the program runs.
                                    • Index: the position of an element, counted from 0. Valid indexes run from 0 to size − 1.
                                    • Initialiser list: values in curly braces that fill an array as it is declared, such as {72, 85, 64, 90, 58}.
                                    • for loop: repeats a block of statements; here, once for each index from 0 to size − 1.
                                    • Off-by-one error: a loop or index that goes one step too far (or stops one step short).
                                    • Out of bounds: using an index outside the array. C does not check it; the result is undefined behaviour.

                                    Quick check

                                    1. An array is declared float temps[7];. What are its first and last valid indexes?

                                      Show answer

                                      temps[0] and temps[6].

                                    2. What is in each element after int counts[4] = {3, 9};?

                                      Show answer

                                      counts[0] is 3, counts[1] is 9, and counts[2] and counts[3] are 0.

                                    3. A program prints scores[5] from a size-5 array and gets 0, with no error. Is the program correct?

                                      Show answer

                                      No. scores[5] is out of bounds. C does not check it, so the 0 is just whatever was in that memory: undefined behaviour that may print something else, or crash, elsewhere.

                                    4. A total of 47 is divided by 4 with average = total / 4; and average is a float. What prints with %.2f, and how do you fix it?

                                      Show answer

                                      11.00, because int ÷ int truncates. Use total / 4.0 to get 11.75.

                                    5. Why does scanf("%d", &scores[i]); need the &?

                                      Show answer

                                      Each element is an ordinary int variable, and scanf needs its location, just like &x.

                                    Coming up: text is an array too

                                    Every array in this lesson held numbers, but the type in each box can be anything, including char, a single character. Put a row of characters in an array and you have a word. In the next lesson you will see that a string in C is just an array of char, so everything here, from indexes starting at 0 to = refusing to copy, carries straight over.

                                    Part of the Introduction to C series. Next: Strings in C: char Arrays, %s, fgets, and strlen

                                    Strings in C: char Arrays, %s, fgets, and strlen

                                    In the last lesson, Arrays in C: Storing Many Values Under One Name, you stored many numbers under one name in an array. A string is the same idea: an array of char, one character in each box. Every variable so far has held a number, but programs work with text all the time: names, cities, answers. In this lesson you store one character, then a whole word, then read a name from the keyboard and break it on purpose. Along the way you find out what the \0 escape sequence from the printf lesson is for, and meet the input buffer from Using Library Functions: #include, getch(), and the Input Buffer again.

                                    In this lesson you will

                                    • Store a single character in a char variable and print it with %c
                                    • Store a word as a string: a row of characters ending in '\0'
                                    • Print a string with %s and read one with scanf, and find out why it stops at a space
                                    • Read a whole line safely with fgets, and spot the Enter key it keeps
                                    • Use strlen and strcpy from string.h, and learn why = cannot copy a string

                                    Start a new project for this lesson. Copy 004-ArraysCProgram to a new folder named 005-StringsCProgram, save the project under the new name, and update its title and output filename, as before. Then replace main.c with each program below in turn.

                                    Try it: one character

                                    The data-type table in the int vs float lesson listed char, a type that holds a single character, printed with %c. Try it:

                                    #include <stdio.h>
                                    #include <stdlib.h>
                                    
                                    int main()
                                    {
                                        char initial = 'K';
                                    
                                        printf("Your initial is %c\n", initial);
                                        return 0;
                                    }
                                    
                                    Your initial is K

                                    Notice the single quotes. 'K' is a character literal: exactly one character. Double quotes make a string literal, which can hold many. Change 'K' to "K" and the build complains. Change it back.

                                    Try it: a whole word

                                    A char holds one character, so a name needs a whole row of them. Replace main with this:

                                    #include <stdio.h>
                                    #include <stdlib.h>
                                    
                                    int main()
                                    {
                                        char name[20] = "Ken";
                                    
                                        printf("Hello, %s!\n", name);
                                        printf("Letters: %c %c %c\n", name[0], name[1], name[2]);
                                        printf("After the last letter: %d\n", name[3]);
                                    
                                        name[0] = 'B';
                                        printf("Hello, %s!\n", name);
                                        return 0;
                                    }
                                    
                                    Hello, Ken!
                                    Letters: K e n
                                    After the last letter: 0
                                    Hello, Ben!

                                    What just happened

                                    char name[20] declares an array, just like int scores[5] in the arrays lesson, except that each of its 20 boxes holds a char instead of an int. You reach each one by its index in square brackets, and counting still starts at 0, so name[0] is the first character and name[19] is the last.

                                    Initialising the array with "Ken" fills it like this:

                                    Index01234 to 19
                                    Contents'K''e''n''\0''\0' (unused)

                                    Straight after the last letter sits '\0', the null character. Printed as a number with %d, it shows as 0. This is the end marker that the escape-sequence table promised to explain: in C, a string is a row of characters that ends with '\0'. %s tells printf to start at the first character and keep printing until it reaches the '\0'. Changing name[0] to 'B' changed one box, so the whole word became Ben.

                                    Because the end marker takes up one place, an array of 20 characters can hold a string of at most 19 characters.

                                    Try it: ask for the name

                                    Now let the user type the name. scanf reads a string with %s:

                                    #include <stdio.h>
                                    #include <stdlib.h>
                                    
                                    int main()
                                    {
                                        char name[20] = "";
                                        char colour[20] = "";
                                    
                                        printf("What is your name?\n");
                                        scanf("%s", name);
                                        printf("What is your favourite colour?\n");
                                        scanf("%s", colour);
                                    
                                        printf("Hello, %s! Your favourite colour is %s.\n", name, colour);
                                        return 0;
                                    }
                                    

                                    Build and run. Type Ken and press Enter, then type blue and press Enter:

                                    What is your name?
                                    Ken
                                    What is your favourite colour?
                                    blue
                                    Hello, Ken! Your favourite colour is blue.

                                    Look closely: there is no & in front of name. In the scanf lesson, scanf needed &x, the location of the variable. The name of an array already stands for the location of its first character, so name on its own is enough. Add an & out of habit and GCC warns:

                                    warning: format '%s' expects argument of type 'char *', but argument 2 has type 'char (*)[20]' [-Wformat=]

                                    If you tried that, remove the & again and rebuild.

                                    Break it on purpose: type a name with a space

                                    Run the program again. At the first question type Ken Smith and press Enter. Observe: the program does not wait for the colour. It answers straight away:

                                    What is your name?
                                    Ken Smith
                                    What is your favourite colour?
                                    Hello, Ken! Your favourite colour is Smith.

                                    Your surname has become your favourite colour.

                                    %s in scanf reads one word. It stops at the first space, tab or Enter. So name got Ken, and the rest of the line, Smith and the Enter, stayed behind in the input buffer, the same waiting area that caught the held-down key in the previous lesson. The second scanf found Smith already waiting and took it without asking.

                                    Try it: read the whole line with fgets

                                    To read everything the user typed, up to and including the Enter, use fgets (“file get string”). Here the “file” is stdin, the standard input, which is normally the keyboard. The program also uses strlen (“string length”), which counts the characters before the '\0'. It is declared in string.h, so the program includes that header:

                                    #include <stdio.h>
                                    #include <stdlib.h>
                                    #include <string.h>
                                    
                                    int main()
                                    {
                                        char name[20] = "";
                                    
                                        printf("What is your full name?\n");
                                        fgets(name, sizeof(name), stdin);
                                    
                                        int length = strlen(name);
                                        printf("Hello, %s!\n", name);
                                        printf("Your name has %d characters.\n", length);
                                        return 0;
                                    }
                                    

                                    Run it and type Ken Smith. Observe two odd things:

                                    What is your full name?
                                    Ken Smith
                                    Hello, Ken Smith
                                    !
                                    Your name has 10 characters.

                                    The ! has dropped onto the next line, and Ken Smith has 9 characters (the space counts), not 10. Both clues point to the same thing: fgets keeps the Enter key. The string in memory is Ken Smith\n. That hidden \n is the tenth character, and printing it moves the ! to a new line.

                                    fgets takes three things: where to store the text, the size of the array (sizeof(name), here 20), and where to read from (stdin). Because it knows the size, it stores at most 19 characters plus the '\0'.

                                    To remove the Enter, add one line after the fgets. strcspn(name, "\n"), also from string.h, counts the characters before the first \n, which is exactly the index where the \n sits. Putting '\0' there ends the string one place earlier. Rebuild and run with Ken Smith again:

                                        fgets(name, sizeof(name), stdin);
                                        name[strcspn(name, "\n")] = '\0';   /* remove the Enter */
                                    
                                    What is your full name?
                                    Ken Smith
                                    Hello, Ken Smith!
                                    Your name has 9 characters.

                                    Now try a long name, such as Alexandria Montgomery-Smith. The program prints Hello, Alexandria Montgome! (19 characters). fgets stopped when the array was full and left the rest in the input buffer. Cut off, but safe.

                                    Why the size matters: buffer overflow. scanf("%s", name) does not know how big name is. Type more than 19 characters and it writes past the end of the array, over whatever memory comes next. This is a buffer overflow. The program may crash, quietly change other variables, or work on one computer and fail on another, and attackers use overflows to break into systems. fgets is given the size, so it cannot overflow. (Old books mention a function called gets. It has the same problem and has been removed from C. Never use it.)

                                    Try it: give the string a new value

                                    You can set a number with = at any time, so it seems natural to do the same with a string:

                                    #include <stdio.h>
                                    #include <stdlib.h>
                                    #include <string.h>
                                    
                                    int main()
                                    {
                                        char name[20] = "Ken";
                                        printf("Before: %s\n", name);
                                    
                                        name = "Kenneth";
                                        printf("After: %s\n", name);
                                        return 0;
                                    }
                                    

                                    Break it on purpose: copy a string with =

                                    Build it. The build stops with:

                                    main.c:10:10: error: assignment to expression with array type

                                    = worked in the declaration, char name[20] = "Ken";, because that is initialisation: the array is filled as it is created. Afterwards, C does not let you assign a whole array with =.

                                    To copy text into an existing array, use strcpy (“string copy”) from string.h. It copies the characters one by one, including the '\0'. Replace the = line with:

                                        strcpy(name, "Kenneth");
                                    
                                    Before: Ken
                                    After: Kenneth

                                    Read strcpy(name, "Kenneth") as “copy "Kenneth" into name”: the destination comes first, like the left side of =. Like scanf("%s"), strcpy does not check the size, so the destination must be big enough.

                                    Key terms

                                    • char: a data type that holds a single character, printed with %c.
                                    • Character literal: one character in single quotes, such as 'K'.
                                    • Array: a row of variables of the same type under one name, such as char name[20].
                                    • Index: the position of an item in an array, counted from 0, as in name[0].
                                    • String: in C, a row of characters in a char array, ending with '\0'.
                                    • Null character ('\0'): the character with value 0 that marks the end of a string.
                                    • %s: the format specifier for a string, in both printf and scanf.
                                    • fgets: reads a whole line of input, up to a size limit, and keeps the Enter (\n).
                                    • strlen: a string.h function that counts the characters in a string, not including the '\0'.
                                    • Buffer overflow: writing past the end of an array, into memory that belongs to something else.

                                    Quick check

                                    1. How big must a char array be to hold the string "Hello"?

                                      Show answer

                                      At least 6: five letters plus the '\0' at the end.

                                    2. A program uses scanf("%s", city); and the user types Port of Spain. What ends up in city, and where is the rest?

                                      Show answer

                                      Port. %s stops at the first space, and of Spain plus the Enter wait in the input buffer for the next read.

                                    3. After fgets(name, sizeof(name), stdin) reads Ana, strlen(name) says 4. Why?

                                      Show answer

                                      fgets keeps the Enter, so the string is Ana\n. Remove it with name[strcspn(name, "\n")] = '\0';

                                    4. city = "Paris"; gives assignment to expression with array type. How do you fix it?

                                      Show answer

                                      Use strcpy(city, "Paris"); and add #include <string.h>. Arrays cannot be assigned with = after they are declared.

                                    Part of the Introduction to C series. Next: Storing Records with Parallel Arrays

                                    Updates

                                    2026/10/07
                                    – Moved after the new Arrays lesson and added a link back to it.