# Notes - Intro to Programming **Published by:** [Tony Says](https://paragraph.com/@tonysays/) **Published on:** 2022-01-30 **URL:** https://paragraph.com/@tonysays/notes-intro-to-programming ## Content Original Tutorialby freeCodeCamp.org What is a programmingProgramming language is like a interpreter between human and computerLow level and high level programming language -> the lower the more similar to machine codeHow 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:Error trackingAuto-fillProject hierarchyA syntax is set of rules specific to programming languages -> similar to grammarHow to type out certain functionsWhat to put at end of code lineHow to set up functionsError occurs when syntax is incorrect, and IDE will tell you where error is and won’t run..How to get info from computerEnter 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 usersWhat can computer do?Computer can do simple stuff i.e.arithmetic (x,/,+,-),modulus (%) reminder of a dividend equation -> can be used to determine if a number is even or oddString 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 stringWhat are variablesVariables store information that can be referenced and manipulated Each variable has a type, name, and piece of information stored insidePrimitive variablesintegers, booleans, floats, doubles, strings and charsInteger variable is whole numbers and can't hold decimal numbersBooleans is either true or falseFloats (up to 32bits) and Doubles (up to 64 bits) both store numbers w/ decimal placesStrings for displaying and store input information, also output informationChars (character) each hold one character, useful when reading one button press of one character in a string w/out using string variableVariables 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 tasksHow 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 stringgood practice is camelCase - not capitalise first word, but first letter of all words afterConditional StatementsAdds 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'sA 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.Populate first - insert elements in the array ***immediately ***Populate later - create an array w/ specific size but add elements later, note this size is finalWhen 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 loopsa Loop is a statement to run certain instruction repeatedly For Loopinteger valueconditional statementan operation to modify the integer value after the instructionsdeterminates when conditions are metinfinite loop - you must give a initial integer and operation at some point will be met. For each loop - interacting w/ entire array or listsgo through each element and carry out instructions for each valueWhile loop - continue to carry out instruction while a conditional statement is true, can be an infinite loope.g. while (x == 0)Do-while loops - instruction inside the loop will run once before checking conditional statementErrorsEveryday occurance so dont be suprised, consists of three types:Syntax errors When fail to follow programming rules and highlighted by IDE mostlyRuntime errors Don't show till you run the code, commonly caused by infinite loopwhen the computer is given some condition w/ no feasible wayt o finish, result in error and crashthink about ur code flow (i.e. loops)before running iLogic errors When no issue of the two above but result isn't what you wanted. Error is unknow.test ur code often and incrementallyDebuggingWhen 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 outMark-up the code so computer wouldn't read it, test the programme again if see if this section is the issue. Prevent ErrorsBackup code frequently, use Github or Subversions.you can pull previous versions or backtracking when error was writtenRun ur program frequently - so u dont save a backup that doesn't work and easier to figure our when u wrote the errorWhat are functionsa 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 FunctionsThere are 4 types of functions, seperated by A. Whether or not they take in arguments B. Whether or not they return valuesA Takes in argument or notArguments are variables we pass into a function for manipulation and then either:Returned back to usprinted to the consoleused in another operatione.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 workloadB returning value or notFunction 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 callsHow to import functionImport 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, classImport entire library is a waste of computing power + increase load timepython from math import factorial Java import Jave.math.factorialHow to make functionsA skeleton system for function that worksNo argument return no valueFunction name to follow CamelCase styleFirst define the function's scope public, return type public void, function name public void printStats particular to JavaA parentheses to put ur argument public void printStates()e.g. in Python def printStats():Takes in argument returns no valueRequires variables from user to pass into the function, the variables will then be used in arguments when we call functione.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 typesDon't take argument and take in valueIt must return a variable no matter what path your code takesCannot return on type of variable if you have defined function to return another typeReturn argument and take in valueAssign arguments between parenthesesdesign what you want to returnensure 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 DictionariesArraylist 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 usersDictionary stores multiple values and each value is tied to an identifier to reference it, called its "key"When referencing a value, you use its unique and dictionary will tell you the value tied to itKey must be unique to value, but same value can be stored to different keysDictionary is also “iterable” and can perform operations* or *comparisons on all values in them.Using data structureSearching 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:***worst ***case scenarioaverage number of items caseBig 0 notationLinear 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 listsworst case - runs in logarithmic time 0(log n) average case - find our item in logarithmic time 0 (log n)What is recursionRecursion 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 computeWhat 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 functionWrite-Up write what your code would behave chronologically, outline step by step what the program will accomplishavoid being bogged down w/ syntax and naming conventions, simply making note of what the program ultimate goal should beFunctionality Planning write up main features and what functions or smaller programs needed to complete those features.Choosing a languageProgramming languages are built to optimise different tasks. e.g. HTML and CSS - web developmentHTML a markup language for writing the content of a websiteCSS used to design the style of a websiteScripting 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 applicationsJava - Game/ web developmentPython - Data analysis/ scriptingC++ - application/ system programsApplication of programmingResearch the language via official website and wikiLearn the language use youtube to start introductionFind challenges so you can continue to codeCodingbetcoderbytehackerRank ## Publication Information - [Tony Says](https://paragraph.com/@tonysays/): Publication homepage - [All Posts](https://paragraph.com/@tonysays/): More posts from this publication - [RSS Feed](https://api.paragraph.com/blogs/rss/@tonysays): Subscribe to updates