DEV Community

Cover image for CS—Explained in a blog
Rohan Taneja
Rohan Taneja

Posted on

CS—Explained in a blog

Just as I promised in the title, this is a single blog that I planned to write and explain everything that I've learned about CS until now. Without much jargon, let's dive right into it.

CPU—The brain box

Every computer starts with a CPU—a tiny piece of silicon filled with billions of transistors. These transistors act like switches, flipping between on (1) and off (0). When you combine these switches, you create binary code—the fundamental language of computers.

Imagine a transistor as a simple LED:

if (voltage > threshold) {
    LED = ON;  // 1
} else {
    LED = OFF; // 0
}
Enter fullscreen mode Exit fullscreen mode

This is the simplest form of binary logic. Multiply that by billions, and you have a CPU crunching numbers at gigahertz speeds.

Binary logic

Bits, Bytes, and Binary

A bit is the smallest unit of data—a 0 or a 1. When you group eight bits together, you get a byte. For example, the binary number 01000001 equals 65 in decimal, which is the ASCII code for the uppercase letter 'A'.
Here’s a quick Python snippet:

# Convert binary to integer
binary_value = '01000001'
integer_value = int(binary_value, 2)
print(integer_value)  # Output: 65

# Convert integer to character
char_value = chr(integer_value)
print(char_value)  # Output: A

Enter fullscreen mode Exit fullscreen mode

For easier reading, we often use hexadecimal. Four binary bits map directly to one hex digit. For example, the byte above is 0x41 in hexadecimal.

Binary logic

Logic Gates

Logic gates form the foundation of computation. Consider the AND gate, which only outputs true if both inputs are true:

// Pseudo-code for an AND gate
bool andGate(bool a, bool b) {
    return a && b;
}

Enter fullscreen mode Exit fullscreen mode

For instance, if both a and b are 1:

andGate(1, 1)  // returns 1 (true)

Enter fullscreen mode Exit fullscreen mode

This basic logic is expanded across millions of gates in a CPU, enabling everything from arithmetic to complex decision-making.

Logic gates ft. Drake

OS and Character Encoding

When you press a key, the operating system translates that physical action into digital information. For example, the ASCII code for 'A' is 65, stored as 01000001 in binary.
Here’s a simple C example:

#include <stdio.h>

int main() {
    char c = 'A';
    printf("ASCII value of %c is %d\n", c, c);
    return 0;
}

Enter fullscreen mode Exit fullscreen mode

The OS (be it Windows, Linux, or macOS) manages these translations, handling everything from input devices to file systems.

RAM and Machine Cycles

The CPU is powerful, but it needs fast, temporary storage—this is where RAM comes in. Think of RAM as a whiteboard where the CPU writes data temporarily.
A simple machine cycle involves:

  1. Fetch: Retrieve the next instruction from memory.
  2. Decode: Translate the instruction into signals.
  3. Execute: Perform the operation.
  4. Store: Write the result back to memory. Here’s a pseudo-code example of a loop simulating a simple cycle:
while (instruction != STOP) {
    instruction = fetch(memory, programCounter);
    decoded = decode(instruction);
    result = execute(decoded);
    store(memory, programCounter, result);
    programCounter++;
}

Enter fullscreen mode Exit fullscreen mode

Modern CPUs run billions of these cycles per second, and multiple cores mean several processes run concurrently.

How machines work

Translating Human Ideas to Machine Actions

We never write binary by hand. Programming languages like Python, C, and Go let us express ideas in human-readable form. For example, a simple loop in Python:

for i in range(5):
    print(f"Loop iteration {i}")

Enter fullscreen mode Exit fullscreen mode

The interpreter or compiler then translates this into machine code the CPU can execute. This abstraction lets us focus on solving problems rather than managing every transistor.

Code to Machine

Data Structures

Data structures are essential for managing and retrieving data. Let’s look at a few examples:

Arrays:
Contiguous blocks of memory. In C:

int arr[5] = {1, 2, 3, 4, 5};
printf("%d", arr[2]);  // Output: 3

Enter fullscreen mode Exit fullscreen mode

Linked Lists:
Nodes connected by pointers:

struct Node {
    int data;
    struct Node* next;
};

Enter fullscreen mode Exit fullscreen mode

Hash Maps:
Key-value pairs for fast lookup. In Python:

phone_book = {"Alice": "555-1234", "Bob": "555-5678"}
print(phone_book["Alice"])  # Output: 555-1234

Enter fullscreen mode Exit fullscreen mode

These structures help optimize data access, making programs more efficient.

Step-by-Step Problem Solving with Algorithms

Algorithms are a recipe for solving problems. Consider binary search on a sorted array:

def binary_search(arr, target):
    low = 0
    high = len(arr) - 1
    while low <= high:
        mid = (low + high) // 2
        if arr[mid] == target:
            return mid
        elif arr[mid] < target:
            low = mid + 1
        else:
            high = mid - 1
    return -1

Enter fullscreen mode Exit fullscreen mode

This algorithm runs in O(log n) time, making it much faster than a linear search for large datasets. I keep a keen eye on Big O notation to evaluate performance, whether I'm dealing with recursion or iterative solutions.

Binary tree meme

Object-Oriented Programming

OOP helps in structuring code with classes and objects. Here’s a simple example in Python:

class Dog:
    def __init__(self, name):
        self.name = name

    def bark(self):
        print(f"{self.name} says woof!")

dog1 = Dog("Rex")
dog1.bark()  # Output: Rex says woof!

Enter fullscreen mode Exit fullscreen mode

This method of organizing code lets me reuse and extend functionality easily, using concepts like inheritance and polymorphism.

Machine Learning

Sometimes, we need computers to learn from data instead of following strict instructions. Machine learning involves training models on large datasets. For instance, a simple neural network might adjust weights based on input data to classify images:

# Pseudo-code for a single training iteration in a neural network
predicted = model.forward(input_data)
loss = compute_loss(predicted, target)
model.backward(loss)
model.update_weights()

Enter fullscreen mode Exit fullscreen mode

This iterative process helps the model improve over time. I find it fascinating to see how computers can learn to recognize patterns without explicitly programmed rules.
AI Daddy

The Internet and Databases

When you type a URL, a series of protocols kicks in to fetch the web page. Your browser sends an HTTP request over the TCP/IP network, and the server responds with HTML, CSS, and JavaScript. Databases store the underlying data. Consider a SQL query that retrieves user details:

SELECT username, email FROM users WHERE id = 1;

Enter fullscreen mode Exit fullscreen mode

Proper input sanitization is crucial here to prevent SQL injection attacks. The internet and databases work together to bring content to your screen, connecting data across the globe.

Every day, I’m learning more and tweaking my understanding, so I can not only be a better DevRel but also share these insights with you in a fun and digestible way. Whether you’re a seasoned developer or just starting out, I hope this helps make computer science a bit more approachable and a lot less intimidating.

Feel free to share your thoughts, ask questions, or drop a comment below. Let’s keep coding smart and learning every day!

Before I sign off, here's another meme—I really like this one xD

My Fav meme on ML/AI

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs