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

{% tabs %}
{% tab title="C++ and Java" %}
C++ and Java are statically (strongly) typed languages with strong control over memory. C++ also has the ability to create [*pointers*](https://www.tutorialspoint.com/cplusplus/cpp_pointers.htm) 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](https://en.wikipedia.org/wiki/Primitive_data_type) - similar enough to discuss them together:

```cpp
// 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**](https://en.wikipedia.org/wiki/Primitive_data_type) 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](https://cs.brash.ca/grade11/~/edit/drafts/-LOmmd42868gJKxLnjbm/tl-dr/quick-basics#arrays), below.
{% endtab %}

{% tab title="Javascript" %}
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.

```javascript
// Declare some variables and optionally initialize them
var someNumber, someOtherNumber, x;    // 'undefined' until initialized
var y = 4, z;
let myBoolean = true;
let someString = 'Hello';
const MY_NAME = 'Superman', PI = 3.1415926;
```

#### Links

[Mutable vs Immutable](https://www.sitepoint.com/immutability-javascript/) - the mystery of [`const`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const)\
[`let`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let) vs [`var`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var) and [variable scope](https://codeburst.io/difference-between-let-and-var-in-javascript-537410b2d707)
{% endtab %}

{% tab title="Python" %}
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](https://www.tutorialspoint.com/python/python_variable_types.htm)

```python
# Variables do not need an explicit declaration in Python
myVar = "Initialize as I go!"
x,y,z = 4,5,"Zed"   # Init multiple variables at once
myInteger = 40      # Integer
myFloat = 40.0      # Float

# In Python you can delete objects (variables) to release the memory
del myInteger       # Kaboom! Gone.
```

{% endtab %}

{% tab title="Other" %}
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](https://en.wikipedia.org/wiki/Object_\(computer_science\)). Object Oriented Programming ([OOP](https://en.wikipedia.org/wiki/Object-oriented_programming)) 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](https://cs.brash.ca/grade11/~/edit/drafts/-LOmmd42868gJKxLnjbm/tl-dr/quick-basics#arrays), below.
{% endtab %}
{% endtabs %}

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

{% tabs %}
{% tab title="Visualization" %}
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](https://cs.brash.ca/unit-2/variables/numbers/the-math-object/random-numbers) 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.

![](https://docs.google.com/drawings/d/e/2PACX-1vQ9ujHqIJM1X7SiP9edLC73GWz2WqZUZf5SURercld1d2PMF8xG9ptLELD_3Zjc8ofAyu1UNm6cfy18/pub?w=473\&h=115)

You can then store or retrieve each number by calling its address (index), typically using square brackets:&#x20;

```cpp
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.&#x20;
{% endtab %}

{% tab title="C++" %}
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:

```cpp
// Declaring an array of integers of size 20
int arrayOfInts[ 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 4
double arrayOfDoubles[] = {13.2, 10.0, 2.16, 32.75};
std::cout << arrayOfDoubles[ 3 ] << std::endl;  // Will output 32.75

```

{% endtab %}

{% tab title="Java" %}
Java works in a similar fashion but the syntax is different.

C++:  `type name[size];`\
Java:  `type[] name = new type;`

```java
// declare & allocate memory to integer array
int[] intArray = new int[20];  

// another way to declare an array
double[] dblArray = new double[]{ 1.1, 2.0, 3.6, 10.5 }; 

// Put values into the intArray
for (int i = 0; i < intArray.length; i++) {
    intArray[i] = i * (i + 1);   // some math... 
}
 
// Print the elements of the intArray
for (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.
{% endtab %}

{% tab title="Javascript" %}
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).

```javascript
// Let's declare an array, there are two ways to do it
let someArray = new Array();         // Bad
let otherArray = [];                 // Good 
/* While both methods work, it is considered 
   proper form to use the second method above  */
   
// Let's put some values into an array
let integers = [40, 100, 1, 5, 25, 10];

// Let's add another item by 'pushing' it on the end
integers.push(6);

// Let's add a string in the 8th position (index 7) without using push
integers[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 method
for (let value of integers) {
    console.log(value);
}
```

Tons more reading [here](https://www.w3schools.com/js/js_arrays.asp) and [here](https://www.tutorialspoint.com/javascript/javascript_arrays_object.htm).&#x20;
{% endtab %}

{% tab title="Python" %}
Python has a more versatile 'array' type called a `sequence`. The most basic sequence is a [`list`](https://www.tutorialspoint.com/python/python_lists.htm). 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.

```python
# Let's create two lists
listOne = ['Iron Man', 'Thor', 1980, 2018];
listTwo = [1, 'second', 3, 4, "fifth", 6, 7];

# Print the second item of listOne:  Thor
print 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`**](https://www.tutorialspoint.com/python/python_lists.htm), Python also has `Tuples` and `Dictionaries`. Read more about all of [Python's types](https://www.tutorialspoint.com/python/python_variable_types.htm).
{% endtab %}

{% tab title="Strings" %}
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.

![](https://docs.google.com/drawings/d/e/2PACX-1vRL0enP6qaEFyVu8BG5wLQvLUQ_JYpDJbJaQF0gpqfEd4PE8MBucKASmoi5VHKvuAJUEwTuNqQM8d7a/pub?w=616\&h=324)
{% endtab %}

{% tab title="Other" %}
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.

![](https://docs.google.com/drawings/d/e/2PACX-1vSPRsA8CgrcHL1fqpjPRmk2rkaCxg9NNpWcO1xeBcrLjPEXEbhj6Y-13waawAxltpETXzSOzfvbcOXg/pub?w=620)

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.
{% endtab %}
{% endtabs %}

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

{% tabs %}
{% tab title="C++, Java, and Javascript" %}
Same syntax for C++ , Java, Javascript, and many other languages.

```cpp
if (booleanExpression1) {
   // code to be executed if true
}
else if(booleanExpression2) {
   // booleanExpression1 is false and booleanExpression2 is true
}
else if (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)
}
```

{% endtab %}

{% tab title="Python" %}
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:

```python
if booleanExpression1:
   # statement(s)
elif booleanExpression2:
   # statement(s)
elif booleanExpression3:
   # statement(s)
else:
   # statement(s)
   
#  Note: "elif" and "else" statements are optional
```

{% endtab %}

{% tab title="Other" %}
`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`**](https://en.wikipedia.org/wiki/%3F:) operator. It is used for simple yes/no situations and is worth learning.

```cpp
// C++ ternary example
int a, b = 2, c = 3;
a = (b > c ? b : c);   // since b > c is false, a takes the value of c (3)
```

{% endtab %}
{% endtabs %}

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

{% tabs %}
{% tab title="C++, Java, and Javascript" %}
Same syntax for C++, Java, Javascript, and many other languages.

```cpp
switch(expression) {
   case value :
      // Code to run
      break; // optional to break out of the switch block
   
   case value :
      // Code to run
      break; // 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
}
```

{% endtab %}

{% tab title="Python" %}
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:

{% embed url="<https://jaxenter.com/implement-switch-case-statement-python-138315.html>" %}
{% endtab %}

{% tab title="Example" %}
Switching on use input:

```javascript
// Javascript
let userInput = prompt("Please enter a colour", "blue");

switch (userInput) {
   case "red":
      // code for what happens when user enters red
      break;
   case "blue":
      // code for what happens when user enters blue
      break;
   case "black":
      // code for what happens when user enters black
      break;
   case "yellow":
      // code for what happens when user enters yellow
      break;
   default:
      // code for what happens when user enters anything else
}
```

{% endtab %}
{% endtabs %}

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

{% tabs %}
{% tab title="C++, Java, and Javascript" %}
Same syntax for C++, Java, Javascript, and many other languages.

```cpp
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)

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

{% endtab %}

{% tab title="Python" %}
Don't forget - Python uses while space to end blocks of code.

```python
for iterating_var in sequence:
   # Code to run repeatedly
```

**Example:**  Print the remainder (modulo) of `10/i` for `i` = 1 to 10  (Python)

```python
for i in range(1, 10):
	print 10%i
# Output (each on a new line): 0 1 2 0 4 3 2 1 0
```

{% endtab %}

{% tab title="Animation" %}
Here is an animated example:

![Click to enlarge, created by author](https://1200419583-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LKbpNQDFNJap9OTDSt6%2F-LQREfC7GUqPbGRmeAux%2F-LQRF9dT7G220-aFU38g%2FFor-Loop-\(Large-0.8\).gif?alt=media\&token=6758e361-d14b-49e4-8777-1575315873a1)
{% endtab %}

{% tab title="For-Each" %}
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:

{% embed url="<https://tech.io/snippet/SNf0sjV>" %}
Scroll the widget to see Run button and output
{% endembed %}
{% endtab %}
{% endtabs %}

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

{% tabs %}
{% tab title="C++, Java, and Javascript" %}
It has the same syntax for C++, Java, Javascript, and many other languages.

```cpp
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)

```javascript
let myRandomNumber = Math.floor(Math.random() * 100) + 1;

while (myRandomNumber >= 10) {
    console.log(myRandomNumber);
    myRandomNumber = Math.floor(Math.random() * 100) + 1;
}

console.log(myRandomNumber);
```

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.
{% endtab %}

{% tab title="Python" %}
Python has a `while` loop and it works extremely similarly to any other language. Here is the syntax:

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

```python
import random

x = 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.
{% endtab %}

{% tab title="Other" %}
Some websites that teach coding have you create a while loop like this:

```javascript
while(true) {
    // Your code here
}
```

An example of this is [CodeCombat](https://codecombat.com) (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.
{% endtab %}
{% endtabs %}

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

{% tabs %}
{% tab title="C++, Java, and Javascript" %}

```javascript
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)

```javascript
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.
{% endtab %}

{% tab title="Python" %}
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:

```python
while True:
    # statement(s)
    if not condition:
        break
```

If that syntax hurts your brain, you can understand why I decided not to teach Python for our first programming language.
{% endtab %}
{% endtabs %}

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

{% tabs %}
{% tab title="C++" %}
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.

**Syntax**\
`type nameOfFunction(type parameter1, type parameter2, ...) {`\
&#x20;   `// Code execution`\
&#x20;   `return [value matching function type]`\
`}`

That syntax requires a good example:

```cpp
#include <iostream>

/* Function that takes a boolean and two integers
   If square is true, return the average of the squares
   Otherwise, return the average */
double avg(double num1, double num2, bool squared) {
  if (squared) {
    num1 = num1*num1;
    num2 = num2*num2;
  }
  return (num1+num2)/2;
}

int main() {
  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`.

```cpp
#include <iostream>

// Here's our prototype
double avg(double num1, double num2, bool squared);

// Main execution function
int main() {
  std::cout << avg(9, 6, true) << std::endl;
  std::cout << avg(9, 6, false) << std::endl;
}

// User-defined function
double avg(double num1, double num2, bool squared) {
  if (squared) {
    num1 = num1*num1;
    num2 = num2*num2;
  }
  return (num1+num2)/2;
}
```

{% endtab %}

{% tab title="Java" %}
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, ...) {`\
&#x20;   `// Code inside the method`\
&#x20;   `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.

```java
class Main {
   public static void main(String[] args) {
      int a = 11;
      int b = 6;
      
      System.out.println("Minimum Value = " + minimum(a, b));
   }

   // Return the minimum of two values
   public static int minimum(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).
{% endtab %}

{% tab title="Javascript" %}
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.

**Syntax**\
`function nameOfFunction(parameter1, parameter2, ...) {`\
&#x20; `// Content inside the function`\
&#x20; `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.

```javascript
// Ignoring the fact that we can use Array.includes()
function contains(theArray, value) {
  for (let i = 0; i < theArray.length; i++)
    if (theArray[i] == value) return true;
    
  return false;
}
```

(Here is the actual [Array.includes()](https://www.w3schools.com/jsref/jsref_includes_array.asp) syntax)
{% endtab %}

{% tab title="Python" %}
Python utilizes the `def` keyword to define functions.

**Syntax**\
`def name_of_function(parameter1, paramter2, ...):`\
&#x20;   `statement_1`\
&#x20;   `statement_2`\
&#x20;   `....`\
&#x20;   `[optional return]`

The return statement works exactly like other languages and you can return any type of value you like because Python is dynamically (loosely) typed.

**Example** - Return the average of two numbers.

```python
def avg(num1, num2):
    return (num1 + num2)/2
```

{% endtab %}
{% endtabs %}

## Input / Output

<< coming soon >>

{% tabs %}
{% tab title="C++" %}

{% endtab %}

{% tab title="Java" %}
Text here
{% endtab %}

{% tab title="Python" %}

{% endtab %}

{% tab title="Javascript" %}

{% endtab %}

{% tab title="Other" %}

{% endtab %}
{% endtabs %}
