Fundamentals of problem solving & programming

Ace your homework & exams now with Quizwiz!

Boolean value

"Boolean" value (variable type) - Is either "True" or "False" ("Yes" or "No", 0 or 1) - ALL decisions MUST be "boolean" - The result of a decision MUST be "True" or "False" - "Yes" or "No"

Naming convention for variables

- Do not use spaces - Use either camelCase or use_underscore - Describe what the information is and what it is for - Avoid abbreviations and contractions (they may lead to confusion) - Short and concise eg. studentAge NOT ageofTheCurrentStudent

The 6 step problem solving for computers

1. Analyse the problem - 5 'whys' 2. Design a solution - algorithm (pseudocode or flowchart) 3. Check the solution - step thru the algorithm 4. Implement the solution - write the code 5. Test the implementation - test code by running program 6. Done

What is the CPU fetch-decode-execute cycle?

1. Fetch the next instruction 2. Decode that instruction - works out what it needs to do 3. Execute that instruction

Problem Decomposition technique

1. Identify the nouns ie the 'things' 2. Eliminate the nouns that are repeated or not relevant; eliminate any collections, e.g. Dimensions vs length, width & height 3. Identify the 'verbs'

The 6 steps for problem solving

1. Identify the problem 2. Understand the problem (Identify any constraints) - use the 5 why's method 3. Identify alternative solutions 4. Select the best method to solve the problem a) Eliminate alternatives unacceptable ( cost too much, not practical etc.) b) list pros &a cons of each method c) Weigh the pros & cons to make a final decision 5. Prepare a list of instructions to solve the problem 6. Evaluate the solution

General rules for functions

1. In most cases a function should not call itself; this is recursion 2. A function should NEVER call back to the function that it called; this indirect recursion and often leads to INFINITE LOOPS which are BAD and have very high memory use. 3. If one function ALWAYS calls another, then: a) Merge them into a single function; just ensure that you follow the single purpose design principle b) Move the second function call to be inside the same function that called the first

Types of functions

1. Input: Prompts should be passed in as inputs to the function; if you get a value give it a name i.e define as a variable. 2. Output: Anything that could be a variable should be -Names, values etc... 3. Processing: - Do not display anything to the user (unless we're testing/debugging) - Do not get any values from the user - Input should be passed in as variables, not as literals. Any fixed values should be assigned as variables. These should be defined on only one place as it makes it easier for editing and evaluating; only need to change it in one place in the code, i.e. where it is defined as a variable - Output should be returned to main()

What are the six basic computer operations?

1. Receive information (input) 2. Put out information (output) 3. Perform arithmetic 4. Assign a value to a variable (memory location) 5. Compare two variables and select 1 or 2 alternative actions depending on the result of the comparison (ie. True or False) 6. Repeat a group of actions

Three decision types

1. Single path decision: - There is only one path, which includes some conditional behaviour Example: Ask an employee for their current salary. If their salary is less than $45,000 then they receive a 10% pay raise. Whether they receive the raise or not, display the final salary. 2. Two possible branches - The decision has 2 possible outcomes (True/False, Yes/No) - EACH result has a path with some conditional behaviour The earlier 'invalid number' example contains a two path decision. Many paths... - Used for more complex decisions Example: Ask a user to enter their score (out of 100) for a test. If their score is less than 50 then their result is "Fail". If they scored at least 50 but less than 65 their result is "Pass". 65 to 74 is a "Credit", 75 to 84 is a "Distinction" and 85 or over is a "High Distinction"

Low level language

A computer language that is closer to computer code ie binary language

Flowchart

A consistent & visual representation of a problem; it uses a small set of symbols that have different meanings.

Function

A self-contained segment of code that accomplishes a specific task. This is the "single purpose design principle". Once written, the function can be called multiple times; it is therefore more efficient than re-writing the same code every time it is used. A function is a construct used to combine local variables and statements to perform a single task. A function must first be defined and then called in the code.

What is a computer program?

A series of instructions that a modern computer can execute; a program allows you to tell a computer what to do. We write programs that allow us to solve problems with a computer.

Problem Decomposition

A technique used to identify the core elements of a problem by breaking the problem into its parts: - Identify the variables that need to be stored (what are the 'things' in the problem that are important - Identify any processes (what needs to be done; context is important) - Identify the output (what do I need to produce)

What is an IPO chart?

A way to analyse & decompose a problem based on the data: - What are we given (input) - What are we asked to produce (output) - How do we get from input to output (processing) IPO chart is NOT an alternative to algorithms/flowcharts, rather it is a planning tool for identifying variables and processing steps

Flowchart in programming

A way to reason about how a particular sequence of program statements work. In particular, it shows the possible paths of execution. Control of execution is an important aspect of programming languages

OR

AND joins two boolean values together, the result depends on the values of the LHS and the RHS Result is only True if BOTH the LHS and RHS are True

AND

AND joins two boolean values together, the result depends on the values of the LHS and the RHS Result is only True if Result is only True if BOTH the LHS and RHS are TrueBOTH the LHS and RHS are True

Why use & evaluate algorithms?

Algorithms allow us to analyse the completeness and correctness of a solution without the burden of having to observe exact language syntax. Also, by using algorithms you will get familiar with how certain problems are solved; look for patterns of problems. Similar problems have similar solutions; avoid reinventing the wheel, just modify an algorithm for our purposes.

Boolean Algebra

Allows us to combine boolean values to produce new boolean values -More simply - it allows us to do more complicated conditions, so that we can test more than one thing at a time

Partially Compiled Languages

Becoming very common •Source code is partially compiled to 'bytecode', which is then distributed and interpreted on the users computer. The user MUST have the necessary interpreter on their computer •Pros -Faster than purely interpreted -More secure than interpreted -More flexible than compiled •Cons -Still needs specific software •Examples include Java (mostly), Visual Basic (now) •Note - in theory any language can be compiled or interpreted. The examples given are how these languages are generally used.

Analyse the problem

Break it down and identify the real issue. Use the 5 Whys - ask 'Why' at least 5 times In business, solving problems can have a very high cost, therefore need to identify the 'real problem'.

How do we evaluate an algorithm?

Compare what it does to what it SHOULD do; if they don't match, then algorithm is wrong! Stepping through the algorithm Correction by using easy calculation to test for realistic values N.B. To test an algorithm, you need to know what is the expected result. Look for illogical results, eg negative costs. If it works, can we improve it by removing any unnecessary steps or rearrange the steps to make it more elegant? If it doesn't, Why and how do we fix it? Are there any missing/incorrect steps? Are any steps in the wrong place?

Nested if statements

Conditionals inside other conditionals Can often be avoided with good design, but not always... Check a) the number of variables b) the number of paths If many variables and many paths, then you may need a nested if statement

Categorising data

Determine what 'type' a piece of data should be; eg. name, address Strings (text) age (in years) Integer (whole number) price, pay rate Float (decimal number)

How do we represent an algorithm?

Either by using pseudocode (ie. plain text) or by way of a flowchart.

How do we communicate a solution?

Either: a) Wall of text or b) Algorithm

Elements in an Array

Even though we store them as a collection, we still deal each variable individually •To access a single element of an array we use its name (like any other variable) followed by a number in [square brackets] -The number is the number of items to step over -Starts at 0 -Often called 'index', or just 'i'

Iterations (AKA Loops)

Extend Decomposition -'for', 'while', 'repeatedly', 'until' •These words indicate that an iteration is probably necessary

When to use decisions?

Extending Decomposition: What words in a problem description indicate decisions? - Look for words like 'if', 'otherwise' and so on 'when' and 'then' MAY indicate decisions, but might not. - Read the description carefully - if a decision is implied in the wording then it is needed in the solution. Not all decisions will be part of the initial problem. Sometimes we will need to add decisions to ensure our solution always works. - Look for 'problem' values or situations What data values make no sense? What will happen if those values are used? - Avoid them with decisions In some situations there is a better solution

Loops for input validation

Here we use a loop for input validation, rather than an if statement (like last week) Why? When is this NOT a good decision?

Loop design tool

Identify three (3) things •Loop variable - What value are we checking when we decide to loop again or not? •Exit condition - When do we stop? What value of the loop variable will make us stop? Usually the first thing we find •Loop body - What happens each time •What should only happen before/after the loop?

Logic errors

If more than one variable is passed in, the inputs are linked to the function variables by their order and type. Variables must be passed into the function in the correct order, otherwise it may produce an incorrect result (Logic Error) or may not run at all. If two integers are passed in, but not in the right order, then - Depending on the function it may not matter - Or it may produce incorrect results Logic errors are the most common type of error in programming.

Output Data

If the function produces a result that must be stored, then assign the returned value to a local variable using the equal '=' operator e.g. employeePay = calculatePay

What is a decision?

In algorithm design (and programming) all decision are done with comparisons: - We compare one value to another - ALL comparisons MUST return a Boolean result, i.e. True or False All the standard mathematical comparisons are available to us: - Equal (=) - Less than (<) - Greater than (>) -Less than or equal to (<=) - Greater than or equal to (>=) - Not equal to (<>) - In Java and Python 'equal' is == - 'not equal' is !=

Passing data to functions

In programming, each function only knows about its own data - this is called scope To be useful, we need to send data in and out of functions - PASS data into functions - RETURN data from functions N.B. If more than one variable, is passed then the order MUST match up

The power of a programming language

Is its ability to combine statements and constructs together; this another manifestation of abstraction

Pseudocode

It is a step-by-step description of the actions a computer should execute; - Written in standard English - Each instruction is on a separate line - Keywords and indenting are used to indicate control structures (sequence, selection, repetition) - Any variables needed are listed - Set of instructions is written from top to bottom - Groups of statements can be placed in modules or functions

Algorithm

It is a step-by-step explanation of a particular solution to a problem. A method—a sequence of steps—that describes how to solve a problem or class of problems.

When to use arrays?

Look for logical collections of data, lists etc •When the problem says 'for each' or 'for all' then a collection MAY make sense -But not in all cases, it depends on what we are doing -This is where you need to analyse and decide, you will practice this in the workshops

NOT

NOT is a 'unary' operator -It only operates on one value, unlike AND and OR which operate on two •They are 'binary' operators •NOT reverses the value -if it is True then it becomes False, if it is False then it becomes True -Classic example: if age does not equal 18

Loops in algorithms

New keywords -'repeat n times' •Can be used for definite loops (replace n) -'repeat while' •Can be used for definite or indefinite loops •Like conditionals, steps inside the loop are indented

Decisions in Algorithms

New keywords: - 'if' - used for the initial decision - 'then' used to identify the behaviour on that path ~ Instructions on the path should be indented - 'otherwise' - used for all other branches ~ Can combine 'otherwise' with 'if' for many branches Example: get score if score < 50 then display "Fail" otherwise if score < 65 then display "Pass" otherwise if score < 75 then display "Credit" otherwise if score < 85 then display "Distinction" otherwise display "High Distinction" N.B. We don't require the last "if" statement for score >= 85 because it can only be HD

Array

New kind of variable -New way of storing data •An "array' is a whole list (or collection) of data -Accessed by a single variable name •Very useful for dealing with lots of similar values

Interpreted Languages

No processing done before runtime •Code is 'interpreted' on the users computer by special software •Source code is distributed •Pros -Easier to distribute •Cons -Can be slower -Users MUST have the required software -Users can potentially alter the code •Examples include Python and VBA (mostly)

How do we design decisions?

Now we know WHEN to use decisions... - HOW do we design our decisions? Decisions are written as one value c.f. another value; the result is a Boolean, i.e. True or false. - Check a condition e.g. temp > 40 OR temp < 40 How do we identify the 'paths' coming out of this decision? How many are there? What are they? N.B. How you program multi-path decisions depends on the programming language used.

Programming

Programming is the art of taking a planned solution and producing a working implementation of it. A programming language is a tool used to implement these solutions.

High level language

Python is an example of one; it is closer to human langauge

Processing an entire array

Quite often we need to do something with each element of an array -This is what 'for' loops are designed to do! -Just an alternate version of 'repeat n times' •For loops allow us to do something 'for each item' in a list -The phrase 'for each item' will be used in our design •We will also use 'item' to refer to the specific element of the array

Problem breakdown

Some problems are too big or complex to solve as a single problem; these large problems need to be broken down into manageable chunks by using the following tools: Look for 'themes': What are the 'sections' of this program Can be data-driven For a processing step, what are the inputs and outputs? If different processing steps have different data then the MAY be different sections! Can be user-interface driven Caution!!! We should separate user interface from process BUT interface may be a guide; different buttons/menu options may be different 'sections' Look at problem description: Are there separate ideas or components? Some of these may be dealt with separately

Compiled Languages

Source code (written by a programmer) is processed by software tools which link it to any other code it uses, and produces a stand-alone executable file. •The file is then distributed to any one who wants to run it and then can do so without the need for other software on their computer. •This 'processing' has several steps, but is broadly called 'compilation'. •Pros -Faster execution for users, no need to users to have special software •Cons -Harder to distribute across different OS's (Mac, Windows, Unix etc) -Developer must recompile for any target platform •Examples include C/C++, Visual Basic (initially)

Why make decisions?

The ability to make decisions within any solution is fundamental. Otherwise each solution is just a step by step process, i.e there is no complexity or dynamism in the solution. This means we would need to design separate solutions for all possible scenarios...

Naming rules for functions

The name should describe what the function does: e.g. calculatePay NOT pay calcFahrenheit NOT fahrenheit N.B. Function name should always contain a verb, I.e. What does it do,

Syntax errors

These are errors in the use of the programming language. These occur when we ask the program to do something that it inherently cannot do! They are the easiest to detect and are detected by the interpreter

Input Data (arguments)

These are listed in order (in brackets) after the function name in BOTH the function definition and the function call e.g. calculatePay(hours, payRate)

Types of variables

Three main types: - Strings (text or numbers displayed as characters in text) - Integers (whole numbers) - Floating point or real numbers ( decimal numbers) Remember, that variable 'type' is an issue of implementation; cannot add an integer to a string.

Boolean Operators

Three that we will use: -AND -OR -NOT •AND and OR are similar to most mathematical operations -They have a left hand side (LHS) and a right hand side (RHS) like addition, multiplication etc •e.g. 5 + 2 -LHS = 5, RHS = 2

Sentinel value

To find out when we stop looping we look for 'end-cases' -Usually found near words like 'until' or 'while' •Test-values for these 'end-cases' are often called sentinel values -Sometimes enforced by the problem, sometimes we make up our own •What if it doesn't stop? -Infinite loop - VERY BAD!

Common array operations

Total of all elements -Keep a running total •Average of all elements -Similar to total, but with an extra step... •Find the smallest/largest element -How could we do this? •Sort -This one is quite tricky, lots of options

Condition/Action Tables

Used to plan our decisions: Path Which path is this? Condition What condition (result of a decision) lets us know we are on this path? Result What do we do on this path?

Variable

Variables are used to store and describe data; input, output or processing data. A variable is a name we use to refer to a value; the value can change without changing the name. The variable's name allows access to the variable's value.

Function call

When a function is called, the program comes to line of code with "function call'; program goes to first line of function, and executes all the instructions from top to bottom; program leaves the function and returns to where it came from. Any data computed and returned by the function is used in place of the function in the original line of code

Definite vs Indefinite Loops

When a loop begins we ask "How many times will it run?" •if we know the answer - definite loop -Ask the user for a number repeatedly until they have entered five numbers. •if we don't (or can't know) -indefinite loop -Get numbers from the user until they enter zero or less

Categorising problems

Working out what type of problem we are solving

Function or Loop

•if the same algorithm steps appear more than once we can use either -A Loop, or... -A Function •It's important to get this right, so how do we decide? 1 - Look for patterns Position of the duplicate steps: -One copy after another, or -Several different places •One after the other is probably a loop -Possibly a function, depending on variables •Different places is a function 2 - Examine variable values Another option - look at variables, specifically what values they have on each iteration •Are they: -Related to previous values •E.g. increase by 1 each time -Unrelated •E.g. 5 then 10 then 6 then 8 then 1... •Related would be a loop •Unrelated would be a function


Related study sets

Psychology Ch.12: Stress and Health

View Set

Private Pilot Knowledge Test: Chapter 5

View Set