Introduction to Programming
Introduction to Programming — Comprehensive Study Notes
What is Programming?
Programming is the process of preparing a set of instructions for a computer to perform a specific task. The goal is to get the computer to complete the task without making mistakes.
A computer is fundamentally dumb — it only follows exactly what it is told. Its apparent intelligence comes from how programmers manipulate it.
Analogy: instructing a less‑intelligent friend to build a Lego set without instructions. If any piece is not specifically placed, the entire build fails. Programmers give similarly precise instructions to computers.
The computer does not understand human language. It only understands machine code — a binary language of
1s and0s that the computer can read and execute.Every instruction must be converted into binary before the computer can act on it.
Programming Languages
Programming languages act as a middleman between human instructions and machine code. They are easier for humans to learn and use than raw binary.
Low‑level languages (e.g., assembly, C) are closer to machine code. The code resembles what the computer can interpret directly.
High‑level languages (e.g., Python, Java) are more abstracted and easier for humans to read and write.
General‑purpose languages (Python, Java, C++) can perform a wide variety of computational tasks.
Specialized languages (HTML/CSS for web, RobotC for robotics) are designed for specific domains.
The power/level of a language is measured by how similar it is to machine code. Lower‑level languages produce code that more closely matches the computer’s native instructions.
Choosing a language often comes down to preference: try different languages and decide which syntax, rules, and level of simplification suit you best.
Integrated Development Environment (IDE)
An IDE (Integrated Development Environment) is a software application that provides a graphical interface for writing, running, and debugging code.
The IDE handles the conversion of human‑readable code into machine code (compilation or interpretation).
Key features include:
Built‑in error checking — detects syntax errors before running the program.
Auto‑fill — suggests frequently used words or phrases.
Project hierarchy — organizes files within a project.
Before IDEs, code was often written on punch cards and fed into computers, a slow and error‑prone process. Modern IDEs streamline the entire workflow.
Syntax
Syntax refers to the set of rules that define how code must be written in a given programming language. It is the grammar of programming.
Each language has its own syntax rules: how to end a line (e.g., semicolon in Java), how to define variables, how to structure functions.
Breaking syntax rules results in a syntax error — the program will not run.
Analogy: forgetting a comma in “Let’s eat, grandma” changes the meaning entirely. Similarly, a missing semicolon can corrupt the program.
IDEs highlight syntax errors and prevent execution until they are fixed.
Example: defining an integer variable in different languages:
Java:
int num = 3;Python:
num = 3JavaScript:
var num = 3
It is recommended to learn the syntax rules of a language before writing complex programs in it.
Console and Print Statements
The console is a text interface within the IDE that displays output from a program. It is primarily a developer tool, not meant for end users.
A print statement is a command that outputs text to the console. It exists in almost every programming language.
In Python:
print("Hello World")In Java:
System.out.println("Hello World");
Print statements are used to:
Display simple messages.
Show the result of a computation (e.g.,
print(4+3)prints7).Debug code by printing intermediate values.
Printing is a developer tool — final products use graphics or user interfaces instead of the console.
When printing multiple items together, use concatenation (the
+operator) to join strings and numbers. Example:"Game over, " + score + " was your final score"Important:
"4"(string) is different from4(integer). Trying to do math with a string causes an error.
Basic Mathematics and Strings
Computers come with built‑in ability to perform basic arithmetic.
Operators:
+(addition),-(subtraction),*(multiplication),/(division)Modulus (
%): returns the remainder of a division. Example:10 % 3 = 1. Useful for checking even/odd: ifnumber % 2 == 0, the number is even.Strings are sequences of characters enclosed in quotation marks (e.g.,
"hello").Concatenation: combining strings and numbers using
+. If you have a stringname, you can do"Your name is: " + name + ".".
Variables
A variable is a container that stores a piece of information. It has a type, a name, and a value. Think of it as a labeled box in a storage facility (memory).
Primitive Variable Types
Integer (
int): stores whole numbers between −2,147,483,648 and 2,147,483,647. No decimals.Boolean (
bool): stores onlytrueorfalse. Used in conditional statements.Float and Double: store numbers with decimal places. Double has higher precision (64‑bit) than Float (32‑bit).
String: stores a sequence of characters (text). Useful for displaying information and storing user input. Strings can be concatenated.
Char: stores a single character (e.g.,
'A'). Used for reading individual key presses.
Using Variables
Definition: creating a variable allocates memory for it. Example:
int score = 10;Empty variables: you can declare a variable without a value (e.g.,
int score;). If you try to use it before assigning a value, a NullPointerException may occur (in languages like Java).Assignment: variables can be updated throughout the program. Example:
score = 15;replaces the old value.Referencing: one variable can be set equal to another, pointing to the same memory location (two labels on one box).
Operations: integers can be added, subtracted, multiplied, divided, and modded. Strings can be concatenated with
+.
Naming Conventions
Variable names must be one continuous string (no spaces).
CamelCase is a common convention: first word lowercase, each subsequent word capitalized. Example:
playerScore.Other conventions use underscores:
player_score.Good naming improves code readability and debugging.
Conditional Statements
Conditional statements allow the program to take different paths based on conditions.
If‑Else If‑Else
If statement: executes a block of code if a condition (enclosed in parentheses) is
true. In most languages, the block is enclosed in curly braces{}.Else if: follows an
ifand is tested only if the precedingif(orelse if) wasfalse. You can chain manyelse ifs.Else: catches all cases that did not match any preceding condition. It is good practice to always include an
elseto handle unexpected values.
Example:
if (age == 10) {
// age is 10
} else if (age == 12) {
// age is 12
} else {
// age is something else
}Conditions evaluate to a boolean (
trueorfalse). Common comparisons:==,!=,>,<,>=,<=.
Switch Statement
A switch statement is a more compact alternative to many if‑else if chains when comparing a single variable against many possible values.
Syntax:
switch(variable)followed by cases.Each case uses a colon
:to start its code block and abreakstatement to exit the switch.A default case handles all values not explicitly listed.
switch(day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
default:
System.out.println("Other day");
}Arrays
An array is a list of elements of the same type. Use arrays when you need to store multiple related values that can be accessed by their position (index).
Key Properties
Indexing starts at 0: the first element is at index 0, the second at index 1, etc.
Fixed size: once an array is created, its size cannot change. You must allocate the size when you create it or populate it immediately.
Type‑specific: an array can only hold one type (e.g., all integers or all strings; no mixing).
Referencing Elements
Access an element using its index:
numbers[0]gives the first element.Accessing an index outside the array’s bounds throws an out‑of‑bounds error.
Two‑Dimensional Arrays
A 2D array is an array of arrays. Think of it as a table with rows and columns.
Indexing uses two numbers:
array[row][column]. Example:array[0][2]is first row, third column.Higher dimensions (3D, 4D) are possible but less common.
Creating Arrays
// Populate immediately
int[] numbers = {1, 2, 3, 4, 5};
// Define size, then fill later
int[] numbers = new int[5];
numbers[0] = 1;Loops
Loops repeat a block of code multiple times.
For Loop
A for loop repeats a known number of times. It has three parts:
Initialization of a counter variable (e.g.,
int i = 0)A condition that must be
truefor the loop to continue (e.g.,i < 5)An update operation (e.g.,
i++) executed after each iteration.
for (int i = 0; i < 3; i++) {
System.out.println("Hello");
}Ensures the condition will eventually become
falseto avoid infinite loops (e.g.,for (int i=10; i>0; i++)never ends becauseialways increases).
For‑Each Loop (Enhanced For Loop)
A for‑each loop iterates over each element in an array or collection without needing an index.
for (int number : numbers) {
System.out.println(number);
}While Loop
A while loop repeats as long as a condition is true. The condition is checked before each iteration.
while (condition) {
// code
}Infinite
whileloops are sometimes intentional, e.g.,while(true)for game loops that run until the user exits.
Do‑While Loop
A do‑while loop executes the code block at least once, then repeats as long as the condition is true.
do {
// code
} while (condition);Types of Errors
Errors (bugs) fall into three categories:
1. Syntax Errors
Violations of the language’s grammar rules (e.g., missing semicolon, misspelled keyword).
Caught by the IDE; the program will not run until fixed.
Usually the easiest to fix.
2. Runtime Errors
Occur while the program is running.
Example: infinite loop that never terminates, causing the program to crash.
Often caused by conditions that can never be satisfied (e.g., a loop that counts up but the condition expects a decrease).
3. Logic Errors
The program runs without errors but produces incorrect results.
Example: using
*instead of+in a calculator.Hardest to find because there is no error message; the programmer must trace the code.
Debugging Strategies
Read the error message: the IDE often points to the exact line and describes the problem.
Google the error: sites like StackOverflow have solutions for common errors.
Use print statements: print variable values at key points to see what the program is actually doing.
Use breakpoints: pause the program at a specific line and inspect variable values. Resume step by step.
Comment out sections: if you suspect a block of code, comment it out (turn it into a comment) and see if the error disappears.
Test incrementally: run the program frequently after small changes to isolate new bugs.
Backup frequently: use version control (Git, GitHub) to revert to a working version if needed.
Functions
A function is a reusable block of code that performs a specific task. Functions can be called multiple times from different places.
Arguments (parameters) are values passed into the function.
A function may return a value (e.g., an
int,String, etc.) or bevoid(returns nothing).Functions reduce clutter, improve readability, and make large‑scale changes easier.
Types of Functions
Takes arguments, returns value – e.g.,
max(a, b)returns the larger number.Takes arguments, returns nothing (void) – e.g.,
printSum(a, b)prints the sum but returns nothing.Takes no arguments, returns value – e.g.,
getPi()returns 3.1415.Takes no arguments, returns nothing – e.g.,
printStats()prints a set of values.
Creating Your Own Function
Naming: use camelCase (same as variables).
In Java: specify scope (e.g.,
public), return type (orvoid), name, and parameters.public int add(int a, int b) { return a + b; }In Python: use
defkeyword.def add(a, b): return a + bReturn handling: if the function declares a return type, every code path must return a value of that type. Use a default return at the end to cover unexpected paths.
Functions that take arguments must be called with the correct number and type of arguments.
Importing Functions (Libraries)
Importing brings in pre‑written functions from libraries into your program, saving you from rewriting common code.
A library is a collection of related functions (e.g., math library, data analysis library).
An import statement specifies the library, package, and class (or use
*to import all classes from a package).Example in Java:
import java.util.Scanner;Example in Python:
from math import factorialImport only what you need to keep the program efficient (importing an entire library when only one function is needed wastes resources).
Data Structures beyond Arrays
ArrayList (List in Python)
An ArrayList is like a resizable array. It automatically grows when more elements are added beyond its initial capacity.
Initial size is typically 10, but it expands as needed.
Useful when the final number of elements is unknown.
Dictionary (Map)
A dictionary stores key‑value pairs. Each value is accessed by its unique key, not by an index.
Keys must be unique; reusing a key overwrites the old pair.
Values can be duplicated as long as keys differ.
Example: a price list where product names are keys and prices are values.
Easy to look up:
dictionary["bread"]returns the price of bread.
Searching Algorithms
Searching algorithms find a specific element in a list and return its index (or a null/‑1 if not found).
Linear Search: check every element from start to end.
Works on both sorted and unsorted lists.
Worst‑case efficiency: O(n) (must check all n items).
Average‑case: O(n/2).
Binary Search: works only on sorted lists.
Repeatedly divides the search interval in half.
Compare the middle element with the target, then discard the half that cannot contain the target.
Worst‑case efficiency: O(log n) — much faster than linear search for large lists.
Example: finding a name in an alphabetically sorted list.
Big O Notation describes the worst‑case time complexity of an algorithm as a function of the input size n.
Recursion
Recursion is when a function calls itself. It is used to break a problem into smaller, similar subproblems.
Every recursive function must have a base case — a condition that stops the recursion (e.g.,
if (n <= 1) return 1).Without a base case, the function will call itself indefinitely, causing a stack overflow error.
How Recursion Works (The Stack)
When a function is called, its information is placed on the call stack (a data structure using LIFO — Last In, First Out).
If a function calls itself before finishing, the new call is stacked on top.
The base case is reached first, then the stack is unwound, returning values upward.
Example: sum of numbers from 1 to n
int sum(int n) { if (n <= 1) return n; else return n + sum(n - 1); }
Pseudocode (Planning Before Coding)
Pseudocode is a human‑readable outline of a program that ignores language‑specific syntax. It helps programmers plan logic before writing actual code.
Three Common Pseudocode Strategies
Flowcharts: graphical diagrams with blocks for steps and arrows for flow. Great for visualizing conditional paths.
Chronological write‑up: write step‑by‑step what the program should do in plain English.
Feature hierarchy: list the main features and sub‑functions needed. Useful for larger programs.
Pseudocode drastically reduces errors and speeds up the actual coding phase.
Choosing a Programming Language
The choice of language depends on the project and personal preference.
Low‑level languages (C, Assembly) give fine control over hardware but are harder to write.
High‑level languages (Python, Java) offer abstraction and ease of use.
General‑purpose languages (Python, Java, C++) can handle most applications.
Web development: HTML, CSS, JavaScript.
Scripting languages (JavaScript, PHP) automate tasks and are often used with websites.
Personal comfort with syntax and community support matters.
Next Steps to Continue Learning
Online resources: free tutorials on YouTube for specific languages.
Practice websites:
CodingBat – Java and Python challenges.
CoderByte – 200+ challenges in 10+ languages.
HackerRank – challenges plus job/internship opportunities.
Academic courses: AP Computer Science Principles and AP Computer Science A (for high school students), college‑level data structures and algorithms courses.
Contribute to open‑source projects on GitHub.
Build personal projects: start small and expand.
The key to mastery is consistent practice and planning. Use pseudocode, test incrementally, and embrace debugging as a normal part of the process.

Ask anything
We've read this whole study set, so questions about it get the best answers.