< All Topics

Programming Basics & Foundations

“Programming is not about typing; it is about thinking.”

1. What is Programming?

Programming is the art of giving instructions to a computer to perform specific tasks. A computer is a powerful machine, but it is not “smart” on its own it needs logic to function.

A program tells the computer “What to do”, “How to do it”, “When to do it”.

At its core, every program follows the IPO Cycle:

  1. Input: The computer receives data.
  2. Process: The CPU manipulates the data based on your code.
  3. Output: The result is displayed or stored.

A computer simply executes instructions sequentially (line-by-line) in the exact order they are written.

Syntax: – Syntax refers to the rules and conventions for writing code in a specific programming language.

Debugging: – Debugging is the process of finding and fixing errors (bugs) in a program. 


2. Generations of Programming Languages

The history of code is a journey from “machine-speak” to “human-speak.”

  • 1st Generation (Machine Language): The native language of the CPU using only binary (0 and 1). It is extremely fast but nearly impossible for humans to read.
  • 2nd Generation (Assembly Language): Uses “mnemonics” (short codes like ADD, MOV). Still very close to hardware; used today for device drivers.
  • 3rd Generation (High-Level Languages): Uses English-like words (if, while, print). This is where most modern coding happens (Java, C++, Python).
  • 4th Generation (Query Languages): Focuses on what to do, not how (e.g., SQL for databases).
  • 5th Generation (AI Languages): Focuses on constraints and problem-solving logic (e.g., Prolog).

1. Classification of programming languages

CategoryDescription & CharacteristicsExamplesBest Use Cases
Low-Level Languages• Sit closest to the hardware.
• Provide little to no abstraction.
• Require manual management of memory and CPU registers.
Machine Language (Binary), AssemblyDevice drivers, embedded systems, and real-time systems where hardware control is critical.
System Languages• Designed for building system software.
• Offer a balance of high-level readability and low-level control.
• Extremely fast with manual memory management.
C, C++, Rust, GoOperating Systems (Windows/Linux), Game Engines, Browsers.
Scripting Languages• High-level languages used to “glue” software or automate tasks.
• Usually interpreted (run line-by-line) rather than compiled.
• Slower execution but very fast development speed.
Python, Bash, Perl, Ruby, PowerShellData Science, system automation, cybersecurity scripts, quick prototyping.
Web-Based Languages• Specialized for creating websites and web applications.
• Divided into Frontend (User Interface) and Backend (Server Logic).
Frontend: HTML, CSS, JavaScript
Backend: PHP, Node.js, Python
E-commerce sites, social networks, blogs, and interactive web applications.

3. How Code Runs

Understanding this separates a “coder” from a “developer.” Computers don’t understand English; they need a translator.

1. The Translation Pipeline

  1. Source Code: The code you write.
  2. Compiler/Interpreter: Translates source code into machine code.
  3. Linker: Connects your code to existing libraries (like math or graphics tools).
  4. Loader: Places the program into RAM so the CPU can run it.

2. Compiler vs. Interpreter

FeatureCompiler (e.g., C, C++)Interpreter (e.g., Python, JS)
MethodScans the entire program and translates it all at once.Translates and runs line-by-line.
SpeedCompilation takes time, but the result is very fast.Execution is slower as it translates on the fly.
ErrorsReports all errors at the end.Stops execution at the first error.

3. Memory Management: Stack vs. Heap

  • Stack Memory: Organized, fast storage for temporary data (like local variables inside a function).
  • Heap Memory: Large, unorganized storage for global data and complex objects. Memory Leaks happen here if you don’t clean up unused data.

4. The Building Blocks of Code

Every language uses these fundamental concepts.

1. Variables & Constants

  • Variable: A named container for data. Its value can change (e.g., score = 10).
  • Constant: A container whose value cannot change (e.g., PI = 3.14).

2. Data Types

  • Integer: Whole numbers (10, -5).
  • Float: Decimal numbers (9.8, 3.14).
  • String: Text (“Hello World”).
  • Boolean: Logic values (True/False).

3. Type Casting

Converting one data type to another temporarily.

  • Example: converting the string “100” into the number 100 to do math.

4. Formal programming terminology

  • Declaration → Creating a variable
  • Initialization → Assigning initial value
  • Assignment → Changing the value


5. Control Structures – Guiding the Logic

Code doesn’t always run in a straight line. We control the flow using:

1. Sequential Flow – Default program flow

  • Instructions execute one after another

2. Selection – Decision Making

  • if / if-else/ else-if / else: Execute code only if a condition is true.
  • Switch: Efficiently check one variable against many possible values.

3. Iteration – Loops

  • For Loop: Repeat a specific number of times.
  • While Loop: Repeat as long as a condition is true.
  • Do-While loop:
  • Sentinel Value: A special value used to terminate a loop (e.g., “Enter -1 to exit”).

6. Logic Design Tools

Professional developers plan before they type.

  • Algorithm: A step-by-step logical solution written in plain English.
    • Input and output
    • Clear steps
    • Effective and finite
    • Language independent
  • Pseudocode: A mix of English and code structure. It helps draft the logic without worrying about syntax.
    • Capital keywords
    • One statement per line
    • Proper indentation
    • Simple language
    • No programming syntax
  • Flowchart: A visual diagram of the algorithm.
    • Oval: Start/Stop
    • Diamond: Decision (Yes/No)
    • Rectangle: Process/Action
    • Shows steps visually
    • Helps understand program flow
    • Used for planning and teaching

7. Data Structures

How you organize data determines the speed of your software.

1. Linear – Sequential

  • Array: Fixed size, fast access.
  • List: Flexible size.
  • Stack (LIFO): Last In, First Out (like a stack of plates).
  • Queue (FIFO): First In, First Out (like a ticket line).

2. Non-Linear (Hierarchical)

  • Tree: Parent-child data (like file folders).
  • Graph: A network of interconnected nodes (no strict hierarchy).

3. Key-Value (Associative)

  • Hash Map (Dictionary): Key-Value pairs. The fastest way to find data (O(1) complexity).

4. Static vs. Dynamic (Memory)

FeatureStatic Data StructureDynamic Data Structure
DefinitionMemory size is fixed at Compile Time (before running).Memory size changes at Runtime (while running).
BehaviorSize is set permanently. You cannot resize it later.Size grows or shrinks automatically as needed.
Memory UsageCan waste memory (if unused) or run out of space.Efficient; uses exactly as much memory as needed.
PerformanceExtremely fast data access.Slightly slower (due to memory reallocation).
ExampleArray (int arr[10])Linked List, Vector, ArrayList

5. Homogeneous vs. Non-Homogeneous (Data Type)

FeatureHomogeneousNon-Homogeneous (Heterogeneous)
DefinitionStores elements of the same data type only.Stores elements of mixed data types.
ConstraintStrict. (e.g., Integer only).Flexible. (Integers, Strings, Objects together).
AdvantageFaster calculation of memory addresses.Great for storing complex records (like a user profile).
ExampleArrays ([1, 2, 3])Python Lists ([1, "Hi", 3.14]), Classes, Structs

CRUD Operations: The 4 basic actions of data storage: Create, Read, Update, Delete.


8. Programming Paradigms – POP vs. OOP

A “paradigm” is a style of coding.

1. Procedure Oriented Programming (POP)

is best suited for problems with step-by-step instructions. A complex programming problem is solved by dividing into smaller problems using functions or procedures. And called as top-down approach.

The “Top-Down” Approach: – a complex problem is not solved all at once. Instead, it uses a “Divide and Conquer” strategy.

  1. Break Down: – The large program is divided into smaller, manageable tasks called Functions.
  2. Solve Separately: – Each function is written to solve a specific part of the problem.
  3. Combine: – All functions are combined to form the final solution.

Key Characteristics

  1. Top-Down Design: – Programs start from a high-level routine and break down into low-level routines.
  2. Function-Centric: – The program is a collection of functions. Each function performs a specific task.
  3. Detached Data & Logic: – Real-world processes are modeled as “procedures” acting on “data”. However, the data and the functions are separate entities.
  4. Free-Moving Data: – Data moves freely between functions (often as global data), making it accessible to many parts of the program.
  5. Simplicity: – The logic is straightforward and easy to follow for small to medium-sized programs.

Limitations of POP

  1. Low Data Security: Since data moves freely and is often global, it can be accidentally modified by any function. This makes the system vulnerable.
  2. Hard to Maintain: Data and functions are separate. If you change a data type (e.g., changing an integer to a float), you must manually update every function that uses that data.
  3. Limited Reusability: It is difficult to reuse code in other programs because functions are often tightly coupled to the specific global data of the current program.
  4. Not Scalable: As programs grow larger and more complex, managing the “spaghetti code” of interlinked functions and global data becomes extremely difficult.
  • Examples: C, Pascal. COBOL, BASIC

2. Object-Oriented Programming (OOP)

OOP is a programming paradigm based on the concept of “Objects”, which can contain data (attributes) and code (methods). Unlike POP, which focuses on the logic/steps, OOP focuses on the data and the objects that manipulate it.

The “Bottom-Up” Approach:

In OOP, we solve problems by looking at the small parts first.

  1. Identify Objects: We look for the “actors” or entities in the problem (e.g., User, Order, Product).
  2. Define Behavior: We decide what each object is and what it can do.
  3. Build Up: We connect these objects to form the complete system.

Core Concepts

  1. The Object (The Real Entity):
    • Everything in OOP is an object.
    • An object is an identifiable entity that has: –
      • Attributes (Data): – What the object is or has (e.g., Color, Size, Price).
      • Behavior (Methods): – What the object does (e.g., Start, Stop, Calculate).
  2. The Class (The Blueprint):
    • A Class is a template or blueprint used to create objects. It describes the common attributes and behaviors.
    • Instance: – An object created from a class is called an instance of that class.
    • The Architect’s Plan is the Class. The actual House built from that plan is the Object.

Key Characteristics

  1. Encapsulation: Data and functions are wrapped together into a single unit (the Object).
  2. Data Hiding (Security): Data is not freely accessible to the entire program. It can only be accessed or modified through the object’s own functions. This prevents accidental corruption.
  3. Real-World Modeling: OOP mirrors the real world. If you are building a banking app, your code will actually have Customer, Account, and Transaction objects.
  4. Reusability: Once a Class is defined properly, it can be reused in different parts of the program or even in other projects.

Limitations of OOP

  1. Complexity & Size: OOP programs often require more lines of code (boilerplate) than procedural programs, making the file size larger.
  2. Memory Consumption: Creating many objects can consume more RAM compared to simple variables in POP.
  3. Steep Learning Curve: It requires substantial planning and design before writing code. Understanding the interactions between classes can be difficult without good documentation.
  4. Overkill for Simple Tasks: For small, step-by-step scripts (like data processing), OOP adds unnecessary complexity.
  • Examples: Java, C++, Python.

3. The 4 Concepts / Pillars / Principles of OOP

  1. Abstraction: Showing only necessary details to the user.
  2. Encapsulation: Hiding internal data for security (like a car engine under the hood).
  3. Inheritance: Reusing code from a parent class (like a “Sports Car” inheriting wheels from “Car”).
  4. Polymorphism: One function behaving differently in different situations.

For a language to be truly Object-Oriented, it must implement these four core principles. These principles help manage complexity and secure data.

1. Abstraction – Hiding Complexity

Abstraction means showing only the essential features of an object while hiding the complex inner details.

  • It simplifies the interface for the user. The user interacts with a simple button, while the complex logic happens behind the scenes.
  • More over obstruction is relative to the perspective of the viewer.
  • Key Term: Information Hiding (Only exposing what is necessary).

2. Encapsulation – Data Security

Encapsulation is the mechanism of bundling data (variables) and methods (functions) together into a single unit (the Class).

It keeps them both safe from the outside world for any unauthorized access or misuse.

Access to the data and code inside a class is tightly controlled. Only the functions that are inside the class access data.

  • It acts like a protective shield. It restricts direct access to some of an object’s components.
  • Data is kept “private” inside the class. The outside world can only access it through public methods (like “Getters” and “Setters”).
  • It protects data from unauthorized access or accidental modification.

3. Inheritance – Code Reusability

The mechanism where a new class (Child) acquires the properties and behaviors of an existing class (Parent).

  • Parent Class (Super Class): The generic class with common features (e.g., Animal).
  • Child Class (Sub Class): The specific class that inherits from the parent (e.g., Dog inherits from Animal).
  • You don’t have to rewrite code. You write the common logic once in the Parent, and all Children get it automatically. This promotes Reusability.

4. Polymorphism – Flexibility

The word literally means “Many Forms.” It allows a single function or object to behave differently in different contexts.

A powerful mechanism by which one class acquires the properties of another class.

  • You can send the same message to different objects, and each object responds in its own way.
  • Example:
    • You have a function speak().
    • If you call Dog.speak(), it barks.
    • If you call Cat.speak(), it meows.
    • The function name is the same (speak), but the behavior changes based on the object.
  • Benefit: It makes the system flexible and easy to extend without breaking existing code. enables us to reuse existing code easily and flexibly.
Basis for ComparisonProcedure Oriented Programming (POP)Object-Oriented Programming (OOP)
ApproachFollows a top-down approach (starts with high-level routines and breaks them down).Follows a bottom-up approach (starts with small parts/objects and builds up).
OrientationAlgorithmic in nature (instruction-oriented); focuses on logic/steps.Data-oriented in nature; focuses on data and the objects that manipulate it.
Program DivisionThe program is divided into tasks called functions or procedures.The entire program is divided into objects (entities with attributes and behaviors).
Data & Function RelationshipData and functions are separate entities; data moves freely (often global).Data and functions are encapsulated into a single unit (the Object).
Data SecurityLow security; data can be accessed and modified by any function, making it vulnerable.More secure; uses data hiding/encapsulation to restrict access to data.
Data Sharing/InteractionInteraction occurs via direct function calls; functions can access other functions’ data.Interaction occurs via functions defined in the class; only granted data can be accessed.
Abstraction LevelAbstraction is at the procedure (function) level.Abstraction is at the object (class) level.
Code ReusabilityLimited and difficult; functions are often tightly coupled to specific global data.Versatile and easy; classes can be reused across different parts of a program or projects.
Code MaintenanceDifficult to modify, extend, and maintain (e.g., data type changes require manual updates everywhere).Easy to modify, extend, and maintain due to modularity and inheritance.
Real World ModelingRepresents real world as “procedures” acting on “data”.Mirrors the real world using objects (e.g., Customer, Product).
ExamplesC, Pascal, COBOL, BASICJava, C++, C#, Python

4. Constructors – The Object Builder

In Object-Oriented Programming (OOP), a Constructor is a special function used to set up an object when it is first created.

  • A block of code that initializes a newly created object.
  • It is called automatically the moment you create an object (e.g., using the new keyword).
    • Name: Must have the same name as the Class.
    • No Return Type: Unlike other functions, it does not return any value (not even void).
    • Purpose: To give initial values to the object properties.

Types of Constructors

FeatureDefault ConstructorParameterized Constructor
ParametersHas no parameters (arguments).Accepts parameters (arguments).
PurposeSets variables to default values (e.g., 0, null).Sets variables to specific custom values passed by the user.
UsageUsed when you want to create a generic object.Used when you want to create an object with specific details immediately.
ExampleCreating a generic “Car” (no specific color or model).Creating a specific “Red Toyota”.


9. Functions & Modularity

  • Modularity: Breaking a large program into smaller, manageable chunks called Functions.
  • Recursion: When a function calls itself to solve a problem (useful for sorting or tree navigation).
  • Scope:
    • Local Scope: Variables exist only inside the function (Secure).
    • Global Scope: Variables exist everywhere (Less secure).

10. Defensive Programming

Defensive programming is the practice of anticipating failure. Instead of hoping everything goes right, you assume things will go wrong and code safeguards against them.

“Never trust the user and never trust the environment.”

1. Core Principles

  1. Handle Invalid Input – Validation
    • The Risk: – is Users make mistakes (typos) or are malicious (hackers).
    • The Defense: – Validate data before processing it.
    • Technique:
      • Whitelisting: – Only accept known good characters (e.g., “Only allow A-Z for names”).
      • Sanitization: – Strip out dangerous characters (e.g., removing <script> tags to prevent XSS attacks).
    • Example: If a function expects an age, check if (age > 0 && age < 120) before saving it.
  2. Assume Failures – Paranoia
    • The Risk: – The database might be down, the file might be missing, or the internet might disconnect.
    • The Defense: – Don’t just write code for the “Happy Path” (when everything works). Write code for the “Sad Path” (when things break).
    • Example: Always check if a file exists before trying to open it. Use try-catch blocks around network requests.
  3. Follow Standards
    • The Risk: – “Clever” or unique coding styles are hard to read and harder to debug.
    • The Defense: – Stick to industry conventions (like PEP8 for Python or CamelCase for Java).
    • Why: Standard code is predictable. Predictable code is safe code.
  4. Keep Code Simple – Complexity is the Enemy
    • The Risk: – Complex logic hides bugs. If you can’t understand it easily, you can’t secure it.
    • The Defense: – Follow the KISS Principle (Keep It Simple, Stupid).
    • Technique: – Break big functions into small, single-purpose functions. If a function has more than 3 levels of nested if-statements, rewrite it.


11. Errors & Exception Handling

In the coding world, these mistakes are called “Bugs.” Understanding when and why they happen is the key to fixing them.

1. Types of Errors

Errors generally fall into four categories based on when they occur and how they affect the program.

Error TypeDefinitionWhen it HappensResultExample
Syntax Errors
(The “Grammar” Mistake)
Violating the rules of the programming language (like a spelling mistake).Detected by the Compiler before the program runs.The program will not run at all until fixed.Missing a semicolon ;, unclosed parenthesis (, or typing prnt instead of print.
Runtime Errors
(The “Crash”)
The code is grammatically correct, but an illegal operation occurs during execution.Happens during execution.The program crashes or stops abruptly.Dividing by zero (10 / 0), trying to open a missing file, or running out of memory.
Logical Errors
(The “Wrong Answer”)
The program runs without crashing, but the logic is flawed. Hardest to detect.During execution.Produces incorrect output (no error message).Using a + instead of -, or writing an infinite loop.
Compile-time ErrorsA broad category that includes Syntax Errors and Type Checking errors.During the compilation process.Source code cannot be converted into machine code.Trying to store text ("Hello") inside an Integer variable.

2. Exception Handling – Handling Crashes Gracefully

When a Runtime Error occurs (like dividing by zero), the default behavior of a program is to crash immediately. This is bad for the user experience.

Exception Handling is a mechanism to “catch” these errors and handle them safely so the program can continue running or exit gracefully.

The Keywords

  1. Try: You put the “risky” code inside this block. The computer “tries” to execute it.
  2. Catch (or Except): If an error happens in the try block, the code jumps here. This block handles the error (e.g., shows a friendly message like “Something went wrong”).
  3. Finally: This block executes no matter what (whether there was an error or not). It is used for cleanup, like closing files or database connections.

try & except & finally (python)


12. Clean Coding Best Practices

Writing code that works is easy. Writing code that humans can understand and maintain is the real skill.

“Anyone can write code that a computer can understand. Good programmers write code that humans can understand.”

1. The Core Principles

  1. Proper Naming Conventions – Names should be self-explanatory.
    • Use CamelCase for variables (userAge) and PascalCase for classes (UserProfile).
  2. Indentation & Formatting – Use consistent spacing to show the structure of your code.
    • It visually separates blocks of logic (loops, if-statements), making bugs easier to spot.
    • Usually 4 spaces or 1 tab per block standard.
  3. Comments (The “Why”, Not the “What”) – Code explains what is happening. Comments should explain why you did it that way.
  4. White Space – Don’t cram everything together. Use blank lines to separate different logical sections of code, just like paragraphs in a book.
  5. Readable Code (Simplicity) – Keep it simple. Avoid clever “one-liners” that are hard to decode.
    • KISS Principle: “Keep It Simple, Stupid.”

2. The 5 Pillars of Quality Code

To ensure your software lasts, always check for these five traits:

  1. Readability: Can a new developer understand your code in 5 minutes?
  2. Modularity: Is the code broken down into small, independent functions? (One function = One task).
  3. Reusability: Are you writing the same logic twice? If yes, turn it into a function. (Follow the DRY Principle: Don’t Repeat Yourself).
  4. Testing: Have you handled edge cases? (e.g., What happens if the input is empty or negative?).
  5. Documentation: Is there a README file or API guide explaining how to use the software?


13. The Modern Developer Ecosystem

You don’t just write code; you build systems.

  • API (Application Programming Interface): Allows different software to talk to each other (e.g., using REST and JSON).
  • Databases:
    • SQL: Strict tables (MySQL).
    • NoSQL: Flexible documents (MongoDB).
  • Version Control (Git): Tracks changes in your code, allowing you to “undo” mistakes and collaborate with teams.

14. DevSecOps Special – Security & Quality

1. The CIA Triad

  1. Confidentiality: Keep data secret.
  2. Integrity: Keep data correct (unchanged).
  3. Availability: Keep the system running.

2. Secure Coding Habits

  • Input Validation: Never trust user input. Always check it to prevent SQL Injection.
  • Least Privilege: Give the program only the permissions it strictly needs.
  • Error Handling: Use try-catch blocks. Never show raw system errors to users (hackers can use them).

3. Best Practices

  • DRY (Don’t Repeat Yourself): If you write code twice, make it a function.
  • Testing:
    • Unit Testing: Test individual functions.
    • Integration Testing: Test how modules work together.
  • Code Comments: Explain why you did something, not just what you did.

15. The Practical Developer Landscape – Roles & Architecture

Writing code is just one part. You need to know where that code lives.

1. Frontend vs. Backend vs. Full Stack

  • Frontend (Client-Side): The part of the software the user sees and touches.
    • Languages: HTML, CSS, JavaScript.
    • Goal: User Experience (UI/UX).
  • Backend (Server-Side): The “brain” behind the scenes that processes logic and talks to the database.
    • Languages: Python, Java, Node.js, Go.
    • Goal: Logic, Data Management, Security.
  • Full Stack: A developer who can work on both sides.

2. Client-Server Architecture

Most modern apps work like a restaurant:

  1. Client: The browser or mobile app. It looks at the “Menu” and places an order (Request).
  2. Server: It receives the order, cooks the meal (processes logic), and hands it back.
  3. Database: Where the ingredients (data) are stored.

16. Frameworks vs. Libraries

Beginners often confuse these with programming languages.

  • Library (The Toolbox): A collection of pre-written code that you can use to save time. You control the flow.
    • You are building a table. You go to the store and buy a hammer and nails (Library). You decide when to use the hammer.
    • Example: React.js (for UI), NumPy (for Math).
  • Framework (The Skeleton): A rigid structure that provides the foundation. The framework controls the flow.
    • You buy a DIY table kit. The shape and holes are already there; you just assemble it according to the instructions.
    • Example: Django (Python), Spring Boot (Java), Angular.

17. The Programmer’s Toolkit

1. IDE (Integrated Development Environment)

You don’t write code in Notepad. You use an IDE a powerful editor that checks for errors while you type.

  • Popular Tools: VS Code (Lightweight), IntelliJ (Java), PyCharm (Python).
  • Key Features: Syntax Highlighting (coloring code), Auto-complete, and Debugging.

2. The Command Line (CLI)

Real “Gurus” don’t always use a mouse. The CLI (Terminal) allows you to talk directly to the OS using text commands. It’s faster, uses less memory, and is essential for server management and automation.


Contents
Scroll to Top