What are procedures?

Procedure: a named group of programming instructions that may have parameters and return values

Parameters: input values of a procedure, specified by arguments

Arguments: specify the values of the parameters when a procedure is called

Modularity: separating a program's functions into independent pieces or blocks, each containing all the parts needed to execute a single aspect of the functionality

Procedural Abstraction: providing a name for a process that allows a procedure to be used only knowing WHAT it does, not HOW it does it

What are some other names for procedures?: function or method

Why are procedures effective?: Procedures allow certain series of algorithms and functions to be run more simply. They can put a set of complex actions under a distinct framework to be called upon later for ease of use.

Additional Notes

Calling Procedures (Python)

  • It's important to know what arguments and parameters are necessary when creating a procedure
  • You can call a procedure within other statements like 'print' to show the return value
  • Procedures with return values can essentially be placed as variables representing whatever would be returned by the function (in most cases)
  • Some procedures do not return values, simply running to serve background purposes before ending

Calling Procedures (JavaScript)

  • JavaScript uses function instead of def plus curly brace syntax
  • Below is an example (1) of a JavaScript function using an array:
function plusMinus(arr) {
    var pos = 0;
    var neg = 0;
    var zero = 0;
    
    var length = arr.length;
    for (var i = 0; i < arr.length; i++) {
        if (arr[i] > 0) {
          pos += 1;
        } else if (arr[i] < 0) {
          neg += 1;
        } else {
          zero += 1;
        }
      }
     console.log("There are " + arr.length + " total numbers");
     console.log("There are " + pos + " positive numbers");
     console.log("There are " + neg + " negative numbers");
     console.log("There are " + zero + " zeroes");
    }

    var array = [1, 1, 0 , -1, -1];
    plusMinus(array);
There are 5 total numbers
There are 2 positive numbers
There are 2 negative numbers
There are 1 zeroes
  • This creates an array based on the indexes of the array items
  • Here is the military time converter (example 2):
function timeConversion(s) {
    var arr = s.slice(0,8).split(':');
    arr[0] = (s.indexOf('PM') > -1) ?
             (arr[0] == 12 ? '12' : Number(arr[0]) + 12) :
             (arr[0] == 12 ? '00' : arr[0]);
    console.log(arr.join(':'));
    }
  
    var input = "07:05:45PM";
    timeConversion(input);
19:05:45

Developing Procedures

Questions to ask yourself when developing procedures:

  • What am I going to name my procedure? (It should reflect the purpose of the code)
  • What parameters do I need?
  • What data would I need to take in to accomplish my goal?
  • Do I want my procedure to give a numerical value, or complete an action?

Procedural abstraction is an important part of clarifying the purpose of various procedures. This promotes efficient collaboration.

According to the lesson, it is sometimes efficient to group multiple procedures into a single procedure, further abstracting and giving specific uses for possibly more general procedures.

Challenge 1

I made the procedure and then called it within the print statement.

decimal = 7

def convertToBinary(n):
    if 0 <= n <= 255: #here's the program itself
        pass
    else:
        return "Invalid input." #error if not valid for 8-bit binary
    i = 7
    binary = ""
    while i >= 0:
        if n % (2**i) == n:
            binary += "0"
            i -= 1
        else:
            binary += "1"
            n -= 2**i
            i -= 1
    return binary

print(convertToBinary(decimal)) #this calls the function despite being in 'print'
00000111

Challenge 2

I created the findMax and findMin procedures and ran them with the numbers 4 and 3. I did this all in JavaScript for bonus points.

Optional Bonus (Hack)

See the bottom procedure findExtrema. It checks an array for its greatest and least values, then prints them in the console.

// Start by creating a procedure called findMax and set the parameters to numberA and numberB.
// Within the procedure, write the code to determine which of the two parameters, numberA or numberB, is the larger value. Print that value.
function findMax(numberA, numberB) {
    if (numberA !== numberB) {
        if (numberA > numberB) {
            console.log(numberA);
        } else {
            console.log(numberB);
        };
    } else {
        console.log(numberA, "and", numberB, "are equal")
    }
}
// Repeat the process, this time creating a procedure called findMin, which will print the parameter with a smaller value.
function findMin(numberA, numberB) {
    if (numberA !== numberB) {
        if (numberA > numberB) {
            console.log(numberB);
        } else {
            console.log(numberA);
        };
    } else {
        console.log(numberA, "and", numberB, "are equal")
    }
}
// Call both functions so that the parameters numberA and numberB are given a value.
var x = 4
var y = 3
findMax(x, y)
findMin(x, y)

// Optional bonus- create a procedure that can determine the minimum or maximum value out of more than two parameters.
numarr = [3, 50, 20, 3134, 5555, 2, 73, 59]
function findExtrema(array) {
    greatest = array[0]
    least = array[0]
    for (let i = 1; i < array.length; i++) {
        if (array[i] > greatest) {greatest = array[i]}
        if (array[i] < least) {least = array[i]}
    };
    console.log("The greatest is " + String(greatest) + ". The least is " + String(least) + ".")
}

findExtrema(numarr)
4
3
The greatest is 5555. The least is 2.

Homework/Hacks

I did the "APCSP" to binary thing. The procedure is called charToBinary. It works by first using the procedure DecimalToBinary that I made to convert the decimal version of the given character (found through the innate ord Python function), and then appends it to a list of each of the characters. It then prints it.

The reason the output has a 0 in front of every 8-bit conversion is that the intended output is in 7-bit.

def DecimalToBinary(x):
    if 0 <= x <= 255:
        pass
    else:
        return("Error")
    i = 7
    binary = ""
    while i >= 0:
        if x % (2**i) == x:
            binary += "0"
            i -= 1
        else:
            binary += "1"
            x -= 2**i
            i -= 1
    return binary

def charToBinary(x):
    binlist = []
    for i in x:
        binlist.append(DecimalToBinary(ord(i)))
    print(str(x), "in binary is:", binlist)

# output is has an extra 0 at the front because it is in 8-bit binary, not 7-bit
charToBinary("APCSP")
APCSP in binary is: ['01000001', '01010000', '01000011', '01010011', '01010000']

Frontend Version with User Input

Here's a frontend version that lets you convert anything:

I would like to convert to binary.

Nothing converted yet.

And here is the raw code for this version (including HTML to show IDs).

<p>I would like to convert <input id="binaryinput" style="text-align:left" type="text" minlength="1" value="APCSP"> to binary. <button id="convertbtn">CONVERT</button><br></p>
<p id="binaryconversion">Nothing converted yet.</p>
<script>
    var inpbox = document.getElementById("binaryinput");
    var opbox = document.getElementById("binaryconversion");
    var btn = document.getElementById("convertbtn");
    function DecimalToBinary(parameter) {
        var input = Number(parameter);
        if (input < 0) {
            console.log('invalidreturn');
            return "Invalid input.";
        } else if (input > 255) {
            console.log('invalidreturn');
            return "Invalid input.";
        };
        var i = 7;
        var binary = "";
        while (i >= 0) {
            if (input % (2**i) == input) {
                binary += "0";
                i -= 1;
            } else {
                binary += "1";
                input -= 2**i;
                i -= 1;
            };
        };
        return binary;
    };
    function stringToBinary(x) {
        var x = String(x);
        var binarr = [];
        for (i = 0; i < x.length; i++) {
            binarr.push(DecimalToBinary(x.charCodeAt(i)));
        };
        return binarr
    };
    btn.onclick = function() {
        opbox.innerHTML = '"' + String(inpbox.value) + '" in binary is [' + String(stringToBinary(String(inpbox.value))) + '].';
    };
</script>