Too Long; Didn't Read? I don't blame you. Here are the basics.
Almost every programming language has the same set of basic controls. Use the heading links on the right or scroll down for more information.
Variables
A variable is a virtual bucket that holds data. It is a specifically sized chunk of memory (RAM) that a program uses to collect and manipulate text or numbers. Like renting a storage locker.
C++ and Java are statically (strongly) typed languages with strong control over memory. C++ also has the ability to create pointers which point to a location in memory, based on the address. Java does the memory management for you, while C++ requires the programmer to have full control on memory management (destroying used memory, etc).
C++ and Java have extremely similar primitive types - similar enough to discuss them together:
// Declaring a variable has the following syntax options// Option 1: No initialization// dataType variableList;int i, j, k;char oneChar, twoChar;bool trueOrFalse;// Option 2: Initialization// dataType variableName = value;int x, y =2, z =-5;char myChar ='M';bool t =true;
Primitive types include bool, int, double, float, char, void and some other 'special' types. Note: a string is a special kind of variable, made of up many char values. See Arrays, below.
Javascript is a dynamically (loosely) typed language. Instead of asking for a specific amount of memory, for a specific purpose, you simply declare a variable. The type is determined by the interpreter and how you use the variable in your code.
Javascript considers Numbers, Strings, and Booleans to be primitive types and abstracts the difference between int, double, or float and string or char.
Because Javascript is constantly changing and also due to its loose typing, there are many things one must understand about variables in JS that goes beyond the scope of this course. See the links below for more information.
// Declare some variables and optionally initialize themvar someNumber, someOtherNumber, x; // 'undefined' until initializedvar y =4, z;let myBoolean =true;let someString ='Hello';constMY_NAME='Superman',PI=3.1415926;
Python is a dynamically (loosely) typed language. Similarly to Javascript:
Based on the data type of a variable, the interpreter allocates memory and decides what can be stored in the reserved memory. Therefore, by assigning different data types to variables, you can store integers, decimals or characters in these variables.
~ Tutorialspoint - Python Variable Types
# Variables do not need an explicit declaration in PythonmyVar ="Initialize as I go!"x,y,z =4,5,"Zed"# Init multiple variables at oncemyInteger =40# IntegermyFloat =40.0# Float# In Python you can delete objects (variables) to release the memorydel myInteger # Kaboom! Gone.
Variables, especially primitive types, are an essential building block of programming. It would be impossible to do anything on a computer without them - not even typing. The computer is constantly using various locations of memory (RAM) to store, retrieve, and destroy data while the computer does all the various things like create a visible interface, allow a mouse click or user input, make sound, show an animation, or do math...
Primitive types can be combined to make other, special variables. They can also be used as a way of describing something, creating an object. Object Oriented Programming (OOP) is an extremely powerful tool and it would not be possible without basic variables (primitive types).
Note: a string is a special kind of variable, made of up many char values. See Arrays, below.
Arrays
Variables can only hold one value at a time. But what if you have more than one "person" or "age"?
You won't want to make person1, person2, person3... when does it end?
Think of an array like a line-up of connected bins, each with its own home address (called an index). Let's say you need to store ten random integers for a guessing game. You wouldn't declare ten individual integer variables, you could declare one integer array of size 10 to hold the individual numbers.
You can then store or retrieve each number by calling its address (index), typically using square brackets:
x[0] =7; // Store 7 in the first "bin"int valueOfBin3 =x[2]; // Retrieve the value in the third "bin"
Note: A string is actually an array of char variables.
Arrays in C++ can become confusing when you start to think about memory space and pointers. Let's keep it simple and look at declaring some arrays:
// Declaring an array of integers of size 20intarrayOfInts[ 20 ];// Initialize each item from 1 to 20 (and print them)for (int x =0; x <20; x++) {arrayOfInts[ x ] = x +1; std::cout <<arrayOfInts[ x ] << std::endl;}// Another way to intialize (this creates an array of size 4double arrayOfDoubles[] = {13.2,10.0,2.16,32.75};std::cout <<arrayOfDoubles[ 3 ] << std::endl; // Will output 32.75
Java works in a similar fashion but the syntax is different.
C++: type name[size];
Java: type[] name = new type;
// declare & allocate memory to integer arrayint[] intArray =newint[20]; // another way to declare an arraydouble[] dblArray =newdouble[]{ 1.1,2.0,3.6,10.5 }; // Put values into the intArrayfor (int i =0; i <intArray.length; i++) { intArray[i] = i * (i +1); // some math... }// Print the elements of the intArrayfor (int i =0; i <intArray.length; i++) {System.out.println("Element at index "+ i +" : "+ intArray[i]);}
Note: The C++ syntax will work in Java but it was only implemented as a way to help C++ developers. It is not the preferred method. The examples above are the preferred methods.
Since Javascript does not have types like C++, we just make an array of variables. Javascript also has some great built-in methods that allow us to concatenate, join, search, and sort arrays (among other things).
// Let's declare an array, there are two ways to do itlet someArray =newArray(); // Badlet otherArray = []; // Good /* While both methods work, it is considered proper form to use the second method above */// Let's put some values into an arraylet integers = [40,100,1,5,25,10];// Let's add another item by 'pushing' it on the endintegers.push(6);// Let's add a string in the 8th position (index 7) without using pushintegers[7] ="8th item!";/* Javascript is so loosely typed that our array does not need to be all the same type! Also, the push() method puts a new element on the end of the array but we can add an element wherever we want by using the index. */// Let's print out our array (Javascript has about 5 ways to do that)for (let i =0; i <integers.length; i++) {console.log(integers[i]);}// Using the for...of methodfor (let value of integers) {console.log(value);}
Python has a more versatile 'array' type called a sequence. The most basic sequence is a list. Lists in Python act very similar to arrays in Javascript. They can be modified, contain any type of variable or object, and they have many built-in methods for utilization.
# Let's create two listslistOne = ['Iron Man','Thor',1980,2018];listTwo = [1,'second',3,4,"fifth",6,7];# Print the second item of listOne: Thorprint listOne[1]# Print items 2 through 6 (inclusive) of listTwo: ['second', 3, 4, 'fifth']print listTwo[1:5]# Python has tons of awesome ways to interact with lists# Highly recommend you read www.tutorialspoint.com/python/python_lists.htm
Aside from Lists, Python also has Tuples and Dictionaries. Read more about all of Python's types.
In programming, a string is actually an array of chars. So, the string "Hello" is actually a char array of size 5 where char[0] = 'H', char[1] = 'e', char[2] = 'l', etc.
Most languages allow you to manipulate a string using the indexes of the characters. Also, when you append to a string or concatenate multiple strings together the computer must allocate a new chunk of memory that is the specific size of the new char array and individually assign each index the appropriate letter.
Simple arrays, as discussed in these sections, are called one dimensional arrays. They are linear in the sense that there is a beginning & end, and the indexes in-between have an element on either side, like links in a chain.
Arrays can be two dimensional as well (or even more). A 2D array has two indexes, [x, y], such that each element in the first index is, itself, an array.
You can also chain arrays into a 3D array. The idea there is that each element points to a 2D array of arrays. You can create all sorts of amazing combinations in this fashion.
Conditionals
Make decisions or paths of code based on the value(s) of data.
If...(else if)...else
Do something based on a boolean expression. If this, do that, otherwise if something else, do this... etc.
Same syntax for C++ , Java, Javascript, and many other languages.
if (booleanExpression1) { // code to be executed if true}elseif(booleanExpression2) { // booleanExpression1 is false and booleanExpression2 is true}elseif (booleanExpression3) { // booleanExpression1 and 2 are false and booleanExpression3 is true}. // "else if" statements are optional and you can have infinitely many.else { // code to execute if all test expressions are false (optional)}
Python syntax is a bit strange different - there are shortened words, it uses white space to exit a block of code, and notice the placement of colons:
if booleanExpression1:# statement(s)elif booleanExpression2:# statement(s)elif booleanExpression3:# statement(s)else:# statement(s)# Note: "elif" and "else" statements are optional
If...else statements are the most basic tool for creating multiple pathways of code. There can also be shortcuts if you are comparing a simple boolean or want to combine items with And or Or boolean logic.
There is something called the ternary operator. It is used for simple yes/no situations and is worth learning.
// C++ ternary exampleint a, b =2, c =3;a = (b > c ? b : c); // since b > c is false, a takes the value of c (3)
Switch / Case
Use a Switch or Case statement if you are going to have many else if statements or the condition is not inherently boolean in nature (like the value of a string, for example).
Same syntax for C++, Java, Javascript, and many other languages.
switch(expression) {case value : // Code to runbreak; // optional to break out of the switch blockcase value : // Code to runbreak; // optional to break out of the switch block // You can have any number of case statements.default : // Optional case to catch any other possibilities // Code to run}
Python does not have a Switch / Case implementation. Instead, you use something called a dictionary and call it a switcher. You can read more about that on your own:
Switching on use input:
// Javascriptlet userInput =prompt("Please enter a colour","blue");switch (userInput) {case"red":// code for what happens when user enters redbreak;case"blue":// code for what happens when user enters bluebreak;case"black":// code for what happens when user enters blackbreak;case"yellow":// code for what happens when user enters yellowbreak;default:// code for what happens when user enters anything else}
Loops
For Loop (count controlled)
Need to do a portion of code repeatedly a specific number of times? Need to perform a mathematical algorithm repeatedly based on a value or values?
Same syntax for C++, Java, Javascript, and many other languages.
for(counter_initialization; boolean_expression; inc/dec_counter) { // Code to run repeadtedly, usually utilizing the counter}
Example: Print the remainder (modulo) of 10/i for i = 1 to 10 (Javascript shown)
for (let i =1; i <=10; i++) {console.log(10% i);}// Output (each on a new line): 0 1 2 0 4 3 2 1 0
Don't forget - Python uses while space to end blocks of code.
for iterating_var in sequence:# Code to run repeatedly
Example: Print the remainder (modulo) of 10/i for i = 1 to 10 (Python)
for i inrange(1, 10):print10%i# Output (each on a new line): 0 1 2 0 4 3 2 1 0
Here is an animated example:
This type of looping is called iterating. Some variable types are iterative - like arrays and lists.
Many languages have a method for looping through all of the items in an iterative type. For example, Java has the foreach loop, which is very handy. See the interactive sample below:
Do/While Loop (condition controlled)
The for loop is great when you have a set number of times you want to loop. However, loops don't have to run a specific number of times. There are two ways to loop based on a condition (true or false) instead of a value.
While
The while loop is not guaranteed to run any number of times, even once. It depends on a specific condition and will continue to loop while that condition is true - get it?
It has the same syntax for C++, Java, Javascript, and many other languages.
while(someCondition) { // Code to run until 'someCondition' is set to false}
Notice how you have big potential for an infinite loop if your condition is never changed to false. Infinite loops are very, very bad.
Example: Keep looping until a random number below 10 is generated (Javascript shown)
In the above example, if we don't modify myRandomNumber inside the loop, we might have an infinite loop. I say might because there is no guarantee the loop runs in the first place. myRandomNumber could start at a value less than 10. If that's the case, the loop never runs.
You might wish to lookup the break and continue commands for while loops as well.
Python has a while loop and it works extremely similarly to any other language. Here is the syntax:
while expression:statement(s)
As long as expression is true, loop through the statements below it.
Example: Loop until a value is less than 10
import randomx = random.randint(1,100)while x >=10:print(x) x = random.randint(1,100)print(x)
Similar to the example for C++, Java, and Javascript on the previous tab, this will print numbers greater than or equal to 10 (but below 100) until a number less than 10 is found. It might only print one number and never enter the loop.
You might wish to lookup the break and continue commands for while loops as well.
Some websites that teach coding have you create a while loop like this:
while(true) {// Your code here}
An example of this is CodeCombat (although I do love CodeCombat overall).
What happens in the background is that their coding environment knows to stop this loop at some point. That's extremely dangerous. In my not-so-humble opinion, this should not be taught in this manner. You are creating an infinite loop and not explaining to the learner what that loop really does.
Do While
The while loop has a twin sibling - the do while loop. This slight adjustment to the while loop guarantees the code within the loop will run at least once.
do {statement(s);} while( condition );
Example: This example will generate and print a random number from 1-20 (inclusive) and will loop if the value is greater than 10. It is guaranteed to print at least one number. (Javascript shown)
let myRandomNumber;do { myRandomNumber =Math.floor(Math.random() *20) +1;console.log(myRandomNumber);} while (myRandomNumber >10);
One extremely important item to note is the semicolon at the end of the last line. That helps to close the statement and ensure the while condition loops around the do statement above it.
Python does not have a do...while loop construct. The short version of the story is that there has never been an agreed-upon syntax that matches the indented formatting of the Python language. Furthermore, it can easily be replicated or 'faked' with something like this:
whileTrue:# statement(s)ifnot condition:break
If that syntax hurts your brain, you can understand why I decided not to teach Python for our first programming language.
Functions
The strength in functional programming is the ability to create your own small blocks of code that exist for you to "call" or "run" when needed. They are like mini-programs that sit in the background waiting to be used.
C++ is a statically (or strongly) typed language. So, functions have a type and must return the type of value matching the function. If not returning a value, the function has the type void. It is also important to note that every C++ program has a main() function and is compiled from top-to-bottom (not interpreted). The compiler needs to know the user-defined functions exist before compiling the main function.
Syntaxtype nameOfFunction(type parameter1, type parameter2, ...) {
// Code execution
return [value matching function type]
}
That syntax requires a good example:
#include<iostream>/* Function that takes a boolean and two integers If square is true, return the average of the squares Otherwise, return the average */doubleavg(double num1,double num2,bool squared) {if (squared) { num1 = num1*num1; num2 = num2*num2; }return (num1+num2)/2;}intmain() { std::cout <<avg(9,6,true) << std::endl; std::cout <<avg(9,6,false) << std::endl;}
That example will not compile/run if we declare the avg function after the main. There is a way around this, however. We can prepare the compiler for the existence of our function with a function prototype. That's fancy speak for a quick pre-declaration. Let's see the example again with our avg function declared after main.
Similar to C++, Java is a statically-typed language with a main() function. There is a terminology difference - in Java a user-defined function is called a method. This is due to the fact that Java is a true object-oriented language and not a functional programming language.
Since Java is object-oriented, the methods (user-defined functions) can have scope. This is beyond our course but crucial to understanding Java methods.
Syntax
modifier returnType nameOfMethod(type parameter1, type parameter2, ...) {
// Code inside the method
return [optional value matching method type];
}
Unlike C++, Java does not require prototype methods - you can write your methods above or below the main() method.
Example - Return the minimum value given two integers.
classMain {publicstaticvoidmain(String[] args) {int a =11;int b =6;System.out.println("Minimum Value = "+minimum(a, b)); }// Return the minimum of two valuespublicstaticintminimum(int n1,int n2) {int min;if (n1 > n2) min = n2;else min = n1;return min; }}
Final note - Java allows you to override a method. That means you can write a method with the same name as another but different parameters and return type. That allows for multiple options when calling a method (like integers values vs. doubles).
Creating a function in Javascript is simple. Since it is a loosely-typed language you do not declare a return type for the function. Furthermore, all parameters are optional and if you call the function with too many parameters, the extra ones are ignored.
Syntaxfunction nameOfFunction(parameter1, parameter2, ...) {
// Content inside the function
return [optional value];
}
The return call is optional and you can return any type of data or object. If nothing is returned, the function is said to return undefined.
Example - Given a value and an array, return true if the value exists in the array.
// Ignoring the fact that we can use Array.includes()functioncontains(theArray, value) {for (let i =0; i <theArray.length; i++)if (theArray[i] == value) returntrue;returnfalse;}