These course notes will display the fundamentals of programming
using psydocode to basic understanding. This course will explain the logic
behind all psudocode code. If you desire to see how it can be applied, I have
added Javascript so that you can compare psudocode to actual code to understand
the logic is the same but the code is different. Understanding computer logic
is just as important as learning to write code; therefore, let’s begin.
Intro to programming Logic:
Click to show.
Table of contents:
Introductions to Computer and Programming
Input, Processing, and Output
Modules
Decision structures and Boolean logic
Repetition structures
Functions
Input validation
Arrays
Sorting and Searching Arrays
Files
Menu-driven programs
Text Processing
Recursion
Object-oriented Language
GUI Application and Event-Driven Programming
Here is the following syntax I will go into explaining.
Psudocode:
Modules
Declare variables (real, int, string)
Set ( variable, value, calculation, function)
Message //
Display (“name”,” “)
Input
If, then, Else
Conditions (true, false)
Call
Operators (>,<,=,==, >=, <=, !=)
Loops (While, Do While, Do Until, For)
Calculations and operators (+,-,*,/)
Function
dataType conversion (toInteger, toReal)
Formatting (currencyFormat)
StringdataType (length, append, toUpper, toLower, substring,
contains, stringToInteger, stringToReal, isInteger, isReal, null)
Array (parallel arrays, 2Darrays, search Array)
You are free to skip looking at Javacode. It’s only here for
reference.
Javascript:
Variables:
varName = #;
varName = name;
varname = “name”;
var number : int = 5;
var name : string = “five”;
var speed : float = 1.5;
var missle : Transform;
Boolean:
var shipAlive : boolean = true;
var cockroach : boolean = false;
Display:
draw_text(x,y,item+string(num));
show message(“_”);
debut.Log();
print();
name.setName(“_”);
Global variables:
global.game-score = 0;
Comparison, logical, arithmetic operators:
+
-
*
/
%
++
--
==
===
!=
!==
>
<
>=
<=
&&
||
!
//
/* */
null
void
Random numbers:
var ranNubmer : int;
ranNumber = Random.Range(0,100);
If/else:
if(condition){
Statement;
}
else{
Statement;
}
Switch:
switch(value){
case1 {statement; break;}
case2{statement; break;}
}
switch(x){
case1:
debut.Log();
break;
case2:
debut.Log();
break;
}
With:
with(argument){
Statement;
}
For Loop:
for(i=0;i<5;i+1){
Statement;
}
for(var x = 0; x < 10; x++){
Statement;
}
While Loop:
i=0;
while(i<5){
statement;
}
while(){
}
Do Until Loop/ Do While Loop:
i=0;
do{
statements;
}
Until (i>=5)
do{
}
while();
Array:
varName[x] = “_”;
message[0] = ”yo”;
message[1] = ”HelloWorld”;
var myIntArray : int [];
var myStringArray : string[];
2DArrays:
square[0,0] = “x”;
square[0,1] = “y”;
square[1,0] = “z”;
Function/scripts:
set_gravity();
function shootFireBall(){
statement;
}
function Update(){
}
Class:
var character1 : characters;
character1.name = “myName”;
character1.level = 1;
character1. characterClass = “rogue”;
Class Character{
var name;
var level;
var characterClass;
}
Constructor:
var character1 : characters;
character1.name = “myName”;
character1.level = 1;
character1. characterClass = “rogue”;
function
Models(){
//this is a constructor
Class Character{
var name;
var level;
var characterClass;
}
}
Enum:
Enum potionType{
healthPotion,
manaPotion,
speedPotion,
}
//We’ll start here
Introductions to Computer and Programming
Logic:
A computer’s memory uses bytes, which are small storage locations.
Each byte has eight bits. A bit means binary digit. Bits are like switches that
can be turned on or off. On means a positive charge, off means a negative
charge. Bits are used to represent 1s and 0s called a binary number system.
These 1s and 0s can be used in a series to create a numeric or alphabetical
value. Example: The letter A is stored as the numeric value of 65. This is then
used to create instructions for the computer to execute. This instruction is
called code. All programs and software are made up of code which is fundamentally
a list of instruction for the computer to execute. Lines of code make up a
computer language. There are many computer languages such as: Ada, BASIC,
FORTRAN, COLBOL, Pascal, C, C#, C++, Java, Javascript, Python, Ruby, and Visual
Basic. In a computer language there are key words (reserved words). Each key
word has a specific meaning or purpose. Programming languages also have
operators that perform different data operations; like math operators used to
calculate. Individual instructions that are used to write programs are called
statements. Statements consist of keywords, operators, punctuation, and other
programming elements that are arranged in a proper order to perform a specific
task. A complier is a program that translates a computer language into a machine
language (binary) which executes a task. An interpreter is a program that both
translates and executes programed instructions. Its purpose is also to convert
and translate from machine language to code.
Designing a program:
Computer programs aren’t thought up and written in code, they must
go through a design process. This process incudes conceptualizing and planning.
Many programmers draw, write, create flow charts and diagrams, or write the
code in psudocode to create a model before actually writing real code. Often
when writing code, it’s common for programmers to come up against errors or
bugs, because of syntax errors or logic errors. By planning and conceptualizing
the code, one can have better understanding where they went wrong or how to revise
their code logic.
Input, Processing, and Output:
Output is the data that is generated or displayed by a program.
Input is user entered data or data a program receives, and variables are
assigned data that is stored in locations in memory.
An example of utilizing all three of these are: the user sees a
question such as “What is your name?” the user inputs data like putting his
name in an input slot. The program assigns it to a variable. The variable can
be used by the program and generate an output. The output could be something
like “your name is:” and the program displays your name.
Basic variable types:
Int – which mean integer; whole numbers
Real – decimal numbers
String- a set of characters; strings can also be called “char” for
character
The reason there is int and real is because programming languages
utilizes these two variable types differently.
You can assign values or characters to variables to be used within
the code.
All variables should be declared (initialization) at the start of
writing a program, because this makes it easier to change variable assignments.
The reason we declare a variable is so that the memory can assign it to a
memory location. You can also declare a variable later in the code
(uninitialized variables); however, this makes reviewing or understanding your
code very difficult.
Keep in mind you should write your code in a way that allows you
to revise and understand it easily. In a way programming is like an iceberg,
the top is what users can see and interact, but the body is what’s hidden, this
is the mechanics of a program.
When naming variables, it’s common for programmers to write a
variable in lowercase. If there is additional words, names are usually added
without a space and is capitalized. For example: payRate. It can also be
written as pay_rate. It’s important to write words in this kind of notation
because it could make code errors.
You can also declare a variable a constant, this means it can
never be changed:
Note: // or /* comment*/ allows you to add comments in the code
that will not affect your code. // is called line comments, /* comment */ is
called a block comment.
Note: All string character use quotes around them.
In psudocode for this would look like this:
Declare int
age
Display “What is your age?”
Input age
Display “Your age is:”
Display age
Programs can use calculation operators. Such as:
+
addition
-
subtraction
*
multiplication
/
division
MOD Modulus (divides one number by another and gives
the quotient
^
Exponent (raise a number to a power)
You can group calculations by using parenthesis. Example: (3+2)
*2 value = 28
All programs can utilize calculations. Variables can be used for
calculations. For example: hours * payRate.
Declare real hours
Declare real payRate
Declare real calculation
Display “What is your hour and pay rate?”
Input hours
Input payRate
Calculation = hour *
payRate
// here’s your calculation
Display “Your wage is:” calculation “!”
Calculations have to be written in computer notation. For example
x = y + z or 25 = 5 * 5.
Modules:
A module is a group of statements that exists within a program for
the purpose of performing a specific task. Using modules helps make code more
simple, easier to reuse, better for testing, faster to develop, and easier to
facilitate with teamwork.
Example of a module:
Module name()
Statements
Statements
End Module
You can name and call modules. For example:
Module main ()
Display “Knock knock!”
Call showMessage()
Display “Your face!”
End Module
Module showMessage()
Display “Who’s there?”
End Module
Program output:
Knock knock!
Who’s there?
Your face!
If you declare a variable within a module, this is called a “local
variable” which is a variable that can only be used within the same module.
You can pass a variable to another module by passing an argument.
A parameter is a variable that receives an argument that is passed into a
module. This is the reason why modules have parenthesis. For example:
Module main()
Call doubleNumber (4)
End Module
Module doubleNumber (Integer value)
Declare Integer result
Set result = value * 2
Display result
End Module
You can pass more than one argument into a module, but you have to
use a comma to separate them. Then you have to reference the parameters back
into the main module also using commas.
Example:
Module main()
Display “The sum of 12 and 45 is:”
Call showSum (12,45)
End Module
Module showSum (Integer num1, Integer num2)
Declare Integer result
Set result = num1 + num2
Display result
End Module
Program Output:
The sum of 12 and 45 is
57
You can reference arguments by passing it into a special parameter
called a reference variable. Using a reference variable in a parameter, you can
modify the argument inside a module.
Example:
Module setToZero (Integer Ref value)
Set value = 0
End Module
A global variable is a variable that has access to every module. A
global constant is like a global variable, but it cannot be changed in a program.
To be continued on Computer Programming Logic (part 2)
Decision structure and Boolean logic:
A decision structure allows a program to perform actions only
under certain conditions. An example can be: If a robot walked outside and
calculated if it needed a coat. The robot will execute a true or false
condition in which it will determine to wear a coat or not. If the robot
detects that outside is cold, then this condition is true. The robot will then
wear a coat. However, if the robot does not detect that outside is cold, then
the condition is false. The robot will not wear a coat. This is called a
Boolean.
A Boolean is a variable that is either set to true or false.
We can declare this as its own variable:
Declare Boolean cold = true
Declare Boolean warm = false
Conditions, as stated previously, are programmable operations that
are executed when requirement are met.
We can use an If Then statement to create condition in a program.
Example:
If condition Then
Statement
Statement
End If
Conditions can be created using condition operators:
>
greater than
<
less than
>=
greater than or equal to
<=
less than or equal to
==
equal to
!=
not equal to
Note: = and == are not the same. = is assigning something, == is
used for mathematical or comparing purposes.
An example of making a condition can be:
If x < y Then
Statement
Statement
End If
//If condition of x I greater than y, execute this code.
Here another example of complete psudocode:
Module main()
Declare int sales
Declare real bonus
If sales >= 50000 Then
Set bonus = 500.0
End If
End Module
Along with If statements, we also have If – Else statements. Which
is: If a condition is met, execute this code, else (if the condition is not
true) execute that code.
An example is:
If condition Then
Statement
Statment
Else
Statment
Statment
End If
We can also use the same structure with strings. This counts the
number of letters in a sting.
For example:
If “a” < “b” Then
Display “a is less than b.”
End If
A nested decision structure is a condition with multiple
conditions within it.
For example:
Module main()
Declare real salary
Declare int yearsOnJob
If salary >= Then
If yearsOnJob >= 2 Then
Display “You qualify for the load.”
Else
Display “You must have been on your current”
Display “job for at least two years to qualify.”
End If
Else
Display “You must earn at least $30,000”
Display “per year to qualify.
End If
End Module
It can get even more complicated with an If-Then Else If
statement.
For example:
If condition_1 Then
Statment
Statment
Else If condition_2 Then
Statment
Statement
Else
//can insert as many Else conditions as you want
Statement
Statement
End If
You can execute this code or you can also make it easier by
executing a Case/ Switch structure which is a multiple alternative decision
structure.
An example of this code goes like this:
Select testExtression //this can be a variable or
expression
Case value_1:
Statement
Statement
Case value_2:
Statement
Statement
Case value_3:
//or as many cases as you want
Statement
Statement
Default:
Statement
Statement
End Select
Next we have Logic operators that can be used with Boolean
expression.
Logic Operator:
AND combines Boolean
expressions into one compound expression.
OR one or
both Boolean expression can turned into one compound expression.
NOT an expression in which
only one can work.
Example:
x > y AND a > b
x == y OR x == z
NOT (x > y)
Another example:
Module main()
Declare int temperature
If temperature < 20 OR temperature > 100 Then
Display “The temperature is in the danger zone.”
End If
End Module
Repetition Structure:
A repetition structure causes a statement or set of statements to
execute repeatedly. We can do this by using While, Do-While, and Do-Until
loops.
The While loop allows a program to repeat a certain amount of
statements according to its condition.
A while loop can be written like this:
While condition
Statement
Statement
End While
Here’s another full code:
Module main()
Declare real sales
Declare real commission
Declare string keepGoing = “y”
Declare Constant real commisionRate = 0.10
While keepGoing == “y”
Display “Enter the amount of sales.”
Input sales
Set commission = sales * commisionRate
Display “The commission is $”, commission
Display “Do you want to calculate another?”
Display “commission? (Enter y for yes.)”
Input KeepGoing
End While
End Module
When creating a loop, be sure to not make it loop continuously,
this could create an infinite loop which will never end a program.
The Do-While loop is the same as a While loop; however, the only
difference is that it uses a different logic.
Do-While loops are written like this:
Do
Statement
Statement
While condition
Note: the Do-While does not end with an End While, it ends with a
While and its condition.
The Do-Until loop, is like the Do-While loop except it repeats
until it reaches an extent (condition).
You can write it like this:
Do
Statement
Statement
Until condition
The For loop, however, is different from other loops. It counts
until conditions are met. All For loops have a counter variable, starting
value, and a max value. The counter variable counts incrementally starting with
the starting value until it reaches the max value. In this psudocode example,
the To is a keyword in a For loop. The step is the amount of increments. To
make the For loop count backwards, simply turn the step values to a negative
(In the example below step would be equal to -2).
The For loop can be written like this:
For counterVariable = startingValue To maxValue.
Statement
Statement
End For
Here’s an example using psudocode:
Module main()
Declare int counter
Declare Constant int maxValue = 11
For counter = 1 To maxValue step 2
Display counter
End For
End Module
A counter controlled loop can be made like this:
Module main()
Declare int counter = 10
While counter <= maxValue
Statement
Statement
Set counter = counter + 1
//count
backwards by turning this negative
End While
End Module
A running total is the sum of numbers that accumulates with each
iteration of a loop.
This can be done with the statement:
total = total + number
A sentinel is a special value that marks the end of a list of
values or items.
Just like If and else statements, loops can also be nested in a
program. If a loop is nested in another loop, then it’s called a nested loop.
Functions:
A function is a module that returns a value back to the part of
the program that called. Most programming languages provide a language of
prewritten functions that perform commonly needed tasks.
Most libraries have a random function.
In psudocode, we’ll right them like this:
Module main()
Declare Int number
Set number = random (1,10) //random number
from 1 to 10
Display number
End Module
Functions are similar to modules, but can be pulled up to perform
a group of specific tasks that can be used as a statement or if you decide to
reuse a group code. Commonly, a function is used for a Return (function’s
result) variable/ value. When creating a function, it needs to have a datatype
(int,real,char). The datatype is not for the entire function, it’s for what the
functions Return. Also notice, like a module, it has a parameter/ argument
parenthesis, therefore you can pass variables in and out of it.
You can use a function to return a Boolean, string, Integer, or
Real.
You can make your own function like this:
Function dataType functionName ()
Statement
Statement
Return value
End function
Here is an example of a function:
Module main()
Declare real regularPrice
Set regularPrice = getRegularPrice()
End Module
//function
Function real getRegularPrice()
Declare real price
Display “Enter the items regular price”
Input price
Return price
End function
The following function are written out as you would see them
written as a statement.
There is also other Functions that are common in libraries, such
as:
Set result = sqrt (16)
//square root.
Set area = pow (4,2) //raise a
number to a power; it’s the same as a ^ operator
y = abs
(x) //returns the
absolute value of the argument
y = cos
(x) //returns
the cosine of the argument
y = round (x) //rounds to the
nearest integer
y = sin
(x)
//returns the sine of an argument
y = tan
(x) //return
the tangent of an argument
Along with library function, we also have datatype conversions,
such as:
Set i = toInteger
(r) Accept real numbers and
converts them to integers.
Set r = toReal
(i)
Accepts integer numbers and converts them to real.
String Functions also have their own special functions.
length(wordExample) //calculates the amount of
letter in a word.
Append(wordExample1,
wordExample2)
//puts both words together.
toUpper(wordExample)
//turns all words to uppercase.
toLower(wordExample)
//turns all words to lowercase.
substring(name,2,2) //this
calls parts within a string. The values inside the substring parenthesis will
call from the beginning of a string/name/word and the end of a
string/name/word. An example can be kevin. If you execute this particular sub
string, you’l only see the v.
contain(string1,
string2)
//this, like a Boolean for true or false, check to see if a string/ word
contains another string/word inside it.
stringToInteger(string) //you can initialize a string with a
numeric integer value.
stringToReal(string)
//you can initialize a string with a numeric real value.
isInteger
//can help check to see if a integer value is true or false.
isReal //can help check to see if a real value
is true or false.
Input Validation:
If a program reads bad data as input, it will produce bad data as
output. Programs should be designed to reject bad data that is given as input.
An input validation loop is commonly done with a loop that
iterates as long as an input variable contains bad data.
Input validation is part of the practice of defensive programming.
Throughout input validation anticipates both obvious and unobvious errors.
One should write their programs with the thought of what could
possible go wrong and what could be used to prevent or check for errors.
Arrays:
An array allows you to store and group items of the same datatype
together in memory. Processing a large number of items in an array is usually
easier than processing a large number of items in separate variables.
Instead of this:
Declare string employee1
Declare string employee2
Declare string
employee3
//and so on…
You can write this instead:
Declare string employee [10]
You can also assign specific values in an array like this:
Set numbers[0] = 20
Set numbers[1] = 30
Set numbers[2] = 40
Set numbers[3] = 50
Set numbers[4] = 60
You can also use a loop to step through an array:
For example:
Module main()
Declare int series [10]
Declare int index
For index = 0 To
9 //
Note it starts with zero not one, because you’re counting from zero.
Set series [index] = 100
End For
End Module
In an array you can initialize more variables in a single array
variable, for example:
Constant int size = 5
Declare int numbers[size] = 10, 20, 30, 40, 50
Beware of the off by one error! This happens when there is one too
many or one too few in an array (and of course in counting For loops).
If necessary, if you’re making a database, you can set an array to
an extremely large number so that you have extra slots (elements).
You can count an array using a For-Each loop. Note the In is also
a keyword.
You can write it like this:
For Each var In array
Statement
Statement
End For
In more detail, we can use this code:
Module main()
Declare constant int size = 5
Declare int numbers[size] = 5, 10, 15, 20, 25
Declare int num
For Each num In numbers
Display num
End For
End Module
We can use search algorithms to sequentially search an array.
Here’s an example of that code:
Module main()
Declare constant int size = 10
Declare int score [size] = 87, 75, 98, 100, 82, 72, 88, 92, 60, 78
Declare Boolean found
Declare int index
Set found = false
Set index = 0
While found == False AND index <= size -1
//not the -1, otherwise
off-by-one error
If score[index] == 100 Then
Set found = true
Else
Set index = index +1
End If
End While
End Module
You can do the same thing with string arrays. You can search
though the array until you find the string you’re looking for.
You can use this same method with the other syntax learned to get
an average total, highest or lowest value of an array. You can also copy an
array by using an array inside another array. You can also pass an array
through a module or function’s argument and parameters.
A parallel array is an array that you can use by establishing a
relationship between data stored in two or more arrays. This is like a regular
array, but their data slots(elements) are parallel to each other for example:
slot1 on array1 is parallel to slot 1 in array2. You can then use the
same slot number in your code (like add both slots from array1 and array 2
together).
A two dimensional array is like several identical arrays put
together. It’s useful for storing multiple sets of data.
You can create a two-dimensional array like this:
Declare constant int rows = 3
Declare constant int column = 4
Declare int values[rows][column]
This means every element will have two subscripts; one for row,
the other for column.
For visual representation:
Element row 0
values[0][0]
values[0][1]
value[0][2]
Element row1
values[1][0]
values[1][1]
value[1][2]
Element row2
values[2][0]
values[2][1]
value[2][2]
To access one for the elements in a two-dimensional array, you
need to write both subscripts, for example:
Set values [2][1] = 95
You can make arrays with more than just two dimensions; however,
this can look or get complicated as you add more subscripts.
For example: Declare real seats[3][5][8]
Sorting and Searching:
A sorting algorithm rearranges the contents of an array so they
appear in a specific order (the bubble sort is the simplest sorting method).
Sorting and searching is commonly irrelevant for writing in
programs; therefore I shall provide with a list of search and sorting
algorithms.
The bubble algorithm: sorts and arranges data in ascending and
descending order.
Selection sort algorithm: steps through an array and moves each
value to its final position.
Insertion algorithm: Sorts the first two elements, which becomes the
sorted part of the array. It then inserts each of the remaining elements, one
at a time, into the sorted part of the array at the correct location.
Binary search algorithm: searches by dividing every part of an
array in half.
These are all my notes for my computer programming logic
class.
No comments:
Post a Comment