Notes - Intro to Programming
January 30th, 2022

Original Tutorial

by freeCodeCamp.org


What is a programming

  1. Programming language is like a interpreter between human and computer
  2. Low level and high level programming language -> the lower the more similar to machine code

How do we write code?

We often use IDE (integrated development environment) - a place to write, run and debug codes e.g. VS Code

IDEs are good for:

  1. Error tracking
  2. Auto-fill
  3. Project hierarchy

A syntax is set of rules specific to programming languages -> similar to grammar

  1. How to type out certain functions
  2. What to put at end of code line
  3. How to set up functions

Error occurs when syntax is incorrect, and IDE will tell you where error is and won’t run..

How to get info from computer

Enter your code and use console to keep track of your progress -> a text interface interpreting output of a programme

Console is also seem as a developer tool , not usually meant to be used and interacted by users

What can computer do?

Computer can do simple stuff i.e.

  1. arithmetic (x,/,+,-),
  2. modulus (%) reminder of a dividend equation -> can be used to determine if a number is even or odd

String is text, anything enclosed by quotation marks. i.e. "4" while 4 w/out quotation mark is an integer

Concatenation is when adding strings together

Python example: print("game over, " + 4 + " was your final score." )

Good practice to add space at start/ end of your string

What are variables

Variables store information that can be referenced and manipulated

Each variable has a type, name, and piece of information stored inside

Primitive variables

integers, booleans, floats, doubles, strings and chars

  1. Integer variable is whole numbers and can't hold decimal numbers
  2. Booleans is either true or false
  3. Floats (up to 32bits) and Doubles (up to 64 bits) both store numbers w/ decimal places
  4. Strings for displaying and store input information, also output information
  5. Chars (character) each hold one character, useful when reading one button press of one character in a string w/out using string variable

Variables are useful to keep track of things e.g. user name or score; taking inputs, making variability and have it changed based on certain factors, manipulate for many tasks

How to "variables"

Create a space in memory that stores your variable name and its contents.

Blank variable is for storing info down the road e.g. maybe from user input

Variables can point to the same info/ memory storage

Assign new content to existing variables can update it e.g. RPG games stats

After the code run its course, variables are deleted in memory

#1 Rule for variables is they must be one continuous string

good practice is camelCase - not capitalise first word, but first letter of all words after

Conditional Statements

Adds variability to program based on user inputs, or else program will run the same way every time

If statement -> if true do this, otherwise do sth else e.g. braces () if true inside braces will run, else will not run

Else if statement -> only when if or (if else) is bypassed due to it being false

Else statement -> carry out after if/ else-if statement is not true

Switch statement -> input a variable then determine which "case" it is Start with a colon (:)

What are Array's

A list of something, e.g. integerts, strings or other arrays, all in an array info is related

It's critical how we reference each element inside of array, computer uses indexes which begins at 0.

  1. Populate first - insert elements in the array ***immediately ***
  2. Populate later - create an array w/ specific size but add elements later, note this size is final

When initiate array the type must be determined (String array, integer, double etc), they all have to be the same

Putting array inside an array is 2D array, similar to matrices in math/ physics 2D array use 2 numbers, that is (row, column)

What are loops

a Loop is a statement to run certain instruction repeatedly

For Loop

  1. integer value
  2. conditional statement
  3. an operation to modify the integer value after the instructions
  4. determinates when conditions are met

infinite loop - you must give a initial integer and operation at some point will be met.

For each loop - interacting w/ entire array or lists

go through each element and carry out instructions for each value

While loop - continue to carry out instruction while a conditional statement is true, can be an infinite loop

e.g. while (x == 0)

Do-while loops - instruction inside the loop will run once before checking conditional statement

Errors

Everyday occurance so dont be suprised, consists of three types:

  1. Syntax errors
    When fail to follow programming rules and highlighted by IDE mostly
  2. Runtime errors Don't show till you run the code, commonly caused by infinite loop

when the computer is given some condition w/ no feasible wayt o finish, result in error and crash

think about ur code flow (i.e. loops)before running i

  1. Logic errors When no issue of the two above but result isn't what you wanted. Error is unknow.

test ur code often and incrementally

Debugging

When error occur, read the error coz IDE will print error message FYI.

Trace to the line of code and try to fix.

Go to stackoverflow etc.

Print statement debugging - insert print to validate value from algorithm before enter into potential error prone instructions.

Just remember to delete after checking.

Breakpoint bedugging - pauses the programme when reaches ur breakpoint

Now, to resolve the bug
w/ section of code causing the error, try to commenting it out

Mark-up the code so computer wouldn't read it, test the programme again if see if this section is the issue.

Prevent Errors

  1. Backup code frequently, use Github or Subversions.

you can pull previous versions or backtracking when error was written

  1. Run ur program frequently - so u dont save a backup that doesn't work and easier to figure our when u wrote the error

What are functions

a Function is a segment of code that can be run by calling the function name, and it may do something in return.

Function can be called numerous times and in numerous places

e.g. print function - specific code has ben abstracted down to a single line.

Function can be used to recycle sections of code, for equations to allow multiple inputs, and save space.

Thousands of types of functions available u just need to import the ones u need.

Types of Functions

There are 4 types of functions, seperated by

A. Whether or not they take in arguments

B. Whether or not they return values

A Takes in argument or not

Arguments are variables we pass into a function for manipulation and then either:

  • Returned back to us
  • printed to the console
  • used in another operation

e.g. go to cafe to order food (ur function) - you want nachos and latte (ur argument);

e.g. 2 max function needs numbers as input, error occur when input strings

Without Arguments
combines instructions for ease of eye and workload

B returning value or not

Function can either return variables or not - returns a string, integer, array etc

Returning function - must be return into something, usually a variable (and printed)

Not return function - takes no arguments and returns no value

The Merits of Function
Allow making large changes easily, as each function call is just a copy of that function code, change the function will change all function calls

How to import function

Import pre-made functions to reduce workload.

Library - collection of functions that all have same theme. e.g. mech lib, data analysis lib.

An import statement is used to import library, package, class

Import entire library is a waste of computing power + increase load time

python from math import factorial
Java import Jave.math.factorial

How to make functions

A skeleton system for function that works

No argument return no value

  1. Function name to follow CamelCase style
  2. First define the function's scope public, return type public void, function name public void printStats particular to Java
  3. A parentheses to put ur argument public void printStates()

e.g. in Python def printStats():

Takes in argument returns no value

  • Requires variables from user to pass into the function, the variables will then be used in arguments when we call function

    e.g. public void producCalculator(in num1, num2) {
    
     system.out.println(num1* num2);
    } 
    

    producCalculator(5,8)returns 5x8 = 40.

  • when call a function you must pass in its designated variable types

Don't take argument and take in value

  1. It must return a variable no matter what path your code takes
  2. Cannot return on type of variable if you have defined function to return another type

Return argument and take in value

  1. Assign arguments between parentheses
  2. design what you want to return
  3. ensure no mater what path the code takes, it must return something
`public ini exampleFunction(ini num1, String str1) {
if (num1 == 5) {
  return 5;
} else {
  return 10;
}
}

ArrayLists and Dictionaries

Arraylist is A growing array which dynamically changes its size, starts w/ initial size of 10.

When you don't know the exact number of values to store e.g. database of users

Dictionary stores multiple values and each value is tied to an identifier to reference it, called its "key"

  1. When referencing a value, you use its unique and dictionary will tell you the value tied to it
  2. Key must be unique to value, but same value can be stored to different keys
  3. Dictionary is also “iterable*”* and can perform operations or comparisons on all values in them.

Using data structure

Searching algorithms - ways to look through a list of values stored in a array and find particular piece of data.

Lists can be either sorted (by order or reason) or unsorted (the opposite)

Efficiency based on two values:

  1. ***worst ***case scenario
  2. average number of items case
Big 0 notation
Big 0 notation

Linear search - start from beginning and systematically check each data point until you find what you are looking for.

worst case - check every element 0(n) average case - find our search term halfway 0(n/2)

work with both sorted and unsorted lists

Binary search - a recursive process that break the list down into smaller and smaller parts to find item faster, takes advantage of sorted lists

worst case - runs in logarithmic time 0(log n)
average case - find our item in logarithmic time 0 (log n)

What is recursion

Recursion is using functions that repeated call themselves , in instruction that occur w/in a function, one instruction will be a call to that same function e.g.

public ini myFunction(ini n)
{
instructions;
myFunctions(n+1);
} 
public ini recursiveSum(ini n) {
	if (n<=1) {
		return n;
	} else {
		return (n + recursiveSum(n-1))
	}
} 

the above essentially calculates when N = 3, returns 3+2+1 = 6.

The Stack is a data structure containing all tasks the program is instructed to complete, based on a certain method the program will carry out the tasks you give it

LIFO Structure (last in first out) mean the last item put one the stack will be the first removed from it.

if a recursive function is created w/out a reachable base case, processes will continue adding up the stack, causing a stack overflow error and program crash.

Recursion is useful because it breaks down large problem into smaller pieces to compute

What is Pseudocode?

Most programmer think about code more often than actually writing it. Simply roll-up ur sleeve and write code doesn't guarantee good program.

Pseudocode simply means plan our the code before writing.

  • Flowcharts - think through the process of a particular function
  • Write-Up write what your code would behave chronologically, outline step by step what the program will accomplish

avoid being bogged down w/ syntax and naming conventions, simply making note of what the program ultimate goal should be

  • Functionality Planning write up main features and what functions or smaller programs needed to complete those features.

Choosing a language

Programming languages are built to optimise different tasks. e.g. HTML and CSS - web development

  1. HTML a markup language for writing the content of a website
  2. CSS used to design the style of a website

Scripting language has many commands for you run w/out being complied, easier to port between operating systems. e.g. php, javascript

General purpose languages has wide variety of use case and applications

  1. Java - Game/ web development
  2. Python - Data analysis/ scripting
  3. C++ - application/ system programs

Application of programming

  1. Research the language via official website and wiki
  2. Learn the language use youtube to start introduction
  3. Find challenges so you can continue to code
    • Codingbet
    • coderbyte
    • hackerRank
Subscribe to Tony Says
Receive the latest updates directly to your inbox.
Verification
This entry has been permanently stored onchain and signed by its creator.
More from Tony Says

Skeleton

Skeleton

Skeleton