# Notes - Intro to Programming 

By [Tony Says](https://paragraph.com/@tonysays) · 2022-01-30

---

Original Tutorial
=================

by freeCodeCamp.org

[![]({{DOMAIN}}/editor/youtube/play.png)](https://www.youtube.com/watch?v=zOjov-2OZ0E)

* * *

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

![](https://storage.googleapis.com/papyrus_images/f44ccb43b8c6698126c1948c9ffbe1553eeb3d081b0d60bbc19fdc650adc1b8e.png)

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

![](https://storage.googleapis.com/papyrus_images/19aa46cc9c9c6370a4353589b3c64774c8dee7b770e3f147b39ccc0315ef8d67.png)

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 (:)

![](https://storage.googleapis.com/papyrus_images/51ccf9fb23d01bd8aa68d69eb243adbd35c8cc7840cd3d89fc60ab1594c42878.png)

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 _i_**_ndexes which begins at 0._**

![](https://storage.googleapis.com/papyrus_images/cf64ff52f9b963126a87327510b06a4927b9be2ef6ba0dc04688b7a9d156e776.png)

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 t_ype_ **_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

![](https://storage.googleapis.com/papyrus_images/5e719f9fa6a934c14f42418a17a54346b9b42c67888029db56ad32fcb876868f.png)

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

3.  **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

![](https://storage.googleapis.com/papyrus_images/87bb3a27c24f8bf82310e928aea2661e67993c5cf6271e9281190f44ae95d9ec.png)

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

2.  **_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_**

![](https://storage.googleapis.com/papyrus_images/2e4926d806dc2a3d6f24fc03cadd5bf7a72a82717e0916cfe31b92bdc599b8ef.png)

### 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

![](https://storage.googleapis.com/papyrus_images/cbfca33074df4cb58ad316b6843432222767ab30a7a60bd807d73748cd742331.png)

### 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)

![](https://storage.googleapis.com/papyrus_images/5352a62f43c3fa67d03a73ef4ce9acdedffdb4d8faef3accea9cbf5f77c62a45.png)

**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](https://storage.googleapis.com/papyrus_images/adeb82a44a5848f1af014131b9587160e6a480f1c8d5ecbd72afd281f96f9ce0.png)

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.

![](https://storage.googleapis.com/papyrus_images/bc4eca0fc56f5cc03305a7ad403ca25757ee8dcd4272d4031488ce9dad36964a.png)

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.

![](https://storage.googleapis.com/papyrus_images/31c0a24cb1a28212df930516ba84f67ed8e39aa17e9fcae433141ee9616961ca.png)

*   **Flowcharts** - think through the process of a particular _function_
    

![](https://storage.googleapis.com/papyrus_images/83febbbae6d0c26792afae98850ddc854af70b5967ce3dd0b2f28a157b15db10.png)

*   **Write-Up** write what your code would behave _chronologically_, outline step by step what the program will _accomplish_
    

![](https://storage.googleapis.com/papyrus_images/f3c74f0246425070eb269ce09804e245f2fc18a795442c9ab8d7eeb6f18d427f.png)

> 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
-------------------

![](https://storage.googleapis.com/papyrus_images/b03f7139a96369beed8b1224327645d902dc565a7a963169dd84600662b37b97.png)

_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 complie_d**, 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

---

*Originally published on [Tony Says](https://paragraph.com/@tonysays/notes-intro-to-programming)*
