#Fundtimentals of programming
###What is programming?
- A computer program is a set of instructions.
- A sequence of a set of instructions.
The art of programming is to take a larger idea and break it apart into smaller ideas.
Computers will do exactly as you tell them, so you need to make sure your instructions are right.
Statements - Sentences. Use words, numbers, punctuation to express one thought or one individual peice.
Understanding the rules of each language is called syntax.
the ability to take the idea in your head, break it apart into individual peices, and knowing how to write these peices in the programming language youre using at the time.
#What is a programming lanaguage
###Why are there so many languages?
There is a universal language. Its called machine code, or machine language.
Some languages are close to machine code. They are called Assembly languages.
Some languages arent close to machine code. They are called high-level languages, and dont worry about writing for individual hardware.
Programming for us is all about the source code. We will write the source code, and then translate that source code to machine code, so the computer can execute our instructions.
Understanding 3 things:
- How to write it. Where do we start typing this.
- How this source code will be converted to machine code.
- How do we execute this source code.
#Writing source code
###Compiling and interpreted languages
Compiled - You write source code, and use a compiler, that creates machine code packaged into an executable file. This file can then be executed on the users computer without giving them the source code.
Ex. C, C++, Objective-C
Interpreted - Doesnt compile source code, just sends or creates a copy. So users computer goes through source code line by line and is executed on the fly.
Ex. php, javascript
Intermediate approach - A little bit of both. We can compile part of the way (intermediate language) and when the user executes the compiled code, it would run the rest of the interpreted code.
Ex. java, c#, vb.net, python
#Creating your first program in javascript
Computer programs are all about input and output
ex.
var name = prompt("What is your name?");
alert("Hello, " + name);
requesting input - Using javascript prompt to ask "What is your name?"
###Working with variables
Keeping track of individual peices of data.
Variables are containers - carving out a bit of memory where a variable and value can be stored
var year;
var customerEmail;
var todaysDate;
Setting the variable in javascript -
var year;
year = 2011;
var year = 2011;
Some languages after setting a variable, you need to tell it what type of variable you just set.
###Strong/Weak/Duck-typed languages
In many programming languages you dont just give a variable a name but you must also say exactly what type of information is stored in that variable.
- Integer : whole number
- Floatpoint point : number value after decimal
- Singlecharacter
- Multi-Characters
- String
- Boolean : true or false.
In strictly typed languages, you have to choose a datatype and once you choose, youre not allowed to change it.
Can create as many as you want, and must be one particular type. can cause program to crash if you
javascript - weakly typed generic variables - empty container - any type of values are assigned after
assignment operator to assign variable
var myVariable;
myVariable = "Hello";
myVariable = 200;
myVariable = true;
myVariable = false;
###Working With Numbers ###Working with strings ###Working with operators
Arithmetic operators:
-
addition
-
subtraction
-
multiplication
-
subtraction
var a = 100; var b = 50; var result = a + b;
Operator precidence:
Same as basic math rules.
result = 5 + 5 * 10;
Will complete multiplication first based on precidence.
score = score + 10;
Add a value to an existing variable is so common there is a operator for it.
+=
score += 10;
This means take whatever variable that was set to score and add it to ten. This will result as new score. Also operators for other common arithmetic
+=
-=
*=
/=
Increment/Decrement - Just adding one (*IMPORTANT)
a = a + 1;
a += 1;
a++; (proper way to write increment)
Add one to the variable a
Same idea
a = a - 1;
a -= 1;
a--;
###Properly using whitespace
#Building with the if statement
Conditional code: sometimes runs sometimes doesnt based on what happens before it.
if statement in js:
if (someconditionistrue) {
do whatever code goes between here.
}
() = parenthesis [] = brackets {} = braces Always found in pairs.
if ( a > 50 ) {
alert("It's True!!!");
//etc...
}
REMEMBER Whatever is found inside of the parenthesis must always evaluate to either TRUE or FALSE. ALL CONDITIONS MUST BOIL DOWN TO EITHER TRUE OR FALSE
In javascript, you often want to check equality. This is done by using double equals
if ( a == 50 ) {
alert("This is true!");
}
(if the variable a is equal to 50 then follow the code block otherwise known as the set of instructions inside of the curly braces)
In javascript there is also a special way to check equality, which is the triple equals sign.
if ( c === 99 ) {
alert("It's True!");
}
Never use single equals sign to check equality. Single equals sign is always ASSIGNING a variable to something.
Checking inequality is done by exclaimation point and equals sign.
if ( d != 50 ) {
alert("It's not equal!");
}
if d does NOT equal 50, follow the code block, otherwise known as the set of instructions inside of the curly braces
Blocks can be nesting inside of each other if necessary.
Simple example
var a = 5;
var b = 10;
if ( a < b ) {
alert("Yes, a is less than b");
}
if ( a == b ) {
alert("Yes, a is equal to b");
}
#Working With complex conditions
if balance is greater than zero
var balance = 5000;
if ( balance >= 0 ) {
alert("The balance is positive");
if ( balance >= 10000 ) {
alert("The balance is large");
} else {
alert("The balance is negative");
}
#Setting comparison operators
Assignment instead of equality is a mistake every programmer will make at some point
var a = 5;
var b = 10;
if ( a = b ) {
// Always True because instead of checking for equality of variables, it is setting a to b, so it always outputs as true because a now b...
}
//Should be written as:
if ( a == b ) {
//Only true when a is EQUAL to b. If a is not equal to b, it will never run! Hard to debug! REMEMEBER this!
}
Remember: single equals sign is the assignment operator = double equals sign is the equality operator == javascript and php also have the strict equality operator or ===
var a = 123;
var b = "123";
//equality check
if ( a == b ) {
alert("Yes, they ARE equal");
} else {
alert("No, they AREN'T equal");
}
This will return "Yes, they ARE equal" because javascript is not a strictly typed language. It reads the double equals and assumes you meant the integer to be a string, or a string to be an integer.
If you want it to actually notice the difference between an integer and a string, if they are otherwise the same value, then youd want to use the strict equality operator, or ===
ex.
var a = 123;
var b = "123";
if ( a === b ) {
alert("Yes, they ARE equal");
} else {
alert("No, they ARENT equal");
}
summary:
if ( a == b ) {
//Is equal to
}
if ( a != b ) {
//Not equal to
}
if ( a === b ) {
//Strict equality
}
if ( a !== b ) {
//not strictly equal
}
if ( a > b ) {
//a is greater than b
}
if ( a < b ) {
//a is less than b
}
if ( a >= b ) {
//a is greater than or equal to
}
if ( a<= b ) {
//a is less than or equal to
}
###Logical and / or
if ( a === b && c === d ) {
//a has to be strictly equal to b AND c has to be strictly equal to d
}
if ( a === b || c === d ) {
//a has to be strictly equal to b OR c has to be strictly equal to d
}
To make it more clear you often include each set inside their own set of parenthesis
if (( a > b ) && ( c < d )) {
// if a is greater than b AND if c is greater than d
}
Using the switch statement (instead of if) some languages is called the select or select case statement. (Ability to list in one place several situations or cases in one readable format)
var grade = "Premium";
switch ( grade ) {
case "Regular":
alert("It's $3.15");
break;
case "Premium":
alert("It's $3.35");
break;
case "Diesel":
alert("It's $3.47");
break;
default:
alert("That's not a valid grade");
}
You must use the break statement in a switch statement, otherwise the code continues to run, without triggering the alert, because it hasnt been given the option to leave the function.
###Breaking your code apart
When you start adding too much code together, to keep it reable, we break the code into small peices. In a lot of languages, when we break these peices up, they are called functions.
in js, the syntax looks like this:
function myFunction (you can pass other data to be used in the function here) {
alert( "Hey!" );
myOtherFunction(); (*You can pass other function inside of this function*)
}
myFunction();
define your functions BEFORE you call any of your functions. Makes for much more readable code.
###Setting parameters and arguements:
function addThreeNumbers(a,b,c) {
var result = a + b + c;
alert(result);
}
addThreeNumbers(5,10,15);
addThreeNumbers(500,100,400);
addThreeNumbers(7,-2323,500);
when you are defining a function, the a b and c inside of the parenthesis* are called PARAMETERS.
function addTwoNumbers(a,b,c) {
//Code for addTwoNumbers function
}
when you are calling the function, the values assigned to a b and c are called your ARGUEMENTS.
function addTwoNumbers(a,b,c) {
//Code for addTwoNumbers function
}
addTwoNumbers(a,b,c); //ARGUEMENTS (a,b,c) when it is called
These terms are interchangable, but they do have this formal meaning.
You can pass parameters into a function, but you can also pass results back out of a function. You do this by RETURN You need to pass return variableName;
function addTwoNumbers() {
var result = a + b;
return result;
}
addTwoNumbers(5,10);
addTwoNumbers(500,100);
addTwoNumbers(1000,5000);
As soon as you say return, you are LEAVING the function, so dont write anymore code inside of the function, unless youre meaning to leave the function.
When this function is ran in the browser, NOTHING visible will happen, although it is passing all three of the arguements into the function. This is happening because it has no where to place the result. IT IS STILL GETTING THE RESULT, just not doing anything with it.
function addThreeNumbers ( a, b, c ) {
var result = a + b + c;
return result;
}
var x = addThreeNumbers(1, 2, 3);
alert( x );
var y = addThreeNumbers(-1, -2, -3);
alert( y );
var z = addThreeNumbers(10, 20, 30);
alert( z );
The example below
var name = prompt("What is your name?");
takes in one arguement, whatever is returned from that is what we are going to accept into the variable name.
Both passing information in as parameters, passing in information to be used as an arguement, and doing something with those returned values is a VERY core fundimental in programming.
#Understanding variable scope
function simpleFunction() {
//lots of code
var x = 500;
//lots of code
alert(x);
}
if you create a function and define a variable inside that function, that variable is only available inside of that function. This is because of variable scope. Simply means, where is that variable visible.
for example
function simpleFunction() {
//lots of code
var x = 500;
//lots of code
alert(x);
}
simpleFunction(); //This will run through the function and pop up the alert box that says 500
alert(x); // if you call the function alert on x, because it is outside of the scope of the variable x, it will return undefined.
Undefined means, I don't know what this variable is because it hasn't been defined for me out here...
These variable are known as local variables. This means they are only available inside of the curly braces where they are defined.
If you need to have the contents available outside of the function there are a few ways to do it. You COULD return the value using the return keyword as we saw above (not the way you should do it)
The other way to do it (the common way) is to declare the variable outside of the function. This is referred to as a global variable and can be used anywhere INSIDE or OUTSIDE of any function. We want to be careful NOT to use var INSIDE of a function though, just the variable and what you want to set it to. EX.)
var x;
function simpleFunction() {
//Lots of code
x = 500;
//lots of code
alert(x); // This will show the alert box with the value 500 displaying!
}
simpleFunction();
alert(x);// This will also show the alert box with the value 500 displaying!
- Used both inside and outside the function!
- Having a function call itself is called recursive
#Introduction to iteration
###Programming buzzword for a loop
The only issue with looping is setting conditions on when to stop
WHILE LOOP
var a = 1;
while ( a < 10 ) {
alert( a );
} // this is an infinite loop because it won't ever increment to ten...
var a = 1;
while ( a < 10 ) {
alert(a);
a++;
}
Most basic type of loop. It alerts for a, and each time a is alerted, it increments up, by adding 1 to a. It will increment until it gets to ten and loop one more time, until the function runs as false.
Writing a while statement/loop
var amount = 0;
//create the index
var i = 1;
//check the condition
while ( i < 10 ) {
amount = amount + 100;
//increment the index
i++;
}
alert("The value is:" + amount);
This is the most common mistake with while loops. The result from this will be 900 when you reach the end of the loop, but we thought if we want to add 100, 10 times, we would have 1000.
There are two solutions, but we can't apply both. One or the other. Because i is set to one, it starts from one and runs to 10. This is only 9 increments. 9 * 100 = 900.
The other reason is because, starting at 1, it will run for 1 - 9, and stop at 10, because 10 is not less than 10. This could be solved by setting i <= 10 (less than or equal to)
As you can see, if we run change both, i = 0, and i <= 10, we will end up with 1100 being output. This is because it will run 11 times, for 0 1 2 3 4 5 6 7 8 9 10. This is eleven iterations of the loop.
#CLEANING UP WITH STRING concatenation Javascript is a weakly typed language, meaning our variables can hold numbers, strings, booleans. But javascript still cares.
###Addition vs concatenation
Addition
var foo = 5;
var bar = 5;
alert(foo + bar); //10
concatenation
var foo = "5";
var bar = "5";
alert(foo + bar); //55
Both together
var foo = 5;
var bar = "5";
alert(foo + bar); //55 - one is a string
The one that is a string takes precident over the one that is not a string. Javascript guesses you meant for the other to be a string as well. Concatenation occurs
One that doesn't make much sense
var foo = 5;
var bar = "b";
alert(foo * bar); //NaN (not a number)
NaN is something that just doesn't make sense. NaN is useful because sometimes we want a variable to be a number, but aren't
var foo = "55";
var myNumber = Number(foo); // Make it a number and store the result in the myNumber variable.
if ( isNaN (myNumber) ) {
alert("It's not a number!");
}
If you want to see if it IS a number you want to negate the function
if ( !isNaN (myNumber) ) {
alert("It Is a number!");
}
This asks if myNumber is NOT NOT a number.
###FINDING PATTERNS IN STRINGS: String properties
var phrase = "This is a simple phrase.";
alert( phrase.length );
###String Methods
var phrase = "This is a simple phrase.";
alert( phrase.toUpperCase() );
Strings are quite powerful, they allow you to do a lot with them. More complicated than numbers because of cases.
var st1 = "Hello";
var st2 = "hello";
str1 != str2
if ( str1.toLowerCase() == str2.toLowerCase() ) {
alert("Yes, equal");
}
###String methods - indexOf
var phrase = "We want a groovy keyword.";
var position = phrase.indexOf("groovy");
10 - starting at zero, the first character of the word groovy will return 10. It returns -1 if the term is not found
if ( phrase.indexOf("DDDD") == -1) {
alert("That word does not occur.");
}
#INPUT AND OUTPUT
Old programs used to run batch processes. Take data feed it to a program, and get an output file. OLD STYLE PROGRAMMING
New style are in browsers or desktop but can take any number of inputs and provide any number of outputs. Because what we see in programs now are graphic user interfaces, the combinations of input and output becomes endless.
Persistence, or saving the state of the program. Saving to DB or HDD or WEB. Without deciding to persist our data, everything just dissapears. RAM does not save data, only while the program is running.
#READING AND WRITING FROM THE DOM
what is the document? The webpage itself. This can be HTML or browser view.
What are objects? The different peices of the document. The seperate sections of the document ie.
<h1></h1>
<ul></ul>
<li></li>
What is the model? The model means, what do we call these different peices, and how do we describe the relationship between these different peices. Simply a set of terms that we agree on.
##DOM - Is agreed upon set of terms that describe how we interact with the pieces of a webpage.
Event driven programming - Doing something with any type of input.
Event handler or event listner - a function that waits for an event to happen.
onload onload onclick onblur onfocus
<h1 id="mainHeading"></h1>
var headline = document.getElementById("mainHeading");
headline.onclick = function() {
headline.innerHTML = "You clicked the headline";
};
#Introduction to file I/O -
###File input and output
psudocode examples --
Open file at path "myfile.txt" Read contents of file into string variable Close File
Alot more conditional code for I/O
Simple Reading a file example in ruby -
filename = 'simpleexample.txt'
f = File.open(filename, 'r')
f.each_line { |line|
puts line
}
f.close
Simple Writing a file example in ruby -
message = 'This is for output.'
filename = 'myoutput.txt'
File.open filename, 'w' do |f|
f.write message
end
Breaking Files apart in Ruby -
open file at path "myfile.txt"
while file has lines left
read one line
display line
end
f.close
###Streams - Stream of bytes. One chunk at a time.
#Introduction to debugging -
- syntax errors - Something is wrong with the actual format of what we wrote
- logic errors - Main problems for any programmer.
Arithmetic issues -
var a = 100;
var b = 0;
var result = a/b;
alert(result);
ALWAYS FIRST STEP - REPRODUCE THE PROBLEM
#Object oriented programming
###CLASS A blueprint, the definition, the description
Examples - if you were created a restraunt review web application you would create classes for:
- Restraunt Review User TextBox Button Window etc.
- Also represent invisible things
What does a class define?//person class to describe a person
ATTRIBUTES://Really the data/variables
- name
- height
- weight
- age
- gender
BEHAVIOR://what can you do/functions
- walk
- run
- jump
- speak
- sleep
some languages call these principles PROPERTIES and METHODS class is describing these things in abstract. Says a person HAS a name and HAS a height, but it doesnt say what the persons name or height is
Just like there is no reason to draw a blueprint if you arent going to build a house, there is no reason to define a class unless youre going to make an object.
The class is the idea and the object is the thing itself. We create objects based on the class.
Like creating houses from the blueprints, you can create MULTIPLE houses(object) from one blueprint(class)!
###ENCAPSULATION Idea that classes are self contained units, that represent data and the code that works on that data, take our properties and our methods and box them up.
###OBJECT The object itself, created from the class.
#Using Classes and Objects
Objects:
var myArray = [1,2,3,4,5];//array class built into javascript
var myRE = /hello/;
Objects are smart. They have methods and properties built into themselves.
Primitives:
var myNumber = 123;
var isValid = true;
Some other JS objects
var today = new Date();
var y2k = new Date(2000,0,1);
var y2k = new Date(2000,0,1,0,0,0);
// Get methods
today.getMonth();
today.getFullYear();
// Set method
today.setMonth(5);
today.setFullYear(2012);
today.setDay(0);
Math Object -
var x = 200.6;
var y = Math.round(x); //201
var a = 200, b = 10000, c = 4;
var biggest = Math.max(a,b,c);
var smallest = Math.min(a,b,c);
Math.PI
Math.random();
Math.sqrt();
Math.log();
Javascript Classes/Objects Array RegExp Date Math
Very common in object oriented languages to use the class when you create the object. Uppercase first letter for javascript classes!
var today = new Date();
Strings are objects in most OOL.
OOL is just an idea. Pure OOL = does the language just support the creation of objects, or does it DEMAND that everything MUST be an object.
Current state of things -
C++ C# Java Javascript Perl Python Objective-C Ruby Visual Basic
#Memory Management Across Languages
- Allocate memory
- Create Object
- Use Object
- Free Memory
Common problem, we forget to free memory after we allocate memory, create the object, use object. This is called a memory leak.
#Introduction to algorithms
Part of a program. A small peice. A function.
ex. Sorting
61 13 72 47 14
is first bigger than second, if it is flip them.
- There are a number of sorting algorithms
- Most are built into languages now.
- Simplest to write arent always the most efficient
There never is just one way to solve a problem This is why it is usually called an art, not a science.
#Introduction to multithreading
Programs usually on, use one conveyer belt that goes through tasks one at a time. Multithreading uses a custom thread to go through certain tasks to speed up execution
#Introduction to languages
C-based lanaguages - Most influencial language Characteristics?
- not object oriented
- low-level, comiled, strongly typed
- intermediate - advanced
What is it used for?
- everything
- games
- utilities
- embedded systems
- operating systems
- not typical desktop/web/mobile
ex.
#include <stdio.h>
// this is a comment
int main (void) {
int x;
x = calculateSomeValue();
printf("Hello/n");
}
#include - linking to external libraries
Java - Heavily influenced by C but came along 20 years later.
- Enormously object-oriented
- Huge library java class library
- high-level not much memory Management
- hybrid compilation
- strongly typed
- garbage collected
- Intermediate
Cross platform
- Write once, run anywhere
Desktop application
- Mobile application for android
ex.
class HelloWorldApp {
// another main method!
public static void main(String[] args) {
int myInt = 55;
System.out.println("Hello World!");
}
}
Java is not javascript! Full IDE, eclipse or netbeans
C# and Visual basic .NET
Oject oriented
- .net framework - huge library(.NET framework)
- High-level
- Hybrid compilation
- Garbage collection
- Strongly Typed
Intermediate(Microsoft intermediate language)
- Windows Desktop apps
- Web apps "ASP.NET" (building dynamic smart interactive website using microsoft technology.)
- Mobile applications: Windows Phone
ex.Hello1.cs
public class Hello1
{
public static void Main()
{
System.Console.WriteLine("Hello, World!");
}
}
Pascal or almond style Whitespace insensitive
VB.NET
Module Module1
Sub Main()
System.Console.WriteLine("Hello,World!")
End Sub
End Module
RUBY!!!!!!
Developed in Japan. Very pure OOL
Characteristics: Everything is an object.
- High-level
- Interpreted
- Garbage collected
- Beginner/Intermediate
Cross-Platform
-
Web Apps: Ruby On Rails webframework that uses Ruby utilities
puts "Hello, world!" def welcome(name) puts "Hello, #{name}" end
x = "bob" welcome(x)
Python:
- Like Ruby
- object-oriented
- Large library
- High-level, interpreted
- garbage collected
- strongly typed
- Beginner - Intermediate
Cross-Platform
-
Web apps
-
embedded scripting languages
print 'Hello, World!' def sayhello(name): print 'hello', name sayhello('simon')
Eclipse with PyDev, Komodo
Objective-C
- Older language, OOL of C. Extra stuff to C
- object-oriented
- large library (Cocoa)
- high-level
- compiled
- reference counted
- strongly-typed
Intermediate - Advanced
Apple development Mac Desktop development iOS (iPhone,iPad development)
int main(int argc, const char *argv[]) {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]
NSLog(@"Hello world\n");
[pool drain];
return 0;
}
#Libraries and frameworks
Huge amounts of code already written, already tested, ready for you to use Its not really about the language, its about the libraries!
#Where to go from here
- Basic concepts, core ideas, processes, introduction to best practices.
- Go and explore a language!
- No substitute to hands on practice!