programming overview
programming overview
Programming Languages
Programming languages are tools that allow programmers to write
instructions for computers in a way that's easier for humans to
understand. They act as an interpreter, translating human language into
machine code.
General-
Python, Java Can perform a wide variety of computational tasks.
purpose
Specific- Robot C, Designed for specific purposes (e.g., robotics, web
purpose HTML/CSS development).
Closer to machine code; more difficult for humans
Low-level Assembly, C
to read and write.
Further from machine code; easier for humans to
High-level Java, Python
read and write.
Writing Code
Page 1
Created by Turbolearn AI
You can't just type words into a text document and expect the computer to
understand. You need an IDE (Integrated Development Environment).
IDEs
IDEs (Integrated Development Environments) significantly simplify the coding
process. Historically, code was written on punch cards, a slow and cumbersome
method. IDEs provide a streamlined approach, making programming much easier.
The image displays a Java IDE example, showing the code editor and the console for
output. IDEs are essential tools, used in almost all programming projects. They allow
for smooth code writing and compilation, eliminating compatibility concerns.
Different languages have unique syntaxes. While some share similarities, each
language possesses unique quirks. Ignoring syntax rules leads to errors, similar to
misinterpreting a sentence due to grammatical errors.
For example, initializing a variable (a concept not yet covered, but relevant to the
example):
Page 2
Created by Turbolearn AI
Code
Language Explanation
Example
The comma example: "Let's eat, Grandma" versus "Let's eat Grandma". A small
mistake with significant impact on meaning applies similarly in programming. A
missing semicolon or misplaced character can prevent code execution.
The Console
After writing and running code, you'll need to see the results. Programmers use the
console, a text interface, for various purposes. As previously shown, the console is a
key component of an IDE.
Its primary function is to display program output using print statements. These
commands print text to the console.
Print statements are vital for observing program output. For example, calculating 4 +
3: Instead of just performing the calculation, use a print statement to display the
result (7) on the console.
The print statement's implementation varies across languages. Java, for example,
offers variations with/without line breaks and optimized versions. While the core
function remains, syntax and nuances differ between languages.
Page 3
Created by Turbolearn AI
Beyond these, the modulus operator (%) provides the remainder of a division. For
example:
10 mod 3 = 1
The modulus operator returns the remainder after division. It's useful for
determining if a number is even or odd (even numbers have a remainder of
0 when divided by 2).
For example, to print "Game Over 4 was your final score", you can concatenate:
Page 4
Created by Turbolearn AI
The difference between "4" (a string) and 4 (an integer) is crucial. Using a
string where a number is expected will cause errors.
Variables are containers for information that a programmer can use and
reuse throughout their program. They are fundamental to programming.
Think of it like having a storage facility. Each variable is a box with a label
(the name) and contents (the stored information).
Page 5
Created by Turbolearn AI
You can create a variable without immediately assigning it a value, leaving the space
in memory for later use. However, trying to use a variable without assigning a value
will result in a NullPointerException.
You can also make a variable point to the contents of another existing variable. This
saves space because it doesn't create a new memory location. Instead, it creates
another label pointing to the same memory location.
Variables are essential for clean, efficient code. Understanding variable types and
how to use them is crucial for programming.
Variable Updates
Things that we know are going to have the same value are called variables.
Variables can be updated throughout your code.
For example:
Let's say you had an age variable with the integer value 17.
After celebrating a birthday, you want to update your age to 18.
You would reference the variable and set it equal to the new integer value (18).
This is like having a box labeled "age" with a piece of paper reading "17" inside. You
take out the paper, erase "17", replace it with "18", and put it back in the box. This
allows easy updating of variable contents as things change dynamically.
Another example: In an RPG, your character might have stats like attack, defense, and
mana. As the game progresses, you continuously update these variables to make the
player more powerful. You don't create new variables; you update the existing ones.
Page 6
Created by Turbolearn AI
Variable Arithmetic
You can add, subtract, divide, multiply, and use the modulus operator on integer,
float, and double variables.
Example: In a calculator app, if you store the first number entered as num1 and the
second as num2, you can multiply num1 and num2 and store the result in a new variable
called result. Each time the program runs, the user can input new numbers, which
will be assigned to num1 and num2, and a new result will be calculated.
This approach keeps track of the numbers and the operations, which is
useful.
You can't subtract, multiply, divide, or use the modulus operator on strings, but you
can add them. For example:
Programmers use different naming conventions. We'll use camel case in this lecture:
Example: playerScore
Page 7
Created by Turbolearn AI
Conditional Statements
Conditional statements change the code's path based on conditions. We'll use red
lines to denote paths not taken and green lines for paths followed.
if (condition) {
// Code to execute if the condition is true
} else {
// Code to execute if the condition is false
}
The condition is evaluated as a boolean (true or false). If true, the code inside the
curly braces runs; otherwise, it's skipped.
Note: While curly braces ({}) are used in many languages, some (like
Python) use colons and whitespace.
Example:
if (age == 10) {
// Code to run if age is 10
} else if (age == 12) {
// Code to run if age is 12
} else {
// Code to run if age is neither 10 nor 12
}
If age is 10, only the first code block runs. If age is 12, only the second code block
runs. If age is neither 10 nor 12, only the third code block runs.
Conditional Statements
Conditional statements allow your program to execute different instructions based on
whether a condition is true or false.
Page 8
Created by Turbolearn AI
If Statement
The basic structure of an if statement is:
if (condition) {
// Code to execute if the condition is true
}
If the condition evaluates to true, the code inside the curly brackets {} is
executed. Otherwise, it's skipped.
Else If Statement
else if statements are used to check additional conditions if the preceding if
or else if statements are false.
if (condition1) {
// Code if condition1 is true
} else if (condition2) {
// Code if condition1 is false and condition2 is true
}
Else Statement
An else statement provides a block of code to execute if none of the preceding
if or else if conditions are true. It's a catch-all for cases not covered by the
other conditions.
if (condition1) {
// Code if condition1 is true
} else {
// Code if condition1 is false
}
Switch Statement
Page 9
Created by Turbolearn AI
Switch statements use a colon (:) to signify the start of a case and a
break statement to end it, unlike if-else statements that use curly
brackets {}.
Arrays
Arrays are used to store collections of data of the same type.
Array Indexing
Arrays are zero-indexed. This means that the first element in an array is at
index 0, the second element is at index 1, and so on.
Arrays
Page 10
Created by Turbolearn AI
Important Note: Array sizes are fixed upon initialization. You cannot
increase the size of an array after it's created. Think of it like a bookshelf—
once you've arranged books, adding more requires rearranging everything.
You can create a new, larger array and copy the contents, but the original
array’s size remains unchanged.
You must specify the data type (e.g., string, integer) of an array when you
declare it. You cannot mix data types within a single array.
Multi-Dimensional Arrays
Arrays can be nested to create multi-dimensional arrays. A 2D array (array of arrays)
is like a matrix or a Google Sheet.
Example:
[
["Clint", "Bob", "Alice"],
["Chris", "Sarah", "Mallory"]
]
3D arrays (arrays of arrays of arrays) are also possible but are beyond the
scope of this lecture.
Loops
A loop repeatedly executes a block of code. This is far more efficient than copying
and pasting the same code multiple times.
For Loops
Page 11
Created by Turbolearn AI
A for loop iterates a specific number of times. The syntax varies by programming
language, but generally includes:
Example:
For Loop
A for loop iterates through elements in an array or list. It executes a set of
instructions for each element. This is useful for reading elements and performing
operations on them.
For example: A for loop can iterate through an array and print the value of each
location.
Page 12
Created by Turbolearn AI
Similar to a for loop, a for each loop (or "for in" loop in Python) iterates through each
element in an array or list, carrying out a set of instructions for each value.
While Loop
A while loop continuously executes instructions as long as a given conditional
statement is true. This condition can be based on variable values, numerical
comparisons, or equality checks. Unlike for loops, the loop isn't contained within one
statement; it extends and runs until the condition becomes false. While loops can run
infinitely if the condition never evaluates to false.
Do While Loop
A do while loop is similar to a while loop, but it executes its instructions at least
once, even if the condition is initially false. After the first execution, it behaves like a
standard while loop.
Example: The condition within the loop runs once, then continues to run if
the condition is still met.
Errors in Programming
Program errors, often called bugs, fall into three categories:
Syntax Errors
Syntax errors occur when programming rules (syntax) are broken, making
the code uninterpretable by the computer. Examples include: missing
semicolons, incorrectly defined variables, or misspelled keywords.
Easy to fix: IDEs usually highlight syntax errors and suggest fixes. They prevent
code execution until corrected.
Similar to grammatical errors in writing.
Page 13
Created by Turbolearn AI
Runtime Errors
Runtime errors appear when the code runs but encounters a statement
the computer cannot compute in a reasonable timeframe.
Most common: Infinite loops. Like telling your friend to wait until Michael Scott
makes a specific joke on Friends. The condition for loop termination is never
met.
Avoidance: Carefully plan code flow, especially loops, to ensure all statements
are completable by the computer.
Logic Errors
Logic errors occur when the code runs without syntax or runtime errors,
but produces an unexpected result. The code functions, but doesn't
perform the intended task.
Syntax Errors
Syntax errors occur when you violate the rules of the programming
language's grammar. These are usually caught by the compiler or
interpreter before the program runs.
The IDE will often point to the line number where the error occurred.
Read the error message carefully and try to understand the problem.
If you don't understand the error message, search for it online (e.g., on Stack
Overflow).
Runtime Errors
Page 14
Created by Turbolearn AI
Runtime errors occur while the program is running. These errors often
cause the program to crash.
Similar to syntax errors, the IDE might provide information about the line where
the error occurred.
Consult online resources to find solutions.
Logic Errors
Logic errors are harder to find. They occur when the program runs without
crashing, but produces incorrect results. The program does what you told
it to do, but that wasn't what you wanted it to do.
These errors do not typically result in error messages from the compiler or
interpreter.
You will need to use debugging techniques to find and fix these errors.
Page 15
Created by Turbolearn AI
Preventing Errors
Frequent Backups: Regularly save your code to prevent data loss in case of
catastrophic errors. Version control systems (like Git) are highly recommended
for this task.
Frequent Testing: Run your program often to catch errors early. If you test
frequently, it's much easier to locate the source of an error because fewer lines
of code have been added since the last successful test.
Functions in Programming
What is a Function?
Page 16
Created by Turbolearn AI
A function is a reusable block of code that performs a specific task. It's like wrapping
a gift—you put code inside, give it a name, and then "unwrap" it (call it) whenever
you need that code to run.
Functions are essential for organizing and reusing code. They improve
readability and reduce redundancy.
Function Arguments
Arguments are values passed into a function. They act as inputs, allowing the
function to perform different operations based on the provided arguments.
Page 17
Created by Turbolearn AI
Note: Functions that return values require you to store or use that
returned value explicitly; otherwise, the returned value is lost. A function
with no return value still executes its code, but doesn’t send anything
back to the calling point.
Combining Features
You can combine these features: a function might accept arguments and return a
value, or it might accept no arguments but still return a value. The possibilities are
versatile, allowing for robust and flexible code.
Page 18
Created by Turbolearn AI
1. Functions that take arguments and return a value: These functions accept
input and produce output. For example, a function that adds two numbers
would take two numbers as arguments and return their sum.
2. Functions that take arguments but do not return a value (void functions):
These functions perform actions but don't produce a value that can be assigned
to a variable. print() statements often fall under this category. They are useful
for condensing multiple print statements.
3. Functions that do not take arguments but return a value: These functions
perform calculations or actions based on internal data and return a result.
4. Functions that take no arguments and return no value: These are the simplest
type of function. They perform a specific task without needing input or
producing output.
Importing Functions
Importing functions allows you to use pre-written code. This is analogous to buying
materials from a home improvement store instead of making everything from scratch.
Import Statement: Most languages use an import statement with three parts:
Page 19
Created by Turbolearn AI
1. The library.
2. The package within the library.
3. The specific class from the package.
You can also use * to import all classes from a package, but it's generally more
efficient to import only the necessary classes.
Example (Java): import java.util.Scanner; imports the Scanner class from the util
package within the java library.
Example (Python): from math import factorial imports only the factorial function
from the math library. Importing specific functions is generally more efficient for larger
programs. If you need additional functions later, you can import them as needed.
The lecture notes will continue to cover how to implement these function types in
more detail.
Page 20
Created by Turbolearn AI
A void function is a function that does not return any value. A void
function is similar to the print_stats function discussed earlier.
Arguments must match the defined types. You cannot pass a string when an
integer is expected.
Page 21
Created by Turbolearn AI
Specify return type (e.g., int, String, etc.) before the function name in Java.
Python infers this from the return statement.
Every code path must have a return statement. Failing to do so causes an
error.
The returned variable type must match the function's defined return type.
A useful technique is to have a unique return statement at the end as a
placeholder in case something is wrong in your function. It will help you catch a
bug.
When you create an array, you specify its size, which is fixed. You cannot
increase the size later.
To access elements, you use an index, starting from 0. The first item is at index
0, the second at index 1, and so on.
Accessing an index outside the array's bounds causes an error.
Multi-dimensional arrays are arrays of arrays (e.g., an array containing arrays,
which themselves contain arrays). These are useful for organizing large
amounts of related data.
Array Lists
Page 22
Created by Turbolearn AI
Array lists (or just "lists" in Python) are like arrays, but they can grow dynamically.
An array list initially has a size (e.g., 10 in Python), but if you add more
than 10 elements, the array list automatically increases its size to
accommodate the new values. This avoids the size limitations of arrays.
Dictionaries
Dictionaries store values using key-value pairs.
Think of a dictionary like a set of labeled boxes. Each box contains a value,
and each box has a unique key to identify it. To get the value, you use the
key.
Key Value
"apples" $1
"milk" $2
"bread" $3
Searching Algorithms
Searching algorithms are methods to find a specific piece of data in a list (like an
array). The goal is to find the data as quickly as possible.
They typically return the index of the data in the list. This index can then
be used to access, modify, or update the data. Many applications (like
hospital patient databases) rely on fast searching algorithms.
Searching Algorithms
Page 23
Created by Turbolearn AI
Linear Search
A linear search iterates through a list, comparing each element to the target
value.
It's simple to implement but inefficient for large lists.
Worst-case scenario: O(n) - checks the entire list.
Average case: O(n/2) - checks roughly half the list.
Works with both sorted and unsorted lists.
Think of searching for your name on a class roster: you start at the
beginning and check each name until you find yours (or reach the end).
Binary Search
Binary search is significantly more efficient than linear search but requires a
sorted list.
It works by repeatedly dividing the search interval in half. If the target value is
less than the middle element, the search continues in the lower half; otherwise,
it continues in the upper half. This process continues until the target value is
found or the search interval is empty.
Worst-case scenario: O(log2 n) - much faster than linear search for large lists.
This is because with each step we are effectively halving the amount of
elements we have to search.
Imagine searching for a word in a dictionary. You don't start from page
one; you open to the middle and check if your word comes before or after.
You repeat this process, narrowing down your search until you find the
word.
Page 24
Created by Turbolearn AI
Recursion in Programming
Recursion: Functions that repeatedly call themselves. One of the
instructions within the function is a call to that same function.
Page 25
Created by Turbolearn AI
If a recursive function lacks a base case, it leads to an infinite loop. The stack
continuously grows until a stack overflow error occurs, causing the program to
crash. This is analogous to endlessly adding chores without ever completing one.
Page 26
Created by Turbolearn AI
Optimizing systems
Designing app features
Programming game mechanics
Good programs are not created by simply starting to write code. Careful
planning is essential.
Pseudocode (pseudo meaning "not real" and code meaning "code") helps you
focus on the program's logic without worrying about syntax or variable names.
It's similar to outlining an essay.
Pseudocode Strategies
Flowcharts
Flowcharts graphically represent a function's flow. They use blocks for
conditional statements and loops, connected by arrows to show the
different paths.
Chronological Write-Up
This method involves writing down the program's steps chronologically,
focusing on what the program should do rather than the specific code.
Page 27
Created by Turbolearn AI
Example: An app that takes two numbers and divides them. The pseudocode
would outline prompting for the first number, then the second, performing the
division, and returning the result.
Useful for preventing oversight of algorithm parts or necessary functions.
Feature-Based Outline
This strategy outlines the main user features and the functions needed to
implement them.
Example: A banking interface with options to create a new account or log into
an existing one. Logged-in users can withdraw, deposit, take out loans, or pay
back loans.
Similar to flowcharts, but at a higher level of abstraction. Useful for preventing
last-minute additions.
Page 28
Created by Turbolearn AI
Language
Language Uses
Category
Tutorials: Watch introductory series (like the one you're currently watching)
and subsequent tutorials to grasp syntax and rules.
Practice: Use websites like Codingbat (free Java and Python coding challenges)
to hone skills and learn shortcuts. Overcoming "programmer's block" can
involve finding inspirational projects.
Page 29
Created by Turbolearn AI
Data Structures
Game Design
Data Science
Further Exploration
GitHub Contributions: Contribute to open-source projects to collaborate with
others and gain experience.
Personal Projects: Develop your own projects to explore your interests and
build your portfolio. Collaboration with others is also possible.
Page 30