Programming Constructs Notes Software Design & Development: Computational Constructs, Data Types & Structures, Algorithm Specification.

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

Introduction to C Programming
A Level Computing#BristolMet Session Objectives#U2 S2 MUST describe the steps of an algorithm using a program flowchart SHOULD explain the data types and.
Chapter 2: Using Objects Part 1. To learn about variables To understand the concepts of classes and objects To be able to call methods To learn about.
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
Chapter 7: User-Defined Functions II Instructor: Mohammad Mojaddam.
Chapter 10.
Program Elements We can now examine the core elements of programming (as implemented in Java) We focuse on: data types variable declaration and use, constants.
1 CSC 1401 S1 Computer Programming I Hamid Harroud School of Science and Engineering, Akhawayn University
Chapter 7. 2 Objectives You should be able to describe: The string Class Character Manipulation Methods Exception Handling Input Data Validation Namespaces.
Introduction to C Programming
1 Lab Session-III CSIT-120 Spring 2001 Revising Previous session Data input and output While loop Exercise Limits and Bounds GOTO SLIDE 13 Lab session.
C++ fundamentals.
Chapter Seven Advanced Shell Programming. 2 Lesson A Developing a Fully Featured Program.
© The McGraw-Hill Companies, 2006 Chapter 1 The first step.
1 Lab Session-III CSIT-120 Fall 2000 Revising Previous session Data input and output While loop Exercise Limits and Bounds Session III-B (starts on slide.
Elements of a C++ program 1. Review Algorithms describe how to solve a problem Structured English (pseudo-code) Programs form that can be translated into.
A Level Computing#BristolMet Session Objectives U2#S6 MUST identify different data types used in programming aka variable types SHOULD describe each data.
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
Introduction. 2COMPSCI Computer Science Fundamentals.
Characters The data type char represents a single character in Java. –Character values are written as a symbol: ‘a’, ‘)’, ‘%’, ‘A’, etc. –A char value.
Chapter 3 Processing and Interactive Input. 2 Assignment  The general syntax for an assignment statement is variable = operand; The operand to the right.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley STARTING OUT WITH Python Python First Edition by Tony Gaddis Chapter 2 Input,
Input, Output, and Processing
By the end of this session you should be able to...
Chapter 8 High-Level Programming Languages. 8-2 Chapter Goals Describe the translation process and distinguish between assembly, compilation, interpretation,
Software Development Topic 3 High Level Language Constructs.
An Object-Oriented Approach to Programming Logic and Design Fourth Edition Chapter 6 Using Methods.
CPS120: Introduction to Computer Science Decision Making in Programs.
CPS120: Introduction to Computer Science Functions.
Chapter 4: Subprograms Functions for Problem Solving Mr. Dave Clausen La Cañada High School.
CPS120: Introduction to Computer Science Lecture 14 Functions.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
Writing JavaScript Functions. Goals By the end of this unit, you should understand … How to breakdown applications into individual, re-usable modules.
Procedural programming in Java Methods, parameters and return values.
Higher Grade Computing Studies 3. High Level Language Constructs Higher Computing Software Development S. McCrossan 1 Simple Data Types Integer: An integer.
CS161 Topic #16 1 Today in CS161 Lecture #16 Prepare for the Final Reviewing all Topics this term Variables If Statements Loops (do while, while, for)
Introducing Python CS 4320, SPRING Lexical Structure Two aspects of Python syntax may be challenging to Java programmers Indenting ◦Indenting is.
Chapter 3 Syntax, Errors, and Debugging Fundamentals of Java.
I Power Higher Computing Software Development High Level Language Constructs.
Lecture 26: Reusable Methods: Enviable Sloth. Creating Function M-files User defined functions are stored as M- files To use them, they must be in the.
CSC 1010 Programming for All Lecture 3 Useful Python Elements for Designing Programs Some material based on material from Marty Stepp, Instructor, University.
Intermediate 2 Computing Unit 2 - Software Development.
 Software Development Life Cycle  Software Development Tools  High Level Programming:  Structures  Algorithms  Iteration  Pseudocode  Order of.
Higher Computing Science 2016 Prelim Revision. Topics to revise Computational Constructs parameter passing (value and reference, formal and actual) sub-programs/routines,
A FIRST BOOK OF C++ CHAPTER 14 THE STRING CLASS AND EXCEPTION HANDLING.
Fundamental Programming Fundamental Programming Introduction to Functions.
CSCI 51 Introduction to Programming Dr. Joshua Stough February 24, 2009.
Arrays Chap. 9 Storing Collections of Values 1. Introductory Example Problem: Teachers need to be able to compute a variety of grading statistics for.
Selection Using IF THEN ELSE CASE Introducing Loops.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
Marr CollegeHigher Software DevelopmentSlide 1 Higher Computing Software Development Topic 4: Standard Algorithms.
N5 Databases Notes Information Systems Design & Development: Structures and links.
Topics Designing a Program Input, Processing, and Output
User-Written Functions
COMPUTATIONAL CONSTRUCTS
Chapter 8 Text Files We have, up to now, been storing data only in the variables and data structures of programs. However, such data is not available.
Primitive Data Types August 28, 2006 ComS 207: Programming I (in Java)
Variables, Expressions, and IO
User-Defined Functions
Topics Introduction to File Input and Output
2.1 Parts of a C++ Program.
Introduction to Classes and Objects
Chapter 2: Introduction to C++.
Language Constructs Construct means to build or put together. Language constructs refers to those parts which make up a high level programming language.
Topics Designing a Program Input, Processing, and Output
Topics Designing a Program Input, Processing, and Output
Introduction to Computer Science
ENERGY 211 / CME 211 Lecture 8 October 8, 2008.
Topics Introduction to File Input and Output
Presentation transcript:

Programming Constructs Notes Software Design & Development: Computational Constructs, Data Types & Structures, Algorithm Specification

Contents Subprograms  Questions Questions Standard Algorithms  Questions Questions Complex Data Types  Questions Questions File Handling  Questions Questions

Subprogram A subprogram is a block of code in a program that is semi independent from the rest of the program. Subprograms are used in computing because they make a program more readable and modular. Subprograms can be reused by calling them multiple times in a program – they can even be imported into other programs as a part of a library. This is especially important for large programs, where work is split amongst several programmers. A programmer can be tasked to write a subprogram given its header. The header of a subprogram is enough for other programmers to call that subprogram in the code that they are writing. This way they programmers can work independently.

Parameters The parameters of a subprogram are variables that are passed to that subprogram from the part of the program that calls it. By passing different variables to a subprogram as its parameters, the same subprogram can give different results. This allows the same code to be reused multiple times. A subprogram can only use the values that are passed to it, along with any other local variables it creates itself. It cannot access variables created elsewhere in the program

Call by Reference & Call by Value In programming, the parameters passed into a subprogram use one of two differing methods: call by reference and call by value. Different programming languages use different methods - in some cases they use both! With call by value, a copy of the values stored in the variables is passed into the subprogram. If any changes are made to those values inside the program, the changes are not made to the original variables used in the subprogram call. Variables in Python are passed using call by value With call by reference, the memory location of the parameter is passed to the sub program. This means that any changes made to the value stored in the variable will persist outside of the subprogram.

Local & Global Variables All variable have a scope. The scope of a variable is where within the program that the variable can be seen and used Global variables can be accessed throughout the entire program Using global variables is considered to be bad practice. It ties the programmers to working with specific variables and reduces the reusability of subprograms Local variables can only be accessed in the block of code they were created in Once the program exits the scope of a local variable, the value stored inside it is lost

Functions A function is a type of subprogram that returns a value Because they return a value, you can use a function call as part of a variable assignment, including in a calculation. For example: SET area TO getWidth() * getHeight() Functions need to be defined in order to be used. As well as the body of code used in the function, the function header must include it’s name, any parameters (including their type) and a return type. A function must include a statement to return a value to the part of the program that called it. FUNCTION getArea (float length, float width) RETURNS float …function code goes in here… RETURN area END FUNCTION Some programming languages do not require functions to be defined in such detail though

Procedures A procedure is a type of subprogram that completes a given task. Unlike functions, procedures do not return a value Therefore, procedure calls are only made independent statements. They can’t be made as part of an assignment. For example: displayArea(area) As well as the body of code used in the procedure, the procedure header must include it’s name and any parameters (including their type). For example: PROCEDURE displayGrades (str[] names, str[] grades) … procedure code goes in here END PROCEDURE Some programming languages do not require functions to be defined in such detail though. Some programming languages do not make a distinction between functions and procedures. The parameters in the header are known as the formal parameters The parameters in the call are known as the actual parameters

Questions – Subprograms Answer questions in full sentences! 1. List two advantages of using subprograms 2. What is meant by the term parameter? 3. Explain the difference between call by reference parameter passing and call by value parameter passing 4. Explain the difference between a function and a procedure 5. What is meant by the scope of a variable 6. Explain the difference between local and global variables 7. Using pseudocode, write a function that returns the circumference of a circle, given its radius

Standard Algorithms Standard algorithms are simple, generic case, algorithms that can easily be adapted and incorporated into a program to solve a simple task You are required to know a number of standard algorithms at Higher level:  Input validation  Linear search  Finding maximums / minimums  Counting occurrences You are already familiar with input validation from N5

Input validation Input validation is a standard algorithm that can be used to limit user input. If the user enters an unacceptable input, they are prompted to retry until the input is valid Input validation is important as it can be used to keep programs robust and reliable. Input that can potentially cause a runtime error can be rejected by input validation, as can inputs that would result in nonsensical answers The standard algorithm for input validation is:

Linear Search Linear search is a standard algorithm that identifies if a given value is present in an array or list of values Linear search is only one form of search algorithm. It is relatively inefficient compared to other searches, but does not need the values to be sorted into order Linear searches can be programmed to return a boolean noting if the searched for value is present, or an index or indices where the value is present. The boolean version is:

Finding Max / Min Finding maximum and finding minimum are two very simple standard algorithms that can be used to discover the highest and lowest value in an array respectively Find max / min can be programmed to return either the highest / lowest value, or the index / indices which they are found at. This latter case is useful when using two linked arrays, or two dimensional arrays, as you can use that index to identify other values. For example, finding the highest score, then using the index to find the name of the person who scored it

Here is the simple, finding value, version of finding maximum: Here is the simple, finding value, version of finding minimum:

Counting Occurrences Counting occurrences is a standard algorithm that works out how many of the values in an array or list of values meet a given condition The condition can be something as simple as equalling a particular value, but they can also be complicated conditions made up of many parts The algorithm for counting occurrences is:

You can potentially count many different occurrences at the by including multiple if statements. An example would be exam passes and exam grades: Checking the number of passes would only require a single condition and variable: 1) IF value[i] >= 50 THEN 2) SET passes TO passes + 1 3) END IF Checking the number of different grades would require multiple conditions and variables: 1) IF value[i] >= 70 THEN 2) SET A grades TO A grades + 1 3) END IF 4) IF value[i] >= 60 AND value[i] < 70 THEN 5) SET B grades TO B grades + 1 6) END IF …

Questions – Standard Algorithms Adapt the standard algorithms to write algorithms to solve each of the following problems: 1. The input variable percent must be between 0 and The input variable answer must be either yes, no or maybe 3. Find if any of a list of ten heights is greater than 2 metres 4. Check if the input variable my name is present in an array of 10 names 5. Find the most expensive house in a list of 5 house prices 6. Find the lowest scoring test mark from a class of 30 pupils 7. Find out how many positive numbers are in an array of one hundred values 8. Count the number of As, Bs and C grades in a class of twenty pupils

Complex Data Types - Strings Recall that the string data type stores a series of letters, symbols and numeric characters Strings can be considered to be an array of characters. This opens the possibility of addressing individual characters within the string, and even groups of characters within the string – substrings At Higher level you will be required to manipulate strings including:  Splitting strings into substrings and individual characters  Concatenating substrings to make new strings  Manipulating the individual characters within strings – sort of…

Substrings Individual characters and sections of strings can be accessed. Consider this pseudocode: SET message TO “Hello World!” Then the following pseudocode display lines could be used to output part of that “Hello World!” string literal: SEND message[0] TO DISPLAY – prints the letter “H” SEND message[0:5] TO DISPLAY – prints the word “Hello” Similarly substrings can be concatenated and assigned to other variables: SET letters TO message[0] & message[6] – letters will store “HW”

String Operations Recall that pre-defined functions are already created functions that you can use in your program without having to code yourself There are a number of pre defined functions that can be used to manipulate strings. In Python:  len() – returns the length of a string .lower() – returns a lowercase version of the string .strip(char) – removes the specified character from the start and end of the string .split(char) – splits a string into multiple strings using the specified character as a separator .partition(char) – splits a string in two at the first instance of the specified separator character

Manipulating Individual Characters Recall that individual characters are represented in binary using ASCII and Unicode An individual character can therefore also be considered as or converted into a numeric value. This numeric value can be used in the same way as other numeric values Simple arithmetic operations such as + and - can be used to change the value. Comparison operators such as can be used to determine characters position relative to each other in lexicographical order

Records A record is a complex data type that includes multiple named and typed variables. A record can be defined thus: RECORD Person IS {STRING name, INT age} This defines the record of the type Person to contain two variables, a string called name and an integer called age Records are similar to classes in object orientated languages

Assigning Records Records can be assigned to wholly: SET pupil TO Person {“Alice”, 16 } Which creates a new record of the type Person to store Alice’s details Records can be assigned and accessed in part as well: SET pupil.name TO “Carol” Would change the value store in the name variable of the pupil record to be Carol

Questions – Complex Data types Answer questions in full sentences! 1. What is a substring? 2. What is meant by the term concatenating? 3. Explain how the individual characters in a string can have arithmetic and comparison operations carried out upon them 4. List three string operations and describe what they do. Explain why each one might be useful in a program 5. Explain why in some programming languages manipulating strings might be computationally inefficient

6. Explain what is meant by a record 7. Define a record to store the following information a house – its number, street and postcode 8. Create a record of type house called home, filling it with appropriate information

File Handling Previously, all input has come from the KEYBOARD and all output has gone to the DISPLAY Files are an alternate source of input and output for a computer program. A file can contain data which can read into the program. Alternately, a file can have data written to it after the data has been processed by the program. You are required to make use of files for input and output in Higher Computing Science

Reading From Files Before a file can be read from, it must first be opened. In pseudocode: OPEN “myfile.txt” In pseudocode, a file being read from can be treated the same as keyboard input: RECEIVE data FROM “myfile.txt” Most programming languages will read in data on a line by line basis, or as one very long string potentially including carriage return characters. You will typically require to use string operations to break the data into meaningful values for your program. Once finished you should close the file. In pseudocode: CLOSE “myfile.txt”

Writing to files Writing to files is handled similarly. The file must be opened before use and closed when finished with. Alternately a new file can be created instead when writing: CREATE “newfile.txt” Output to a file is the same as output to the screen in pseudocode: SEND “Hello there!” TO “newfile.txt” In practice, different programming languages behave differently when it comes to either writing over existing file contents or appending to previous file contents

Questions – File handling Answer questions in full sentences! 1. What must be done before you can start reading from or writing to a file? 2. What should be done once you are finished reading from or writing to a file? 3. Explain why creating a file can only be used with writing, not reading? 4. Using pseudocode, write a short program which asks the user their name, address and phone number. The program will output this information to a filename of the user’s choice.