Bytebook Compiler

Bytebook · YEAR 1

First-Year Foundations

How computers, code and the web really work: number systems, logic gates, algorithms and flowcharts, the Linux terminal, Git and GitHub, HTML, CSS and JavaScript.

Back to lessons

Chapter 1 · Computer Basics

How Computers Work

What is inside a computer — CPU, memory, storage and I/O — the fetch–decode–execute cycle, the memory hierarchy, and what an operating system does for your programs.

Every program you will write in C, Python or C++ eventually runs on the same few pieces of hardware. Knowing them explains why some code is fast and some is slow.

The main parts

Part Job Analogy
CPU (processor) executes instructions: arithmetic, comparisons, jumps the chef
RAM (main memory) holds running programs and their data; fast but volatile (erased when power goes off) the kitchen counter
Storage (SSD/HDD) keeps files permanently; much slower than RAM the pantry
Input devices keyboard, mouse, camera, microphone, network orders coming in
Output devices screen, speakers, printer, network plates going out
Motherboard / bus connects everything and carries data between parts the corridors

This design — a CPU that fetches both instructions and data from the same memory — is the von Neumann architecture (1945), and nearly every computer still follows it.

Inside the CPU

  • ALU (arithmetic logic unit): adds, subtracts, compares, does AND/OR/NOT.
  • Control unit: decodes instructions and directs the other parts.
  • Registers: a few tiny, ultra-fast storage slots inside the CPU, including the program counter (address of the next instruction).
  • Cache: small fast memory between the CPU and RAM (L1, L2, L3).
  • Clock: a 3 GHz CPU ticks 3 billion times per second. Modern chips have several cores, each able to run its own stream of instructions.

The fetch–decode–execute cycle

The CPU repeats three steps billions of times per second:

Power onFETCH the instruction at the program counterDECODE it: which operation, which data?EXECUTE it in the ALU, read or write memoryMove the program counter to the next instructionRepeat (billions of times per second)
The instruction cycle. A loop in your code is just the CPU jumping the program counter back to an earlier instruction.

The memory hierarchy

Faster memory is more expensive and smaller. Computers stack several layers:

Level Typical size Typical access time
Registers under 1 KB under 1 ns
L1 cache 32–64 KB per core about 1 ns
L2 / L3 cache 1–64 MB 3–15 ns
RAM 8–32 GB about 100 ns
SSD 256 GB–2 TB about 100,000 ns (0.1 ms)
Hard disk 1–10 TB about 10,000,000 ns (10 ms)

Reading from RAM is about 100 times slower than from L1 cache. Programs that access memory sequentially (like walking through an array) let the cache prefetch data and run much faster than programs that jump around (like following linked-list pointers).

Units of data

Unit Size
bit a single 0 or 1
byte 8 bits — one character in ASCII
kilobyte (KB) 1,024 bytes (strictly, KiB)
megabyte (MB) 1,024 KB
gigabyte (GB) 1,024 MB
terabyte (TB) 1,024 GB

(Storage makers use powers of 1000, which is why a "1 TB" drive shows up as about 931 GB.)

The operating system

The operating system (Linux, Windows, macOS, Android) is the program that manages the hardware for every other program:

  • Process management — runs many programs at once by switching the CPU between them very quickly.
  • Memory management — gives each program its own memory space and protects it from others.
  • File system — organises storage into files and folders.
  • Device drivers — talk to hardware like printers, Wi-Fi and cameras.
  • User interface — a command line (shell) or a graphical desktop.
  • Security — users, permissions and passwords.

When your C program calls printf or fopen, the C library asks the operating system to do the actual work through a system call.

Software layers

BrowserVS CodeYour programsApplicationsKernelDriversOperating systemCompilers & toolsSystem softwareYou
Software sits in layers: applications rely on system software, which controls the hardware.

Chapter 2 · Computer Basics

Number Systems

Binary, octal, decimal and hexadecimal: place values, converting between any two bases, and why programmers use hex — with an interactive converter.

We count in decimal (base 10) because we have ten fingers. Computers use binary (base 2) because a transistor is either off (0) or on (1). Programmers also use octal (base 8) and hexadecimal (base 16) as compact ways to write binary.

System Base Digits Example C / Python literal
Binary 2 0 1 1011 0b1011
Octal 8 0–7 755 0755 (C), 0o755 (Python)
Decimal 10 0–9 255 255
Hexadecimal 16 0–9, A–F (A = 10 … F = 15) FF 0xFF

Place values

In base b, each position is worth a power of b, growing from right to left.

1011₂ = 1·2³ + 0·2² + 1·2¹ + 1·2⁰ = 8 + 0 + 2 + 1 = 11 2F₁₆ = 2·16¹ + 15·16⁰ = 32 + 15 = 47 157₈ = 1·8² + 5·8¹ + 7·8⁰ = 64 + 40 + 7 = 111

Decimal to any base: repeated division

Divide by the base, record the remainder, repeat with the quotient until it reaches 0, then read the remainders bottom to top.

Convert 45 to binary:

Divide Quotient Remainder
45 ÷ 2 22 1
22 ÷ 2 11 0
11 ÷ 2 5 1
5 ÷ 2 2 1
2 ÷ 2 1 0
1 ÷ 2 0 1

Reading upwards: 45 = 101101₂.

Try it

Binary ↔ octal and hexadecimal: grouping

Because 8 = 2³ and 16 = 2⁴, each octal digit is exactly 3 bits and each hex digit exactly 4 bits. Group bits from the right:

1101 0110 1010₂ → D 6 A → D6A₁₆ 110 101 101 010₂ → 6 5 5 2 → 6552₈

Hex Binary Hex Binary
0 0000 8 1000
1 0001 9 1001
2 0010 A 1010
3 0011 B 1011
4 0100 C 1100
5 0101 D 1101
6 0110 E 1110
7 0111 F 1111

That is why programmers love hex: one hex digit = 4 bits, two hex digits = one byte. Colours (#FF8800), memory addresses (0x7ffe…) and file signatures are all written in hex.

Fractions in binary

Positions after the point are negative powers: 0.101₂ = 1/2 + 0/4 + 1/8 = 0.625. To convert a decimal fraction, multiply by 2 repeatedly and take the integer parts: 0.625 → 1.25 (1) → 0.5 (0) → 1.0 (1) → 0.101₂. Some fractions never terminate in binary — 0.1 is 0.000110011…₂ — which is why 0.1 + 0.2 != 0.3 in every language.

Converting in code

C
#include <stdio.h>

void toBase(unsigned n, unsigned base) {
    const char *digits = "0123456789ABCDEF";
    char buf[40];
    int i = 0;
    if (n == 0) buf[i++] = '0';
    while (n > 0) { buf[i++] = digits[n % base]; n /= base; }   // remainders, last first
    while (i > 0) putchar(buf[--i]);                            // print them in reverse
}

int main(void) {
    unsigned n = 2026;
    printf("%u in decimal\n", n);
    printf("binary: "); toBase(n, 2); printf("\n");
    printf("octal:  %o\nhex:    %X\n", n, n);
    printf("base 5: "); toBase(n, 5); printf("\n");
    printf("0x7E2 = %d, 0b11111101010 = %d\n", 0x7E2, 0b11111101010);
    return 0;
}
Output
2026 in decimal
binary: 11111101010
octal:  3752
hex:    7EA
base 5: 31101
0x7E2 = 2018, 0b11111101010 = 2026
Python
n = 2026
print(bin(n), oct(n), hex(n))
print(int("11111101010", 2), int("3752", 8), int("7ea", 16), int("31101", 5))
print(f"{n:b} {n:o} {n:X} {n:#010b}")
Output
0b11111101010 0o3752 0x7ea
2026 2026 2026 2026
11111101010 3752 7EA 0b11111101010

Chapter 3 · Computer Basics

Data Representation

How computers store everything as bits: unsigned and signed integers, two's complement, overflow, floating point, characters with ASCII and Unicode, and images and sound.

Inside a computer, everything — numbers, text, images, music, your code — is a pattern of bits. The meaning depends on how the program interprets those bits.

Unsigned integers

With n bits you can store 2ⁿ patterns: unsigned values 0 to 2ⁿ − 1.

Bits Unsigned range
8 0 to 255
16 0 to 65,535
32 0 to about 4.29 billion
64 0 to about 1.8 × 10¹⁹

Signed integers: two's complement

To store negative numbers, computers use two's complement. The leftmost bit has a negative place value: in 8 bits it is worth −128.

To find the 8-bit pattern for −x: write x in binary, invert all the bits, then add 1.

5 = 0000 0101 → invert → 1111 1010 → add 1 → 1111 1011 = −5

Check: −128 + 64 + 32 + 16 + 8 + 2 + 1 = −5 ✓.

8-bit two's complement ranges from −128 to +127; in general, −2ⁿ⁻¹ to 2ⁿ⁻¹ − 1. Two's complement is used because addition works the same way for positive and negative numbers — the CPU needs only one adder circuit.

C
#include <stdio.h>

void bits8(signed char x) {
    for (int i = 7; i >= 0; i--) putchar((x >> i) & 1 ? '1' : '0');
}

int main(void) {
    signed char values[] = {5, -5, 127, -128, -1};
    for (int i = 0; i < 5; i++) {
        printf("%5d = ", values[i]);
        bits8(values[i]);
        printf("\n");
    }
    return 0;
}
Output
    5 = 00000101
   -5 = 11111011
  127 = 01111111
 -128 = 10000000
   -1 = 11111111

Overflow

When a result does not fit in the available bits, it wraps around:

C
#include <stdio.h>
#include <limits.h>

int main(void) {
    unsigned char u = 255;
    u = u + 1;                                   // 256 does not fit in 8 bits
    printf("255 + 1 in an unsigned char = %d\n", u);
    printf("INT_MAX = %d\n", INT_MAX);
    long long big = (long long)INT_MAX + 1;
    printf("INT_MAX + 1 as a long long = %lld\n", big);
    printf("(int)(INT_MAX + 1LL) = %d\n", (int)(INT_MAX + 1LL));   // wraps to INT_MIN
    return 0;
}
Output
255 + 1 in an unsigned char = 0
INT_MAX = 2147483647
INT_MAX + 1 as a long long = 2147483648
(int)(INT_MAX + 1LL) = -2147483648

The 2038 problem is an overflow waiting to happen: many systems store time as seconds since 1 January 1970 in a signed 32-bit integer, which runs out on 19 January 2038.

Floating point

Real numbers use IEEE 754 floating point — a binary version of scientific notation:

value = (−1)^sign × 1.mantissa × 2^(exponent − bias)

Type Bits Sign Exponent Mantissa Precision
float 32 1 8 23 about 7 decimal digits
double 64 1 11 52 about 15–16 decimal digits

Most decimal fractions cannot be stored exactly, so small errors creep in:

Python
print(0.1 + 0.2)
print(0.1 + 0.2 == 0.3)
print(abs((0.1 + 0.2) - 0.3) < 1e-9)          # compare with a tolerance instead
print(f"{0.1:.20f}")                          # what is really stored
print(1e308 * 10, -1e308 * 10)                 # overflow to infinity
total = 0.0
for _ in range(10):
    total += 0.1                               # tiny errors accumulate
print(total, total == 1.0)
Output
0.30000000000000004
False
True
0.10000000000000000555
inf -inf
0.9999999999999999 False

Characters

Text is stored as numbers too.

  • ASCII (1963) uses 7 bits for 128 characters: 'A' = 65, 'a' = 97, '0' = 48, space = 32, newline = 10.
  • Unicode assigns a code point to every character in every script — over 150,000 of them, including Devanagari, Tamil, emoji and ₹ (U+20B9).
  • UTF-8 encodes Unicode in 1 to 4 bytes, and is identical to ASCII for the first 128 characters. It is the encoding of the web.
Python
for ch in ["A", "a", "0", "₹", "अ", "😀"]:
    data = ch.encode("utf-8")
    print(f"{ch!r}: code point U+{ord(ch):04X} ({ord(ch)}), UTF-8 bytes = {data.hex(' ')} ({len(data)} byte{'s' if len(data) > 1 else ''})")
Output
'A': code point U+0041 (65), UTF-8 bytes = 41 (1 byte)
'a': code point U+0061 (97), UTF-8 bytes = 61 (1 byte)
'0': code point U+0030 (48), UTF-8 bytes = 30 (1 byte)
'₹': code point U+20B9 (8377), UTF-8 bytes = e2 82 b9 (3 bytes)
'अ': code point U+0905 (2309), UTF-8 bytes = e0 a4 85 (3 bytes)
'😀': code point U+1F600 (128512), UTF-8 bytes = f0 9f 98 80 (4 bytes)

Images and sound

  • An image is a grid of pixels; each pixel stores a colour, often as 3 bytes for red, green and blue (24-bit colour). A 1920 × 1080 photo has about 2 million pixels × 3 bytes ≈ 6 MB uncompressed — which is why JPEG and PNG compression matter.
  • Sound is sampled thousands of times per second: CD audio stores 44,100 samples per second, 16 bits each, per channel.

Chapter 4 · Computer Basics

Logic Gates & Circuits

The building blocks of hardware: AND, OR, NOT, NAND, NOR and XOR gates with truth tables, building circuits, the half adder and full adder, and how they add numbers.

A logic gate is a tiny electronic circuit (made of transistors) that takes one or more bits as input and produces a bit as output. Billions of them inside a CPU perform every calculation your programs do.

ANDORNOTNANDNORXORXNOR
The seven standard gates. A small circle (bubble) on the output means the result is inverted.

Truth tables

A B AND OR NAND NOR XOR XNOR
0 0 0 0 1 1 0 1
0 1 0 1 1 0 1 0
1 0 0 1 1 0 1 0
1 1 1 1 0 0 0 1

NOT has one input: NOT 0 = 1, NOT 1 = 0.

Gate Output is 1 when… Boolean expression
AND all inputs are 1 A · B
OR at least one input is 1 A + B
NOT the input is 0 A′
NAND not all inputs are 1 (A · B)′
NOR no input is 1 (A + B)′
XOR the inputs differ A ⊕ B
XNOR the inputs are equal (A ⊕ B)′

Building circuits

Connect gates and you get a circuit for any Boolean expression. Explore one:

That expression, (A AND NOT B) OR (NOT A AND B), is exactly XOR.

Adding binary numbers

Binary addition follows simple rules: 0 + 0 = 0, 0 + 1 = 1, 1 + 1 = 10 (0, carry 1), 1 + 1 + 1 = 11 (1, carry 1).

Text
    1 0 1 1   (11)
  + 0 1 1 1   ( 7)
  ---------
  1 0 0 1 0   (18)

Half adder

Adds two bits A and B:

  • Sum = A XOR B
  • Carry = A AND B

Full adder

Adds two bits plus a carry in, so adders can be chained for multi-bit numbers:

  • Sum = A XOR B XOR Cin
  • Carry out = (A AND B) OR (Cin AND (A XOR B))

Chain 32 or 64 full adders, each passing its carry to the next, and you have the adder inside a CPU's ALU — a ripple-carry adder:

Python
def full_adder(a, b, carry_in):
    s = a ^ b ^ carry_in
    carry_out = (a & b) | (carry_in & (a ^ b))
    return s, carry_out

def add_bits(x, y, width=8):
    carry, result = 0, 0
    for i in range(width):                       # from the least significant bit
        bit, carry = full_adder((x >> i) & 1, (y >> i) & 1, carry)
        result |= bit << i
    return result, carry

for x, y in [(11, 7), (100, 55), (200, 100)]:
    total, overflow = add_bits(x, y)
    print(f"{x:3} + {y:3} = {total:3}  (binary {x:08b} + {y:08b} = {total:08b}, carry out {overflow})")
Output
 11 +   7 =  18  (binary 00001011 + 00000111 = 00010010, carry out 0)
100 +  55 = 155  (binary 01100100 + 00110111 = 10011011, carry out 0)
200 + 100 =  44  (binary 11001000 + 01100100 = 00101100, carry out 1)

The last line shows overflow: 300 does not fit in 8 bits, so the result wraps to 44 and the carry-out bit is 1.

Beyond adders

  • Multiplexers select one of several inputs (the hardware version of switch).
  • Flip-flops use feedback between gates to remember a bit — the basis of registers and memory.
  • Combining adders, multiplexers and flip-flops with a clock gives you a CPU.

Chapter 5 · Problem Solving

Algorithms, Flowcharts & Pseudocode

Think before you code: computational thinking, writing step-by-step algorithms, drawing flowcharts with the standard symbols, and writing clear pseudocode.

Most programming mistakes happen before any code is typed: the plan was wrong or vague. Professional developers plan solutions first. This lesson gives you three tools for planning.

Computational thinking

Skill Meaning Example: "find the class topper"
Decomposition break a big problem into smaller ones read marks; compare; report
Pattern recognition spot similarities with problems you have solved "it's just finding a maximum"
Abstraction ignore details that do not matter names do not matter until the end
Algorithm design write precise steps that always work keep the best so far, update it

Algorithms

An algorithm is a finite, ordered list of unambiguous steps that solves a problem. A recipe is an algorithm for cooking.

Algorithm: find the largest of three numbers

  1. Start.
  2. Read A, B, C.
  3. If A ≥ B and A ≥ C, then LARGEST = A.
  4. Otherwise, if B ≥ C, then LARGEST = B.
  5. Otherwise, LARGEST = C.
  6. Print LARGEST.
  7. Stop.

A good algorithm is correct for every input (what if two numbers are equal?), finite, unambiguous and efficient.

Flowcharts

A flowchart draws an algorithm as connected shapes:

Symbol Shape Use
Terminal rounded rectangle (oval) Start / Stop
Input/Output parallelogram Read or print data
Process rectangle a calculation or assignment
Decision diamond a yes/no question, two exits
Flow line arrow the order of steps
Connector small circle joins parts of a long chart
StartRead a number nn % 2 == 0 ?YesPrint "Even"NoPrint "Odd"Stop
Flowchart for checking whether a number is even or odd.

Loops appear as an arrow going back to an earlier step:

Startsum = 0, i = 1i <= n ?Yessum = sum + i, then i = i + 1NoPrint sumStop
Flowchart for the sum 1 + 2 + … + n. The "Yes" branch loops back to the condition.

Pseudocode

Pseudocode writes an algorithm in structured, code-like English — precise like code, but free of any one language's syntax.

Pseudocode
ALGORITHM SumOfDigits
    INPUT n
    sum ← 0
    WHILE n > 0 DO
        digit ← n MOD 10
        sum ← sum + digit
        n ← n DIV 10
    END WHILE
    OUTPUT sum
END

Common conventions: ← for assignment, IF … THEN … ELSE … END IF, FOR i ← 1 TO n DO … END FOR, WHILE … DO … END WHILE, INPUT and OUTPUT, and indentation to show blocks.

From plan to program

The pseudocode translates almost line by line into any language:

C
#include <stdio.h>

int main(void) {
    int n, sum = 0;
    printf("Enter a number: ");
    scanf("%d", &n);
    while (n > 0) {
        int digit = n % 10;
        sum = sum + digit;
        n = n / 10;
    }
    printf("Sum of digits = %d\n", sum);
    return 0;
}
Output
Enter a number: 40213
Sum of digits = 10
Sample input is includedTry it Yourself
Python
n = int(input("Enter a number: "))
total = 0
while n > 0:
    total += n % 10
    n //= 10
print("Sum of digits =", total)
Output
Enter a number: 40213
Sum of digits = 10
Sample input is includedTry it Yourself

Dry runs

Before running code, trace it by hand with a table of variables — the single best debugging habit:

Step n digit sum
start 40213 – 0
1 4021 3 3
2 402 1 4
3 40 2 6
4 4 0 6
5 0 4 10

Chapter 6 · Problem Solving

From Code to Running Program

How source code becomes a running program: compilers vs interpreters, the build steps, IDEs and editors, and the three kinds of errors — syntax, runtime and logical — with debugging strategies.

Programming languages

Computers only execute machine code — binary instructions specific to a CPU. Programmers write in high-level languages like C, Python and Java that are readable by humans, and a translator converts them.

Level Example Who reads it
Machine code 10110000 01100001 the CPU
Assembly mov al, 0x61 low-level programmers
High-level x = 97 everyone

Compilers vs interpreters

Compiler Interpreter
Translates the whole program before it runs one statement at a time while running
Output a standalone executable file no separate file
Errors all syntax errors reported before running reported when the line is reached
Speed the program runs fast slower
Examples C, C++, Rust, Go Python, JavaScript (with JIT compilers today), Ruby

Java and Python actually do both: they compile to an intermediate bytecode, which a virtual machine then runs.

The C build pipeline

Terminal
gcc -E hello.c -o hello.i     # 1. preprocess: expand #include and #define
gcc -S hello.i -o hello.s     # 2. compile: C to assembly
gcc -c hello.s -o hello.o     # 3. assemble: assembly to machine code (object file)
gcc hello.o -o hello          # 4. link: add library code (printf) into an executable
./hello                       # 5. load and run

Normally one command does it all: gcc hello.c -o hello. See C Introduction for the diagram.

Editors and IDEs

  • A text editor (VS Code, Sublime, Vim) edits code; extensions add colours, suggestions and error checks.
  • An IDE (integrated development environment) bundles an editor, compiler, debugger and project tools: CLion and Visual Studio for C/C++, PyCharm for Python, IntelliJ for Java.
  • Online compilers (like this site's Compiler) need nothing installed.

The three kinds of errors

1. Syntax errors

The code breaks the language's grammar, so it will not compile (or start). The compiler tells you the line.

C
int main(void) {
    printf("Hello")      // missing semicolon -> error: expected ';'
    return 0;
}

2. Runtime errors

The program compiles but crashes or misbehaves while running: dividing by zero, reading past an array, opening a missing file, running out of memory.

Python
marks = [78, 85, 92]
total = 0
for i in range(4):          # one too many
    total += marks[i]
print(total)
Output
Traceback (most recent call last):
  File "main.py", line 4, in <module>
    total += marks[i]
             ~~~~~^^^
IndexError: list index out of range

3. Logical errors

The program runs and finishes, but gives the wrong answer. No error message appears — these are the hardest to find.

Python
marks = [78, 85, 92]
average = sum(marks) / 2       # bug: should divide by len(marks)
print("Average:", average)
Output
Average: 127.5
Error type When found Who finds it Example
Syntax compile time the compiler missing ; or :
Runtime while running a crash or exception divide by zero
Logical after checking the output you, by testing wrong formula

Debugging strategies

  1. Read the error message from the top — it names the file, line and problem.
  2. Reproduce the bug with the smallest input that triggers it.
  3. Print values at key points (printf / print debugging).
  4. Use a debugger: set breakpoints, step line by line, watch variables (gdb, VS Code debugger).
  5. Rubber-duck: explain the code line by line to someone (or a rubber duck). Often you spot the bug while explaining.
  6. Check edge cases: 0, 1, negative numbers, empty input, the largest input.

Chapter 7 · Developer Tools

The Linux Command Line

Work like a developer in the terminal: the file system tree, navigating and managing files, viewing and searching text, permissions, pipes and redirection, processes and compiling code.

Servers, cloud machines, Raspberry Pis and most developer tools run Linux, and they are driven from the command line (also called the terminal or shell). It is faster than clicking once you know a few dozen commands — and in internships you will be expected to use it.

The program that reads your commands is the shell (usually bash or zsh). On Windows, install WSL (Windows Subsystem for Linux) to get a real Linux shell; macOS already has a Unix shell.

The file system

Linux organises everything in one tree starting at the root, /:

projectsnotes.txtashahomeetcbinusrtmp/
Part of a Linux directory tree. Asha's home folder is /home/asha, also written ~.
Path Meaning
/ the root of the whole tree
~ your home folder, e.g. /home/asha
. the current folder
.. the parent folder
/home/asha/notes.txt an absolute path (starts at /)
projects/lab1.c a relative path (starts at the current folder)

Navigating

Terminal
pwd                     # print working directory: where am I?
ls                      # list files
ls -la                  # long format, including hidden files (names starting with .)
cd projects             # change into a folder
cd ..                   # go up one level
cd ~                    # go home (plain `cd` does the same)
cd -                    # go back to the previous folder

Managing files and folders

Terminal
mkdir lab1                      # make a folder
mkdir -p cse101/week2/day3      # make nested folders at once
touch main.c                    # create an empty file
cp main.c backup.c              # copy
cp -r lab1 lab1-backup          # copy a folder recursively
mv backup.c old/                # move into a folder
mv draft.txt final.txt          # rename
rm old.txt                      # delete a file (no recycle bin!)
rm -r lab1-backup               # delete a folder and everything inside

Viewing and searching text

Terminal
cat notes.txt                   # print a whole file
less big.log                    # scroll through a long file (q to quit)
head -n 5 data.csv              # first 5 lines
tail -n 20 server.log           # last 20 lines
tail -f server.log              # follow a growing file live
wc -l *.c                       # count lines in every .c file
grep "main" *.c                 # find lines containing "main"
grep -rn "TODO" src/            # search recursively, with line numbers
find . -name "*.py"             # find files by name

Pipes and redirection

Linux commands are small tools that you combine:

Symbol Meaning Example
> write output to a file (overwrite) ls > files.txt
>> append output to a file echo "done" >> log.txt
< read input from a file ./a.out < input.txt
| pipe one command's output into the next cat log.txt | grep ERROR | wc -l
Terminal
history | grep gcc | tail -n 3          # my last 3 gcc commands
ls -l | sort -k5 -n | tail -n 1          # the largest file in this folder
./marks < test1.txt > result1.txt       # test a program with saved input

Permissions

ls -l shows a permission string like -rwxr-xr--: the file type, then read/write/execute for the owner, the group and others.

Terminal
chmod +x script.sh              # make a script executable
chmod 644 notes.txt             # rw- r-- r-- (6 = 4+2, 4 = read)
sudo apt install gcc            # run one command as the administrator (root)
Digit Permissions
7 rwx (4 + 2 + 1)
6 rw-
5 r-x
4 r--

Processes

Terminal
ps aux | grep python            # list running processes
top                             # live view of CPU and memory use (q to quit)
kill 4321                       # stop process 4321
./server &                      # run in the background
Ctrl+C                          # stop the program running in the terminal

Compiling and running from the terminal

Terminal
gcc -Wall -o hello hello.c && ./hello          # C: compile, then run only if it compiled
g++ -std=c++17 -o app main.cpp && ./app         # C++
python3 script.py                               # Python
./hello < input.txt                             # feed input from a file

Command cheat sheet

Task Command
Where am I / what's here pwd, ls -la
Move around cd folder, cd .., cd ~
Create mkdir, touch
Copy / move / delete cp, mv, rm (-r for folders)
Read files cat, less, head, tail
Search grep, find
Help man ls, ls --help
Install software (Ubuntu) sudo apt install name
Download curl -O url, wget url

Chapter 8 · Developer Tools

Git & GitHub

Version control for every project: repositories, the staging area, commits, history, branches and merging, and sharing work on GitHub with push, pull, clones and pull requests.

Git is a version control system: it records snapshots of your project over time so you can see what changed, go back to any earlier version, and work with others without overwriting each other's work. GitHub is a website that hosts Git repositories online — and doubles as your public developer portfolio.

Why version control?

  • Never lose work — every commit is a restore point.
  • Understand history — who changed what, when, and why.
  • Experiment safely — try ideas on a branch; throw them away if they fail.
  • Collaborate — many people work on one codebase in parallel.

The three areas

Area What lives there
Working directory the files you are editing right now
Staging area (index) changes you have marked for the next commit
Repository (.git folder) the permanent history of commits
Edit files in the working directorygit add — stage the changes you wantgit commit — save a snapshot with a messagegit push — upload commits to GitHubTeammates git pull to get them
The everyday Git workflow.

First-time setup

Terminal
git config --global user.name "Asha Rao"
git config --global user.email "asha@example.com"
git config --global init.defaultBranch main

Starting and saving work

Terminal
git init                          # turn the current folder into a repository
git status                        # what changed? what is staged?
git add main.c                    # stage one file
git add .                         # stage everything in this folder
git commit -m "Add linked list insert and delete"
git log --oneline                 # history, one line per commit
git diff                          # unstaged changes, line by line

.gitignore

List files Git should never track — compiled programs, secrets, editor clutter:

Text
# .gitignore
a.out
*.o
*.exe
__pycache__/
.env
node_modules/
.vscode/

Undoing things

Terminal
git restore main.c                # discard unstaged edits to a file
git restore --staged main.c       # unstage, keeping the edits
git commit --amend                # fix the last commit's message or contents
git revert a1b2c3d                # make a new commit that undoes an old one
git checkout a1b2c3d -- notes.txt # bring back an old version of one file

Branches

A branch is an independent line of development. main holds working code; you create a branch for each feature or fix, then merge it back.

Terminal
git branch                        # list branches
git switch -c feature/stack       # create and switch to a new branch
# ... edit and commit on the branch ...
git switch main                   # go back to main
git merge feature/stack           # bring the branch's commits into main
git branch -d feature/stack       # delete the merged branch

If both branches changed the same lines, Git reports a merge conflict and marks the file:

Text
<<<<<<< HEAD
printf("Hello\n");
=======
printf("Hello, world!\n");
>>>>>>> feature/greeting

Edit the file to keep the right version, delete the markers, then git add and git commit.

Working with GitHub

Terminal
git clone https://github.com/user/repo.git      # download a repository
git remote add origin https://github.com/you/project.git
git push -u origin main                          # upload your commits (first time)
git push                                         # later pushes
git pull                                         # fetch and merge others' changes

Pull requests (PRs): on GitHub, push your branch, then open a pull request asking to merge it into main. Teammates review the changes and comment before merging — the standard workflow in every software company.

Forks: copy someone else's repository to your account, change it, then open a PR back to the original — how open-source contributions work.

Command Purpose
git init / git clone start a repository / copy one
git status, git diff, git log inspect
git add, git commit save a snapshot
git switch -c, git merge branch and merge
git push, git pull sync with GitHub
git restore, git revert undo

Chapter 9 · The Web

How the Internet & Web Work

What happens when you open a website: clients and servers, IP addresses, DNS, TCP and packets, HTTP requests and responses, status codes, HTTPS, and front end vs back end.

The Internet is a global network of networks — billions of devices connected by cables, fibre, Wi-Fi and cell towers, all speaking common protocols (agreed rules). The World Wide Web, invented by Tim Berners-Lee in 1989, is one service that runs on top of the Internet: web pages linked together and fetched with HTTP. Email, video calls and online games are other services on the same Internet.

Clients and servers

  • A client requests something — your browser or a mobile app.
  • A server is a computer that waits for requests and responds — with a web page, an image, or data.

Addresses: IP and DNS

Every device on the Internet has an IP address:

  • IPv4: four numbers 0–255, e.g. 142.250.193.78 (about 4.3 billion addresses — not enough).
  • IPv6: eight groups of hex, e.g. 2404:6800:4007:81a::200e.

Humans prefer names. The Domain Name System (DNS) is the Internet's phone book: it translates a name such as www.example.com into an IP address, asking a hierarchy of DNS servers (root → .com → example.com) and caching the answer.

Packets, TCP and routing

Data travels in small packets. Each packet carries the source and destination IP addresses and is forwarded hop by hop by routers. Packets of one message may take different routes.

  • IP delivers packets on a best-effort basis.
  • TCP sits on top: it numbers packets, re-sends lost ones and reassembles them in order — a reliable stream. (UDP skips that for speed — video calls, games.)

What happens when you visit a website

You type https://example.com and press EnterDNS lookup: example.com → 93.184.215.14TCP connection + TLS handshake (HTTPS encryption)Browser sends an HTTP request: GET /Server responds: 200 OK + HTMLBrowser parses HTML, fetches CSS, JS and imagesPage is rendered and becomes interactive
The journey of one page load, usually completed in well under a second.

HTTP: requests and responses

HTTP (HyperText Transfer Protocol) is a simple text conversation:

Text
GET /courses/c HTTP/1.1
Host: example.com
User-Agent: Mozilla/5.0
Accept: text/html
Text
HTTP/1.1 200 OK
Content-Type: text/html; charset=utf-8
Content-Length: 1532

<!doctype html>
<html> ... </html>
Method Meaning
GET read a resource
POST create something / submit a form
PUT / PATCH update
DELETE delete
Status code Meaning
200 OK success
301 / 302 moved — redirect
400 Bad Request the request was malformed
401 / 403 not logged in / not allowed
404 Not Found no such resource
500 Internal Server Error the server crashed

HTTPS is HTTP inside an encrypted TLS connection, so nobody between you and the server can read or alter the traffic — that is what the padlock in the address bar means.

URLs

https://shop.example.com:443/search?q=keyboard&page=2#reviews

Part Value
Scheme https
Host (domain) shop.example.com
Port 443 (the default for HTTPS)
Path /search
Query string q=keyboard&page=2
Fragment #reviews (handled by the browser only)
JavaScript
const url = new URL("https://shop.example.com:443/search?q=keyboard&page=2#reviews");
console.log(url.protocol, url.hostname, url.pathname);
console.log("q =", url.searchParams.get("q"), "| page =", url.searchParams.get("page"));
console.log("fragment:", url.hash);
Output
https: shop.example.com /search
q = keyboard | page = 2
fragment: #reviews

Front end and back end

Front end (client side) Back end (server side)
Runs in the browser a server
Languages HTML, CSS, JavaScript JavaScript (Node.js), Python, Java, Go, C# …
Job layout, styling, interaction data, logic, authentication, databases
Talks via HTTP requests to APIs (often JSON) HTTP responses

A full-stack developer works on both.

Chapter 10 · The Web

HTML & CSS Essentials

Build and style a web page: HTML document structure, common elements, links, images, lists, tables and forms, then CSS selectors, the box model, colours, fonts and Flexbox — with a live editor.

Every web page is built from three languages:

Language Role Analogy
HTML structure and content the skeleton
CSS presentation and layout the clothes
JavaScript behaviour and interaction the muscles

HTML: structure

HTML marks up content with elements, written as tags: <p>A paragraph</p>. Tags can have attributes: <a href="https://example.com">a link</a>.

HTML
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>My first page</title>
</head>
<body>
  <h1>Hello, I'm Asha</h1>
  <p>I study <strong>computer science</strong> at Kalvium.</p>
  <a href="https://github.com">My GitHub</a>
</body>
</html>
  • <head> holds information about the page (title, character set, CSS links).
  • <body> holds what is shown.

Common elements

Element Purpose
<h1> … <h6> headings, from most to least important
<p> paragraph
<a href="…"> link
<img src="…" alt="…"> image (the alt text is read by screen readers)
<ul>, <ol>, <li> bulleted list, numbered list, list item
<table>, <tr>, <th>, <td> table, row, header cell, data cell
<form>, <input>, <button>, <label> forms
<div>, <span> generic block and inline containers
<header>, <nav>, <main>, <section>, <footer> semantic layout regions

Semantic elements tell browsers, search engines and screen readers what each part means — prefer them to plain <div>s.

CSS: style

CSS rules have a selector and declarations:

CSS
h1 {
  color: #2e8b47;
  font-size: 2rem;
}
.card {                 /* class selector: <div class="card"> */
  padding: 16px;
  border-radius: 12px;
}
#signup { }             /* id selector: <form id="signup"> */
nav a:hover { }         /* descendant + state */
Selector Matches
p every <p>
.card elements with class="card"
#main the element with id="main"
nav a <a> elements inside <nav>
a:hover links under the mouse pointer

When rules conflict, the more specific selector wins (id > class > element), and later rules beat earlier ones of equal specificity — the cascade.

The box model

Every element is a box: content, surrounded by padding, then a border, then margin (space outside).

CSS
.box {
  width: 200px;
  padding: 16px;          /* inside the border */
  border: 2px solid #333;
  margin: 24px auto;      /* outside; auto centres horizontally */
  box-sizing: border-box; /* width now includes padding and border */
}

Flexbox layout

Flexbox arranges children in a row or column with easy alignment and spacing:

CSS
.row {
  display: flex;
  gap: 12px;
  justify-content: space-between;   /* along the main axis */
  align-items: center;              /* across it */
  flex-wrap: wrap;
}

Try it: a live editor

Edit the HTML and CSS — the preview updates as you type:

Responsive design

Phones, tablets and laptops need different layouts. Two essentials:

HTML
<meta name="viewport" content="width=device-width, initial-scale=1">
CSS
@media (max-width: 600px) {
  .row { flex-direction: column; }   /* stack on small screens */
}

Chapter 11 · The Web

JavaScript Essentials

The language of the web: variables, types, functions, arrays and objects, loops, and making pages interactive with the DOM and events — with runnable examples.

JavaScript (JS) is the programming language every web browser runs. It makes pages interactive — buttons, form validation, live updates — and with Node.js it also runs on servers. Despite the name, it is unrelated to Java.

Variables and types

JavaScript
let name = "Asha";        // can be reassigned
const year = 2026;        // cannot be reassigned
let cgpa = 9.1;
let enrolled = true;
let nothing = null;
let notSet;               // undefined

console.log(typeof name, typeof year, typeof enrolled, typeof notSet);
console.log(`${name} joined in ${year} with a CGPA of ${cgpa}`);   // template literal
Output
string number boolean undefined
Asha joined in 2026 with a CGPA of 9.1

Use const by default and let when the value changes. Avoid the old var.

JavaScript
console.log("5" == 5, "5" === 5);
console.log(0 == "", 0 === "");
console.log(0.1 + 0.2);                  // the same floating-point behaviour as C and Python
console.log("3" + 4, "3" * 4);           // + joins strings; * converts to numbers
Output
true false
true false
0.30000000000000004
34 12

Functions

JavaScript
function area(length, width = length) {        // default parameter
  return length * width;
}
const square = x => x * x;                       // arrow function
const greet = (name) => `Hello, ${name}!`;

console.log(area(4, 5), area(3), square(9), greet("Ravi"));
Output
20 9 81 Hello, Ravi!

Arrays and objects

JavaScript
const marks = [78, 92, 65, 88];
marks.push(71);
const total = marks.reduce((sum, m) => sum + m, 0);
const passed = marks.filter(m => m >= 70);
const curved = marks.map(m => Math.min(100, m + 5));
console.log(marks.length, total, passed, curved);
console.log([...marks].sort((a, b) => a - b));   // numeric sort needs a compare function

const student = { name: "Meera", roll: 12, skills: ["C", "JS"] };
student.city = "Hyderabad";
console.log(student.name, student["roll"], student.skills.join(", "));
console.log(JSON.stringify(student));
for (const [key, value] of Object.entries(student)) console.log(`  ${key}: ${value}`);
Output
5 394 [ 78, 92, 88, 71 ] [ 83, 97, 70, 93, 76 ]
[ 65, 71, 78, 88, 92 ]
Meera 12 C, JS
{"name":"Meera","roll":12,"skills":["C","JS"],"city":"Hyderabad"}
  name: Meera
  roll: 12
  skills: C,JS
  city: Hyderabad

Control flow

JavaScript
for (let i = 1; i <= 15; i++) {
  if (i % 15 === 0) console.log("FizzBuzz");
  else if (i % 3 === 0) console.log("Fizz");
  else if (i % 5 === 0) console.log("Buzz");
  else console.log(i);
}
Output
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz

if/else, for, while, switch, break and continue work just like in C.

The DOM: making pages interactive

In the browser, JavaScript sees the page as a tree of objects — the Document Object Model (DOM). You can select elements, change them and react to events:

HTML
<button id="like">♥ Like</button>
<p id="count">0 likes</p>

<script>
  const button = document.querySelector("#like");
  const count = document.querySelector("#count");
  let likes = 0;
  button.addEventListener("click", () => {
    likes++;
    count.textContent = `${likes} like${likes === 1 ? "" : "s"}`;
  });
</script>

Try it — click the button, then change the code:

DOM task Code
Select one element document.querySelector(".card")
Select many document.querySelectorAll("li")
Change text el.textContent = "Hi"
Change a style el.style.color = "red" or el.classList.add("active")
React to events el.addEventListener("click", handler)
Create elements document.createElement("li") + parent.append(li)

Fetching data

Web apps load data from APIs without reloading the page:

JavaScript
const response = await fetch("https://api.github.com/users/octocat");
const user = await response.json();
console.log(user.name, user.public_repos);

await waits for the network without freezing the page — JavaScript is asynchronous.

Where to go next

JavaScript is the gateway to full-stack development: React for user interfaces, Node.js and Express for servers, and TypeScript for typed JavaScript in large projects.