TECHNOLOGY 

Published on

KembaraXtra-Computer Science - The Internet Protocol Suite

Overview

The internet protocol suite standardizes communication on the internet.

Key protocols: Transmission Control Protocol (TCP) and Internet Protocol (IP), collectively known as TCP/IP.

Network protocols operate in a layered model called a network stack.

Layered Model (TCP/IP Model)

Four-layer model (TCP/IP model):

  • Link
  • Internet
  • Transport
  • Application

Protocols at each layer interact with adjacent layers only (encapsulation).

Each layer has specific responsibilities handled by protocols within that layer.

OSI Model

Another network model with seven layers.

Less relevant as the internet is based on the TCP/IP model.

Table of Layers and Protocols

Layer Description Example Protocols
Application Provides application-specific functionality (e.g., email, web pages). Structures data for process-to-process communication. HTTP, SSH
Transport Provides a communication channel for applications to send and receive data between hosts. TCP, UDP
Internet Enables communication across networks. Responsible for host addressing and routing data across the internet. IP
Link Enables communication on a local network. Closely associated with networking hardware (e.g., Wi-Fi). Ethernet, Wi-Fi

Data Transmission Flow

Outgoing Transmission: Travels down the network layers (Application → Transport → Internet → Link).

Incoming Transmission: Travels up the network layers (Link → Internet → Transport → Application).

Network hosts (clients, servers) use all four layers.

Networking hardware (switches, routers) often use only lower layers.

Detailed Layer Breakdown

1. Link Layer

Connects devices on the same local network.

Uses Media Access Control (MAC) addresses to uniquely identify devices.

Data is divided into frames (header, payload, footer).

Frame Header: Contains source and destination MAC addresses, data type descriptor.

Payload: Contains the data being transmitted.

Frame Footer: Used for error detection.

Examples:

  • Wi-Fi (IEEE 802.11): Wireless communication.
  • Ethernet (IEEE 802.3): Wired communication using RJ45 connectors.

Networking devices:

  • Hub: Retransmits frames to all ports.
  • Switch: Examines MAC addresses and sends frames to the correct port.

2. Internet Layer

Allows data to travel beyond the local network (routing).

Uses Internet Protocol (IP) for addressing and routing.

Every host has an IP address.

Data is sent in packets (enclosed in a link layer frame).

IP Packet Header: Contains source and destination IP addresses, IP version, header length.

Data Section: Payload.

IP Versions:

  • IPv4: 32-bit addresses (dominant). Displayed in dotted decimal notation (e.g., 192.168.1.23).
  • IPv6: 128-bit addresses.

Subnets:

  • Devices on the same local network have IP addresses with the same leading bits.
  • Devices on different subnets communicate through a router.
  • IP address divided into: network prefix (shared by subnet) and host identifier (unique to host).
  • CIDR Notation: IP address/prefix length (e.g., 192.168.1.23/24).
  • Subnet Mask: 32-bit number indicating the network prefix (e.g., 255.255.255.0 for a 24-bit prefix).
  • Network ID: Result of a bitwise AND between an IP address and subnet mask. Identifies the subnet.
  • To determine if two computers are on the same subnet: perform a bitwise AND on both IPs with the subnet mask. If the result is the same, they are on the same subnet.
  • Range of usable addresses: First and last address are reserved; others can be used by hosts.

3. Transport Layer

Provides a communication channel for applications.

Protocols:

  • TCP (Transmission Control Protocol): Reliable, connection-oriented. Data is sent in segments.
  • UDP (User Datagram Protocol): Unreliable, "best effort." Data is sent in datagrams.

TCP segment fits within an IP packet's data section.

Network Port Numbers: Identify specific services/processes on a host.

  • Well-known ports: 0–1023
  • Registered ports: 1024–49151
  • Dynamic ports: 49152+

Servers listen on well-known ports. Clients use ephemeral ports.

Socket: An IP address plus a port number. Represents a network endpoint.

4. Application Layer

Focuses on specific application tasks.

Examples:

  • HTTP (web content)
  • SMTP (email)
  • FTP (file transfer)

Application data is contained in the transport layer segment's data section.

Frame Structure

A frame contains:

  • Link layer header and footer
  • IP packet (header and data)
  • TCP segment (header and data)
  • Application data

Transmission Process Summary

Sending: Application data → Segment → Packet → Frame

Receiving: Frame → Packet → Segment → Application data

Picture
Published on
KembaraXtra-Computer Science - A Trip Through the Internet
Overview
This guide summarizes the journey of data across the internet using the TCP/IP model, illustrating how different devices interact at each layer.
Scenario
  • A client device (connected to Wi-Fi) wants to access a web page hosted on a server (connected via wired connection).
  • The client knows the server's IP address.
Step-by-Step Data Transmission
  1. Application Layer (Client):
    • The web browser creates an HTTP request.
    • The browser hands off the HTTP request to the OS's TCP/IP stack.
  2. Transport Layer (Client):
    • The TCP layer encapsulates the HTTP payload into a TCP segment.
    • It sets the destination port to 80 (standard for HTTP) in the segment header.
    • If the data is too large, TCP divides it into multiple segments.
  3. Internet Layer (Client):
    • The IP layer wraps the TCP segment in an IP packet.
    • The packet header includes the destination IP address of the server.
    • If necessary, IP divides the packet into smaller fragments.
  4. Link Layer (Client):
    • The IP packet is encapsulated in a frame.
    • The frame header includes the MAC address of the local router.
    • The client's Wi-Fi hardware transmits the frame wirelessly.
  5. Wireless Access Point:
    • Receives the frame.
    • Sends the frame to the router (operates at the link layer).
  6. Router(s):
    • Examines the IP packet to determine the destination IP address.
    • Encapsulates the packet in a new frame with the MAC address of the next router.
    • Sends the new frame on its way.
    • This routing process continues through multiple routers.
  7. Final Router (Server's Subnet):
    • Encapsulates the packet in a frame suitable for the server's local network.
    • The frame header includes the MAC address of the server.
  8. Switch (Server's Subnet):
    • Looks at the MAC address in the frame.
    • Forwards the frame out the appropriate physical port to the server.
    • Doesn't need to look at higher layers.
  9. Server:
    • Receives the frame.
    • The network interface driver passes the TCP/IP packet up to the TCP/IP stack.
    • The TCP/IP stack hands off the HTTP data to the process listening on TCP port 80.
    • The web server software (listening on port 80) handles the request.
  10. Reverse Process (Server to Client):
    • The server replies to the client, and the entire process happens again in reverse order.
Key Concepts
  • Encapsulation: Each layer adds its own header to the data from the layer above.
  • Decapsulation: Each layer removes its header to reveal the data for that layer.
  • Routers: Operate at the internet layer (primarily) to forward packets between networks based on IP addresses.
  • Switches: Operate at the link layer to forward frames within a local network based on MAC addresses.
  • Ports: Used by the transport layer (TCP/UDP) to identify specific applications or services on a host.
Important Notes
  • Devices interact at different layers of the TCP/IP stack.
  • The routing process involves multiple routers, each forwarding the packet closer to its destination.
  • The switch forwards data based on MAC addresses within the local network.



Picture
Published on
KembaraXtra-Computer Science-Foundational Internet Capabilities
1. Dynamic Host Configuration Protocol (DHCP)
  • Purpose: Automatically assigns IP addresses and related network information to devices when they connect to a network.
  • Why it's important: Simplifies network configuration for end-users by eliminating the need for manual IP address assignment.
  • How it works:
    1. Discovery: A device broadcasts a message to discover available DHCP servers.
    2. Offer: The DHCP server offers an IP address from its available pool.
    3. Request: The device requests the offered IP address.
    4. Acknowledgment: The DHCP server acknowledges the request, assigning the IP address to the device.
  • Lease: IP addresses are leased to devices for a limited time. The device must renew the lease to continue using the IP address.
  • DHCP Server: A device on the network configured to provide DHCP services, including managing a pool of available IP addresses.
2. Private IP Addresses and Network Address Translation (NAT)
  • Problem: Limited number of public IP addresses available, but many networks have multiple devices.
  • Solution: Using private IP addresses for internal network communication and NAT to share a single public IP address.
  • Private IP Addresses:
    • IP address ranges reserved for internal networks (e.g., homes, offices).
    • Ranges: 10.x.x.x, 172.16.x.x to 172.31.x.x, 192.168.x.x.
    • Non-routable on the public internet.
    • Can be used simultaneously on multiple private networks without conflict.
  • Network Address Translation (NAT):
    • Allows devices on a private network to share a single public IP address.
    • The NAT router modifies the source IP address of outgoing packets to its public IP address.
    • When responses return, the router translates the destination IP address back to the correct private IP address.
    • Security benefit: Hides devices on the private network from direct exposure to the public internet.
  • Proxy Server:
    • An alternative to NAT, typically used in corporate networks.
    • Operates at the application layer.
    • Provides additional features: User authentication, traffic logging, and content filtering.
3. The Domain Name System (DNS)
  • Purpose: Translates human-friendly domain names (e.g., www.example.com) into IP addresses.
  • Why it's important: Makes the internet easier to use by allowing users to remember names instead of IP addresses.
  • Fully Qualified Domain Name (FQDN): The complete DNS name of a computer (e.g., travel.example.com).
    • Consists of a hostname (travel) and a domain suffix (example.com).
  • Domain: A grouping of network resources managed by an organization (e.g., example.com).
  • Resolving a Hostname: The process of querying a DNS server to find the IP address associated with a hostname.
  • Mapping:
    • One-to-many: A single name can map to multiple IP addresses (used for load balancing and geographic distribution).
    • Many-to-one: Multiple names can map to the same IP address (used for web hosting).
  • DNS Records: Entries in the DNS database.
    • A Record: Maps a hostname to an IP address.
    • CNAME Record: Maps one hostname to another hostname (alias).
    • MX Record: Used for email services.
  • DNS Hierarchy:
    • A distributed system with shared responsibility for managing DNS records.
    • Root Domain: Top of the hierarchy, contains records for top-level domains (TLDs).
    • Top-Level Domains (TLDs): (e.g., .com, .org, .edu).
    • Second-Level Domains: Registered under TLDs (e.g., example.com).
  • DNS Resolution Process:
i.A client sends a DNS query to its configured DNS server.
ii.If the server has the record in its cache, it returns the IP address.
iii.If not, the server queries other DNS servers, starting at the root, to find the record.
iv.The server caches the record for future queries.
4. Networking in Context of Computing
  • The internet is a network of hardware and software enabling communication between devices.
  • Data transmission over the internet is based on binary data (0s and 1s).
  • Network interfaces (e.g., Wi-Fi, Ethernet) are I/O devices.
  • Operating systems use device drivers and software libraries to facilitate network communication for applications.
  • Networking devices (routers, switches) are specialized computers.
  • Networking extends computing beyond single devices.



Picture
Published on
KembaraXtra -Computer Science -World Wide Web
Core Attributes
Distributed
  • Definition: No central authority controls web content.
  • Implications:
    • Anyone can host a web server and publish content.
    • Organizations/countries can block access.
    • Governments can shut down illegal content.
  • Key Point: The web is open and not centrally controlled.
Addressable
  • Definition: Every web resource has a unique address (URL).
  • URL Components:
    • Scheme: Protocol (e.g., HTTP, HTTPS).
    • Authority:
      • Hostname (e.g., travel.example.com).
      • Optional: Username, Port Number.
    • Path: Location of resource on server (like a file system path).
    • Query: Modifies the resource returned (format varies by site).
  • Relative URLs:
    • Omit scheme, hostname, or full path.
    • Interpreted relative to the current context.
  • Practical URL Reading Example:
http://travel.example.com/destinations/carolinas?location=beach
  • Uses HTTP protocol.
  • Server: travel.example.com.
  • Path: /destinations/carolinas.
  • Query: location=beach (shows beach locations).
Linked
  • Definition: Web resources reference each other via hyperlinks.
  • Hyperlinks: One-way references, no permission needed.
  • Hypertext: Documents connected by hyperlinks.
Protocols of the Web
HTTP (HyperText Transfer Protocol)
  • Purpose: Transferring web resources (reading, creating, updating, deleting).
  • Foundation: Based on TCP/IP for reliable data transfer and addressing.
  • Model: Request and response.
    • Client sends an HTTP request.
    • Server replies with an HTTP response.
HTTP Methods (Verbs)
  • GET: Retrieve a resource (no modification).
  • PUT: Create/modify a resource at a specific URL.
  • POST: Create a new resource as a child of an existing URL.
  • DELETE: Remove a resource.
  • Usage:
    • GET is most common (used for browsing and loading resources).
    • Servers often restrict PUT, POST, DELETE.
HTTP Status Codes
  • Format: 3-digit number.
  • Classes:
    • 100s: Informational.
    • 200s: Success.
    • 300s: Redirection.
    • 400s: Client error.
    • 500s: Server error.
  • Examples:
    • 200 OK: Success.
    • 301 Moved Permanently: Redirect to a new URL.
    • 401 Unauthorized: Authentication required.
    • 403 Forbidden: Access denied.
    • 404 Not Found: Resource not found.
    • 500 Internal Server Error: Server-side error.
HTTP Message Format
  • Request:
    • First line: Method URL HTTP/Version (e.g., GET /documents/hello.txt HTTP/1.1).
    • Headers: Additional information.
    • Optional message body.
  • Response:
    • First line: HTTP/Version Status Code Response Phrase (e.g., HTTP/1.1 200 OK).
    • Headers.
    • Optional message body.
HTTPS (HyperText Transfer Protocol Secure)
  • Purpose: Encrypt data transmitted over the internet.
  • Encryption: Encoding data to be unreadable without decryption.
  • Cryptographic Key: Secret sequence of bytes used for encryption/decryption.
  • Encryption Types:
    • Symmetric: Single shared key for both encryption and decryption.
    • Asymmetric:
      • Public key: Encrypts data.
      • Private key: Decrypts data (kept secret).
  • Security:
    • Prevents interception and modification of data.
    • Encrypts the entire HTTP request (URL, headers, body).
  • TLS (Transport Layer Security): Protocol used to encrypt HTTP requests (formerly SSL).
  • HTTPS Handshake:
i.Client hello: Client sends the server the encryption methods it supports.
ii.Server hello: Server selects the encryption methods. The server provides its public key.
iii.The client encrypts a string of bytes with the server's public key, and sends it to the server.
iv.Server decrypts using its private key. Both compute a shared secret key for symmetric encryption.
v.All further data is encrypted using the shared secret key.
The Searchable Web
  • Entry Point: Often accessed through search engines.
  • Search Engines: Non-standard, proprietary systems (e.g. Google). """



Picture
Published on

KembaraXtra – Computer Science – Web Languages

I. Core Web Languages

A. HTML (HyperText Markup Language)

  • Purpose: Defines the structure of a web page. It determines what is on the page.
  • Key Concepts:
    • Tags: Enclosed in < and > (e.g., <p>, <h1>).
    • Elements: Consist of a start tag, content, and an end tag (e.g., <p>This is a cat.</p>). Some elements don't require end tags (e.g., <img>).
    • Structure: HTML documents have a tree-like structure with parent and child elements.
    • <!DOCTYPE html>: Declares the document as HTML.
    • <html>: The root element, containing everything else.
    • <head>: Contains document metadata (e.g., title, character set).
    • <body>: Contains the content of the web page.
    • <h1> to <h6>: Heading tags, with <h1> being the highest level.
    • <p>: Paragraph tag.
    • <img>: Image tag; src specifies image URL, alt gives alternative text.
    • Whitespace: Browsers ignore extra whitespace. Use indentation for readability.
    • HTML Living Standard: Maintained by WHATWG.
  • Example:
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>A Cat</title>
  </head>
  <body>
    <h1>Thoughts on a Cat</h1>
    <p>This is a cat.</p>
    <img src="cat.jpg" alt="cat photo">
  </body>
</html>
    

B. CSS (Cascading Style Sheets)

  • Purpose: Defines the appearance/style of a web page.
  • Key Concepts:
    • Rules: Define styles for specific elements.
    • Selectors: Indicate which elements are affected.
    • Cascading: Multiple rules can apply to the same element.
    • Font-family: Defines fallback fonts.
  • Methods of Application:
    • Inline: Within a <style> element – not recommended.
    • External: In a separate .css file and linked using <link> in <head>.
  • Example:
p {
  font-family: Arial, Helvetica, sans-serif;
  font-size: 11pt;
  margin-left: 10px;
  color: DimGray;
}
h1 {
  font-family: 'Courier New', Courier, monospace;
  font-size: 18pt;
  font-weight: bold;
}
    

C. JavaScript

  • Purpose: Defines behavior/functionality of a web page.
  • Key Concepts:
    • Interpreted Language: Executed at runtime by browser.
    • Minification: Reduces file size by removing whitespace/comments.
    • DOM: JavaScript can access and modify the page structure.
    • Event Handlers: Respond to user actions.
    • Integration: Embedded in HTML or linked via <script src="cat.js"></script>.
  • Example:
document.getElementById('cat-photo').onclick = function() {
  document.getElementById('cat-para').innerHTML += ' Meow!';
};
    
  • Explanation:
    • Selects element by ID.
    • Assigns a function on click.
    • Appends "Meow!" to the paragraph.
  • ECMAScript: The standardized specification for JavaScript.
  • II. Data Structuring Languages

    A. XML (Extensible Markup Language)

    • Purpose: Text-based language for data exchange.
    • Key Concepts:
      • Custom tags defined by the user.
      • Requires producer-consumer agreement.
    • Example:
    <band name="The Highbury Musical Club">
      <bandMembers>
        <member name="Jane Fairfax" instrument="Piano" />
        <member name="Emma Woodhouse" instrument="Guitar" />
      </bandMembers>
    </band>
        

    B. JSON (JavaScript Object Notation)

    • Purpose: Lightweight data format.
    • Key Concepts:
      • JavaScript-like syntax with {} and [].
      • Compact and readable.
    • Example:
    {
      "name": "The Highbury Musical Club",
      "bandMembers": [
        {
          "name": "Jane Fairfax",
          "instrument": "Piano"
        },
        {
          "name": "Emma Woodhouse",
          "instrument": "Guitar"
        }
      ]
    }
        
  • Usage: Used for API communication between clients and servers.

  • KembaraXtra – Computer Science – Web Browsers

    I. Introduction

    • Definition: Software applications for accessing web pages.
    • Key Functions: Requesting, receiving, and displaying web content.

    II. History of Web Browsers

    • WorldWideWeb: First browser, by Tim Berners-Lee (1990).
    • Mosaic: Brought the web to the masses.
    • Netscape Navigator: Popular in early web history.
    • Internet Explorer: Dominated the late 1990s and 2000s.
    • Modern Browsers: Chrome, Safari, Firefox.

    III. Rendering a Web Page: The Process

    1. Request: Browser sends URL request.
    2. HTML Response: Server returns HTML content.
    3. DOM Creation: Browser parses HTML into a DOM tree.
    4. Resource Requests: Additional resources (images, JS, CSS) are loaded.
    5. Rendering:
      • Displays HTML.
      • Applies CSS.
      • Executes JavaScript.
      • Updates dynamically via JS if needed.

    IV. Web Browser Architecture

    • Rendering Engine: Handles HTML/CSS layout.
    • JavaScript Engine: Runs JS code.
    • User Interface: Provides controls like the address bar.

    V. Rendering Engine Landscape

    • Key Point: Engines affect how pages look.
    • WebKit: Safari and iOS apps.
    • Blink: Chrome, Edge, Opera (Chromium-based).
    • Gecko: Firefox (with SpiderMonkey JS engine).

    VI. Understanding the User Agent String

    • Definition: The technical term for a browser is a "user agent."
    • User-Agent Header: Identifies browser during requests.
    • Example: Mozilla/5.0 (Windows NT 10.0; Win64; x64)...
    • Components Explained:
      • Mozilla/5.0: Compatibility prefix.
      • (Windows NT 10.0; Win64; x64): Platform.
      • AppleWebKit/537.36: Rendering engine.
      • (KHTML, like Gecko): History artifact.
      • Chrome/71.0.3578.98: Browser version.
      • Safari/537.36: Ensures Safari compatibility.
    • Reason for Complexity: Historical compatibility tricks.
    Picture
    Published on

    KembaraXtra – Computer Science – Web Servers

    I. Client-Side vs. Server-Side Technologies

    • Client-Side: Primarily deals with what the user sees and interacts with in the web browser. Uses HTML, CSS, and JavaScript.
    • Server-Side: Deals with the logic and data processing behind the website. Any programming language or technology can be used, as long as it communicates over HTTP and returns data in a format the client understands.

    II. Static vs. Dynamic Websites

    Feature Static Websites Dynamic Websites
    Content HTML, CSS, and JavaScript built ahead of time. HTML generated when a request comes in.
    Processing Server returns pre-built files without modification. Server processes the request, often querying a database, generating HTML, and then responding.
    Complexity Simpler setup. More complex setup, slower response times, potentially heavy server load, increased security risks.
    Response Time Typically faster. Typically slower due to processing.
    Server Load Lighter load. Heavier load.
    Security Generally more secure. Potentially less secure due to increased complexity.
    Example Website developed using only HTML, CSS and JavaScript files and hosted on a web server (Projects #37 through #40). A blog where posts are stored in a database and rendered into HTML when requested.

    Important Note: The terms "static" and "dynamic" refer to how the content is generated on the server, not whether the website is interactive or has updated content. User experience (interactivity, content updates) is often handled with JavaScript on the client-side, regardless of whether the site is static or dynamic from the server's perspective.

    III. How Static Websites Handle Requests

    1. Browser requests a specific URL.
    2. Web server receives the request.
    3. Web server finds the corresponding static file (e.g., /images/cat.jpg) in its directory.
    4. Web server returns the content of that file to the browser.
    5. The server does not modify the content.

    IV. How Dynamic Websites Handle Requests

    1. Browser requests a specific URL.
    2. Web server receives the request and determines that it needs to generate HTML.
    3. The server executes code.
    4. The code queries a database and retrieves the relevant data.
    5. The server formats the data as HTML.
    6. The server responds to the client with the generated HTML.

    V. The Trend Toward Static Sites

    • In recent years, there has been a shift back towards static sites where possible.
    • Static sites offer simplicity, speed, and security benefits.

    VI. Hosting Static Sites

    • You need a web server software that can serve static files.
    • The software is configured to point to a directory containing the website files.
    • When a request comes in, the server returns the contents of the matching file.

    VII. Building Dynamic Websites/Web Services

    • You can use existing software or write custom code to generate dynamic pages.
    • Server-side development offers a wide range of technology choices (programming languages, operating systems, databases, etc.).
    • The client doesn't care what technologies are used on the server-side; it only needs a response in a format it can handle.

    VIII. Server-Side Technology Choices

    • Programming Languages: Python, C#, JavaScript (Node.js), Java, Ruby, PHP, etc.
    • Databases: Any type of database can be used.
    Picture
    Published on

    Study Guide: Logic in Programming

    I. Introduction

    • Processors excel at logical operations, which are fundamental to digital circuits.

    • Programming languages provide operators for handling logic.

    • Two main types of logical operators:

    • Bitwise Operators: Operate on individual bits of integers.
    • Boolean Operators: Operate on Boolean (true/false) values.

    • Terminology varies across languages (e.g., C uses "logical" instead of "Boolean"). This guide will use "bitwise" and "Boolean."

    II. Bitwise Operators

    • Act on individual bits of integers.

    • Result: an integer value.

    • Perform logical operations (AND, OR, XOR, NOT) on the bits of integers in parallel.

    • Operators (common in C and Python):

    • AND: &
    • OR: |
    • XOR: ^
    • NOT (complement): ~

    Example (Python):

    x = 5  # Binary: 0101
    y = 3  # Binary: 0011
    a = x & y  # Bitwise AND
    b = x | y  # Bitwise OR
    
    # a is 1 (0001 in binary)
    # b is 7 (0111 in binary)
    

    Explanation of Example

    • AND: The result is 1 only when both corresponding bits are 1.

    • 5 & 3:

    0101
    0011
    ----
    0001 (1 in decimal)
    

    • OR: The result is 1 if either corresponding bit (or both) is 1.

    • 5 | 3:

    0101
    0011
    ----
    0111 (7 in decimal)
    

    III. Boolean Operators

    • Work on Boolean values (true or false).

    • Result: a Boolean value.

    • Boolean values: represented differently in different languages (e.g., True or False in Python).

    • Boolean variable: a named memory address holding a true or false value.

    • Expressions can evaluate to true or false (e.g., item_cost > 5).

    Boolean Operators:

    • Perform logical operations (AND, OR, NOT) on Boolean values.

    • Example: item_on_sale and item_cost > 5 (checks if both conditions are true).

    Boolean Operation C Operator Python Operator
    AND && and
    OR || or
    NOT ! not

    Comparison Operators:

    • Compare two values and evaluate to true or false.

    Comparison Operation Operator
    EQUALITY ==
    NOT EQUAL !=
    GREATER THAN >
    LESS THAN <
    GREATER THAN OR EQUAL >=
    LESS THAN OR EQUAL <=

    Important:

    • == (double equals) is for equality comparison (returns true/false).
    • = (single equals) is for assignment (sets a variable's value).
    • Example: x == 5 (is x equal to 5?) vs. x = 5 (set x to 5).
    Published on

    Program Flow: Controlling What Your Code Does

    Core Idea: Program flow (or control flow) lets your program make decisions and repeat actions based on conditions.

    1. If Statements: Doing Something Based on a Condition

    Purpose: Executes a block of code only if a specified condition is true. Optionally includes else to execute a different block if the condition is false.

    Basic Structure:

    Python:

    if condition:
        # Code to execute if condition is true
    else:
        # Code to execute if condition is false

    C:

    if (condition) {
        // Code to execute if condition is true
    } else {
        // Code to execute if condition is false
    }

    Key Differences (Python vs. C):

    • Code Blocks:
      • Python: Uses indentation to define code blocks (lines with the same indentation level belong to the same block).
      • C: Uses curly braces {} to define code blocks. Braces can be omitted for single-line blocks.
    • elif (Python) / else if (C): Used to check multiple conditions in sequence. The elif/else if condition is only evaluated if the preceding if or elif/else if condition was false.

    Python:

    if condition1:
        # Code for condition1
    elif condition2:
        # Code for condition2
    else:
        # Code if neither condition1 nor condition2 is true

    C:

    if (condition1) {
        // Code for condition1
    } else if (condition2) {
        // Code for condition2
    } else {
        // Code if neither condition1 nor condition2 is true
    }

    2. Looping: Repeating Actions

    Purpose: Executes a block of code repeatedly.

    Types:

    • while loop: Repeats as long as a condition is true.

    Python:

    while condition:
        # Code to repeat

    C:

    while (condition) {
        // Code to repeat
    }

    Important: Make sure the condition eventually becomes false to avoid an infinite loop!

    • for loop: Iterates over a sequence of values (numbers, items in a list, etc.).

    C Style (for with numeric range):

    for (initialization; condition; increment/decrement) {
        // Code to execute in each iteration
    }

    • initialization: Executed once at the beginning of the loop (e.g., int x = 1;).
    • condition: Checked before each iteration. The loop continues as long as the condition is true (e.g., x <= 10;).
    • increment/decrement: Executed after each iteration (e.g., x++;).

    Python Style (for with collection):

    for item in collection:
        # Code to execute for each item in the collection

    • collection: A list, tuple, string, or other iterable object.
    • item: A variable that takes on the value of each item in the collection during each loop iteration.
    Picture
    Published on

    KembaraXtra-Computer Science - Functions

    1. What are Functions?

    Definition: A function is a reusable block of code that performs a specific task.

    Purpose:

    • Avoid code duplication.
    • Promote code reusability.
    • Improve code organization and readability.

    Terminology: Functions may also be called subroutines, procedures, or methods (slight differences in meaning may exist depending on the language).

    DRY Principle: Functions adhere to the "Don't Repeat Yourself" (DRY) principle by reducing duplicative code.

    Encapsulation: Functions encapsulate internal details, providing an interface (inputs and outputs) for usage. Users don't need to know the inner workings.

    2. Defining Functions

    Definition: Creating a function and specifying its behavior.

    Elements of a Function Definition:

    • Name: A unique identifier for the function.
    • Parameters (Inputs): Values passed to the function when it is called.
    • Body: The code block containing the instructions the function executes.
    • Return Value (Output): The value the function sends back to the caller (optional).

    Example (C):

    double areaOfCircle(double radius) {
        double area = 3.14 * radius * radius;
        return area;
    }
    • double: Return type (floating-point number).
    • areaOfCircle: Function name.
    • double radius: Input parameter (radius of the circle).
    • { ... }: Function body.
    • return area: Returns the calculated area.

    Example (Python):

    def area_of_circle(radius):
        area = 3.14 * radius * radius
        return area
    • def: Keyword to define a function.
    • Type declarations are not required in Python.

    3. Calling Functions

    Definition: Executing a defined function.

    Process:

    1. The calling code invokes the function.
    2. Parameters are passed (if any).
    3. Control is transferred to the function.
    4. The function executes its code.
    5. The function returns control (and a return value, if any) to the caller.

    Example (C):

    double area1 = areaOfCircle(2.0);
    double area2 = areaOfCircle(38.6);

    Example (Python):

    area1 = area_of_circle(2.0)
    area2 = area_of_circle(38.6)

    The returned value can be stored in a variable or ignored (though ignoring the return value might not be useful, depending on the function).

    4. Using Libraries

    Definition: Leveraging pre-written functions provided by programming languages or third-party developers.

    Standard Library: A set of functions included with a programming language.

    Examples: Printing to the console, file operations, text processing.

    C and Python both have standard libraries. Python's is known to be extensive.

    Additional Libraries: Libraries created by developers and shared for others to use.

    Package Managers: Tools for managing and distributing libraries (packages).

    • Python: pip (widely used).
    • C: Multiple package managers exist, but none are universally adopted.
    Picture
    Published on
    KembaraXtra-Computer Science- Object-Oriented Programming (OOP)
    I. Paradigms in Programming
    • Programming languages support different approaches to programming called paradigms.
    • Examples:
      • Procedural Programming
      • Functional Programming
      • Object-Oriented Programming (OOP)
    • Languages can support multiple paradigms.
    II. Object-Oriented Programming (OOP)
    • Definition: A programming paradigm where code and data are grouped together into objects.
    • Objects: Logical groupings of data and functionality, designed to model real-world concepts.
    III. Classes and Objects
    • Class-Based Approach: Common in OOP languages.
      • Class: A blueprint for an object. Defines the structure and behavior of a type of object.
      • Object: An instance of a class. A concrete realization of the class blueprint.
    • Methods: Functions defined within a class. They define the actions that an object can perform.
    • Fields: Variables declared within a class. They store the data associated with an object.
      • Instance Variables (Python): Fields that have different values for each object (instance) of the class. Each object has its own unique value for these fields.
      • Class Variables (Python): Fields that have the same value across all objects (instances) of the class. These variables are shared by all objects of the class.
    IV. Example: Bank Account
    • Class: BankAccount (a blueprint)
      • Fields:
        • balance (instance variable - each account has a unique balance)
        • holder's name (instance variable - each account has a unique name)
      • Methods:
        • withdraw()
        • deposit()
    • Objects: Specific bank accounts created from the BankAccount class (instances). These are real accounts with specific names and balances.
    • Interaction: We can use the withdraw or deposit methods to modify the balance field of specific bank account objects.
    V. Python Example
    myAccount.deposit(25) # Increases myAccount's balance by 25
    Key Concept: myAccount is an object (instance of BankAccount). deposit() is a method called on that specific object, modifying its balance field.


    Picture