Main content
Pseudocode Equivalents
Defining a procedure
Here's the equivalent of that pseudocode in more languages:
- Python calls procedures "functions" and uses
def
to define them:def sing_bingo(): print "B!" print "I!" print "N!" print "G!" print "O!" sing_bingo() sing_bingo() sing_bingo()
- Java is an object-oriented language, so all procedures must be a member of a class. They are often called "methods" in Java.
class Main { public static void singBingo() { System.out.println("B!"); System.out.println("I!"); System.out.println("N!"); System.out.println("G!"); System.out.println("O!"); } public static void main(String[] args) { singBingo(); singBingo(); singBingo(); } }
- When you make your own "block" in Snap!, you are defining a new procedure.
Procedures with parameters
- Python specifies parameters the same way as shown in the pseudocode:
def report_grade(student_name, num_correct): score = (num_correct/30) * 100 report = student_name + " earned: " + str(score) print "score" report_grade("Sally", 27) report_grade("Wilbur", 24)
- Java is an object-oriented language, so all procedures must be a member of a class and are typically called "methods". Since Java is a typed language, you must specify the data type before each parameter name to a method.
class Main { public static void reportGrade(String studentName, int numCorrect) { double score = (numCorrect/30.0) * 100; String report = studentName + " earned: " + score; System.out.println(report); } public static void main(String[] args) { reportGrade("Sally", 27); reportGrade("Wilbur", 24); } }
- In Snap!, you can make procedures by making "blocks" and then specify parameters by pressing the "+" sign next to the block name.
Procedures with return values
- Python uses
return
to specify return values:def calc_line_slope(x1, y1, x2, y2): yDiff = y2 - y1 xDiff = x2 - x1 slope = yDiff / xDiff return slope slope1 = calc_line_slope(1, 2, 4, 5) slope2 = calc_line_slope(0, -1, 3, 10)
- Java is an object-oriented language, so all procedures must be a member of a class and are typically called "methods". Java is also a typed language, so the data type of the return value must be declared in the method header, before the method name.
class Main { public static float calcLineSlope(float x1, float y1, float x2, float y2) { float yDiff = y2 - y1; float xDiff = x2 - x1; float slope = yDiff / xDiff; return slope; } public static void main(String[] args) { float slope1 = calcLineSlope(1, 2, 4, 5); float slope2 = calcLineSlope(0, -1, 3, 10); } }
- In Snap!, you can make procedures that return values by making "reporter" type blocks. The final line in the block will start with "report", the equivalent of return.
Conditionals with if, else, booleans
- Python does not put the conditions inside parentheses, and it follows the if/else with a colon instead of curly brackets. It then uses an extra level of indentation for the instructions inside the if/else blocks.
if password == "TOPSECRET": print("You got it!") else: print("Try again!")
- Java has similar syntax to JavaScript and the pseudocode. However, it is different in that checking string equality must be done with the
.equals()
method. Number equality can be checked with==
.if (password.equals("TOPSECRET")) { System.out.println("You got it!"); } else { System.out.println("Try again!"); }
- You can find
if
andif/else
blocks inside the Snap! Control blocks. You can then drag conditions from the Operators blocks.
Nested conditionals
Here's the equivalent of that pseudocode in more languages:
- Python does not put the conditions inside parentheses, and it follows the if/else with a colon instead of curly brackets. It then uses an extra level of indentation for the instructions inside the if/else blocks.
if number > 0: sign = "positive" else: if number < 0: sign = "negative" else: sign = "neutral"
- Java has very similar syntax to JavaScript and the pseudocode.
String sign; if (number > 0) { sign = "positive"; } else { if (number < 0) { sign = "negative"; } else { sign = "neutral"; } }
- You can find
if
andif/else
blocks inside the Snap! Control blocks. You can drag additionalif/else
blocks inside the outer blocks and then drag conditions from the Operators blocks.
Compound booleans
Here's the equivalent of that pseudocode in more languages:
- The logical operators in Python are similar to the pseudocode operators, but lowercased.
if csp_grade >= 75 or prog_grade >= 75: print("You're eligible for AP CS A!")
if cumulative_GPA > 2.0 and total_units >= 120: print("You can graduate!")
if not (cumulative_GPA > 2.0 and total_units >= 120): send_email()
- Java has the same logical operators as JavaScript,
||
,&&
, and!
.if (cspGrade >= 75 || progGrade >= 75) { System.out.println("You're eligible for AP CS A!"); }
if (cumulativeGPA > 2.0 && totalUnits >= 120) { System.out.println("You can graduate!"); }
if (!(cumulativeGPA > 2.0 && unitsCompleted >= 120)) { sendEmail(); }
- You can find
if
andif/else
blocks inside the Snap! Control blocks. You can then drag the logical operators (and
/or
/not
) and relational operators (>
/<
/=
) from the Operators blocks.Note that Snap does not have>=
or<=
, so you can either adjust the numbers or use theor
block to achieve the same effect.
Random numbers
Here's the equivalent of that pseudocode in more languages:
- Python offers a wide variety of random number generations in the
random
module. Therandint()
function is equivalent to the pseudocode procedure.import random val = random.randint(1, 4) if val == 1: print("1") elif val == 2: print("2") elif val == 3: print("3") else: print("4")
There are other functions inrandom
that are better picks for other use cases, however. - Java provides the same procedures as JavaScript, so we can use very similar code with
Math.floor()
andMath.random()
to define our ownrandInt()
method:class Main { public static int randInt(int start, int end) { int range = (end - start) + 1; return (int) Math.floor(Math.random() * range) + start; } public static void main(String[] args) { int val = randInt(1, 4); System.out.println(val); } }
- Snap provides a
pick random
block in the Operators toolbox that functions the same as the pseudocode procedure.However, Snap does not provide a chainedif
/else
block, so we use nestedif
/else
blocks instead.
Numbered repetition of instructions
Here's the equivalent of that pseudocode in more languages:
- Python does have a
for
loop, but it does not have a three-part header. Instead, Pythonfor
loops use arange()
function to generate the range of values to iterate through.for i in range(1, 13): print(9 * i)
Note that therange()
function does not generate the end number in the range, so the above loop goes from 1 to 12 (excluding 13).for i in range(10, 0, -1): print(i)
Since therange()
function counts up by default, we specify a third parameter of -1 to ask it to count down. - Java has the same 3-part
for
loop as JavaScript. The only differences in the code are that Java is typed, so the counter variable is declared as anint
, andSystem.out.println()
displays the output.for (int i = 0; i < 13; i++) { System.out.println(9 * i); }
for (int i = 10; i > 0; i--) { System.out.println(i); }
- Snap has a
repeat n
block that you can find in the Control blocks. It also has achange by n
block that makes it easy to add one to the counter variable.
Conditional repetition
Here's the equivalent of that pseudocode in more languages:
- Python has a
while
loop, which is conceptually the same as the Javascriptwhile
loop. The syntax differs in the usual way; Python uses a colon and indentation instead of curly brackets.i = 1 while i < 11: print(i) i += 1
num_rabbits = 2 num_years = 0 while (num_rabbits <= 100): num_rabbits += (num_rabbits/2 * 30) num_years += 1
- Java has the same
while
loop as JavaScript. The only differences in the code are that Java is typed, so each variables is declared as anint
, andSystem.out.println()
is used to display output.int numRabbits = 2; int numYears = 0; while (numRabbits <= 100) { numRabbits += (numRabbits/2 * 30); numYears++; }
int i = 1; while (i <= 10) { System.out.println(i); i++; }
- Snap has a
repeat until
block that you can find in the Control blocks. It also has achange by n
block that makes it easy to add one to variables.
Storing and updating lists
Here's the equivalent of that pseudocode in more languages:
- Python also uses bracket notation for creating lists and updating list values, and its indices are 0-based like in JavaScript.
rainbow_colors = ["red", "orange", "yellow", "green", "blue", "indigo", "violet"] first_color = rainbow_colors[0] last_color = rainbow_colors[6] rainbow_colors[4] = "cyan" rainbow_colors[5] = "blue"
- The syntax for declaring an array in Java is a bit different because Java is a strongly typed language. We start the declaration with the data type (
String[]
orint[]
, for example), and then we use curly brackets to provide initial values.String[] rainbowColors = {"red", "orange", "yellow", "green", "blue", "indigo", "violet"}; String firstColor = rainbowColors[0]; String lastColor = rainbowColors[6]; rainbowColors[4] = "cyan"; rainbowColors[5] = "blue";
To declare an empty array, we must provide the length of the array:String[] myChores = new String[5];
Java arrays are fixed-length, so if you need to be able to change the length of your array throughout your program, you will need to use another collection type, likeArrayList
. - All of the blocks for creating and updating list items are in the Variables toolbox.After you create a variable, you can use the
set
block with thelist
block. Then you can useset
with theitem i of list
block to reference the values. To then update them, use thereplace
block.
Here's the equivalent of that pseudocode in more languages:
- Python provides various methods for lists. The
append()
andinsert()
methods operate very similarly to the pseudocode procedures with the same name. There are a few ways to delete items from lists in Python, butpop()
is the method that's most similar to the pseudocodeREMOVE
.my_chores = [] my_chores.append("Wash the dishes") my_chores.append("Do laundry") my_chores.append("Mow the lawn") my_chores.insert(0, "Scare ants away") my_chores.insert(2, "Write this article") my_chores.pop(4) my_chores.pop(2)
- Java arrays have a fixed-size, so their length cannot change during program execution. That means procedures like append/insert/remove wouldn't make sense for arrays.However, Java offers many other collection types, like
ArrayList
, which can change length, and includes methods likeadd()
andremove()
.ArrayList myChores = new ArrayList(); myChores.add("Wash the dishes"); myChores.add("Do laundry"); myChores.add("Mow the lawn"); myChores.add(0, "Scare ants away"); myChores.add(2, "Write this article"); myChores.remove(4); myChores.remove(2);
- Snap has many list-related blocks in the Variables toolbox. To create an empty list, first create a variable and use
set
with thelist
block. Press the left arrow to empty the list. Then useadd
to append items,insert
to insert items, anddelete
to remove items.
List iteration
Here's the equivalent of that pseudocode in more languages:
- Python provides a simple
for-in
loop for iterating over every element in a list, and it looks very similar to the pseudocode:planets = ["Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"] for planet in planets: print(planet)
Here are the other 3 examples using afor-in
loop:total_price = 0 prices = [1.75, 3.50, 4.99, 2.50] for price in prices: total_price += price
num_freezing = 0 temps = [29, 33, 31, 30, 28, 33, 35, 34, 32, 28] for temp in temps: if temp <= 32: num_freezing += 1
prices = [39.99, 29.99, 19.99] discounted_prices = [] for price in prices: new_price = price * 0.75 discounted_prices.append(new_price)
- Java provides a
for-each
loop as well, which can iterate through arrays as well as collections like theArrayList
.String[] planets = {"Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"}; for (String planet : planets) { System.out.println(planet); }
Here are the other 3 examples using afor-each
loop:double totalPrice = 0; double[] prices = {1.75, 3.50, 4.99, 2.50}; for (double price : prices) { totalPrice += price; }
int numFreezing = 0; int[] temps = {29, 33, 31, 30, 28, 33, 35, 34, 32, 28}; for (int temp: temps) { if (temp <= 32) { numFreezing++; } }
double[] prices2 = {39.99, 29.99, 19.99}; ArrayList<Double> discountedPrices = new ArrayList<Double>(); for (double price : prices2) { double newPrice = price * 0.75; discountedPrices.add(newPrice); }
- Snap does not have a specific block for repeating through elements of a list. However, similar to JavaScript, we can use the
repeat until
block and repeat for each index in the list.List indices start at 1 in Snap, so the counter variable starts at 1 and the loop stops when the counter variable is greater than the length of the list.Here are the other 3 examples using arepeat until
block: