1 Week 3 Before we begin…... 2 4CS001 - Lecture 3 Remember Jafa (in Wolf) 4CS001- Lecture 1 2 Enter your normal username/password Some people are not.

Slides:



Advertisements
Similar presentations
Lecture 10 Flow of Control: Loops (Part 2) COMP1681 / SE15 Introduction to Programming.
Advertisements

Introduction to Flowcharting A Supplement to Starting Out with C++, 4th Edition by Tony Gaddis Published by Addison-Wesley.
 Control structures  Algorithm & flowchart  If statements  While statements.
Computer Science 101 Overview of Algorithms. Example: Make Pancakes Prepare batter Beat 2 eggs Add 1 tablespoon of brown sugar Add 1 cup of milk Add 2.
Chapter 4 Control Structures I. Objectives ► Examine relational and logical operators ► Explore how to form and evaluate logical (Boolean) expressions.
1 Week 4 Selection (if..then..else), and Compound Conditions.
Some revision.  Today, we will do some revision on: - ◦ booleans, and ◦ if statements.
2  An instruction or group of instructions need to be repeated several times.  2 types of iteration: 1.You do not know how many times you will need.
© Copyright 1992–2005 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Tutorial 4 – Introducing Algorithms, Pseudocode and.
1 Objectives You should be able to describe: Relational Expressions The if-else Statement Nested if Statements The switch Statement Common Programming.
School of Computing Science CMT1000 Ed Currie © Middlesex University 1 CMT1000: Introduction to Programming Ed Currie Lecture 5B: Branch Statements - Making.
1 Selection Structures. 2 Making Decisions Sample assignment statements to figure worker pay with possible overtime PayAmount = Hours * Rate PayAmount.
CSC103: Introduction to Computer and Programming
1. Know the different types of flow block 2. Understand how problems can be broken down into smaller problems.
PROGRAMMING, ALGORITHMS AND FLOWCHARTS
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
Programming Fundamentals. Today’s lecture Decisions If else …… Switch Conditional Operators Logical Operators.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 4: Control Structures I (Selection)
Scott Marino MSMIS Kean University MSAS5104 Programming with Data Structures and Algorithms Week 5 Scott Marino.
1 Introduction to Flowcharting. 2 Writing a program Defining the problem –Write down what the program will do Planning –Write down the steps, draw a flowchart.
1 Conditions Logical Expressions Selection Control Structures Chapter 5.
Problem Solving with Decisions
2 Objectives You should be able to describe: Relational Expressions Relational Expressions The if-else Statement The if-else Statement Nested if Statements.
Selection Control Structures. Simple Program Design, Fourth Edition Chapter 4 2 Objectives In this chapter you will be able to: Elaborate on the uses.
Conditions. Objectives  Understanding what altering the flow of control does on programs and being able to apply thee to design code  Look at why indentation.
Lecture 2: Logical Problems with Choices. Problem Solving Before writing a program Have a thorough understanding of the problem Carefully plan an approach.
1 Computer Programming (ECGD2102 ) Using MATLAB Instructor: Eng. Eman Al.Swaity Lecture (4): Control Flow (Chapter 2)
PROBLEM SOLVING & ALGORITHMS CHAPTER 5: CONTROL STRUCTURES - SELECTION.
Control Structures (A) Topics to cover here: Introduction to Control Structures in the algorithmic language Sequencing.
An Introduction to Programming with C++ Sixth Edition Chapter 7 The Repetition Structure.
1 COMS 261 Computer Science I Title: C++ Fundamentals Date: September 21, 2005 Lecture Number: 10.
CMP-MX21: Lecture 4 Selections Steve Hordley. Overview 1. The if-else selection in JAVA 2. More useful JAVA operators 4. Other selection constructs in.
Lecture 3 – Selection. Outline Recall selection control structure Types of selection One-way selection Two-way selection Multi-selection Compound statement.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Selection Statements Selection Switch Conditional.
Chapter 7 Selection Dept of Computer Engineering Khon Kaen University.
CHAPTER#3 PART1 STRUCTURED PROGRAM DEVELOPMENT IN C++ 2 nd semester King Saud University College of Applied studies and Community Service Csc.
CMP-MX21: Lecture 5 Repetitions Steve Hordley. Overview 1. Repetition using the do-while construct 2. Repetition using the while construct 3. Repetition.
Control Structures (B) Topics to cover here: Sequencing in C++ language.
Chapter 5: Control Structures I (Selection). Objectives In this chapter you will: Learn about control structures Examine relational and logical operators.
Chapter#3 Part1 Structured Program Development in C++
Control Statements: Part1  if, if…else, switch 1.
1 Flow of Control Chapter 5. 2 Objectives You will be able to: Use the Java "if" statement to control flow of control within your program.  Use the Java.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Decisions and Iterations.
An Introduction to Programming with C++ Sixth Edition Chapter 5 The Selection Structure.
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
Flow Charts And Pseudo Codes Grade 12. An algorithm is a complete step-by- step procedure for solving a problem or accomplishing a task.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
ALGORITHMS AND FLOWCHARTS
CNG 140 C Programming (Lecture set 3)
Repetition (While-Loop) version]
Algorithms and Flowcharts
Operator Precedence Operators Precedence Parentheses () unary
The Selection Structure
ALGORITHM Basic CONCEPTS of Basic Concepts of Algorithm
The order in which statements are executed is called the flow of control. Most of the time, a running program starts at the first programming statement,
Chapter 6: Conditional Statements and Loops
Lecture 2: Logical Problems with Choices
MSIS 655 Advanced Business Applications Programming
1) C program development 2) Selection structure
` Structured Programming & Flowchart
3. Decision Structures Rocky K. C. Chang 19 September 2018
Computer Science Core Concepts
Flowcharts and Pseudo Code
Chapter 4: Boolean Expressions, Making Decisions, and Disk Input and Output Prof. Salim Arfaoui.
Life is Full of Alternatives
CHAPTER 5: Control Flow Tools (if statement)
Basic Concepts of Algorithm
Module 3 Selection Structures 6/25/2019 CSE 1321 Module 3.
Control Structures.
Presentation transcript:

1 Week 3 Before we begin…..

2 4CS001 - Lecture 3 Remember Jafa (in Wolf) 4CS001- Lecture 1 2 Enter your normal username/password Some people are not keeping up-to-date with these.

Directory Structure 3 4CS001 - Lecture 3 If you do not have this structure you can easily create directories using Windows Explorer. You may find it easier than using the command prompt. MyModules 4CS001 Week01 Week02 Week03

4CS001 - Lecture 3 4 Once you have your command prompt window open in the correct directory use the following commands: javac Program3.java to compile your program java Program3 to run your program Compile and run your program

5 Last week on 4CS001

6 Output and Input System.out.print( … ); (no new line) System.out.println( … ); (new line after print) JOptionPane.showMessageDialogue(null, “ … ”); (output) (message) (input) JOptionPane.showInputDialogue(null, “ … ”);

7 Homework for last week was Read chapter 4 of Currie Attempt the new Jafa exercises Finish the workshop for week 2 We assume that you have done these tasks. If you do not keep up-to-date, particularly with Jafa and the workshop exercises, you will find the module tasks more and more difficult.

8 Learning Outcomes This Week To understand three building blocks for structured programming (sequence, selection, and iteration) To introduce the concept of:- –Activity Diagrams with structured programming –And revise boolean expressions and –Jeliot The outcome of the lecture will be: –That you will be able to design simple “programs” involving “sequence” and “selection” using “activity diagrams”. –That you will be able to convert the activity diagram to Java code. –That you will be able to compile and run the code. –That you will be able to use Jeliot.

9 Lecture 3 structured programming concepts, boolean variables, if … then … else statements

10 There are 3 fundamental concepts of Structured Programming: Sequence –One (instruction) statement follows another and the program executes them in sequence. Selection –The next statement to be executed depends on the value of an expression. Iteration –A section of the program may be repeated multiple times. Any program can be constructed with these. Other concepts exist but are not essential Programming Building Blocks

11 Sequence You have already used “sequence” Instructions are performed in sequence starting from the beginning and systematically moving to the end. Every instruction is taken in turn. No instructions are skipped over. Examples: –Cooking recipe –Workshop manual page on how to change your oil filter –Musical score –Map and directions to the University campus

12 Selection Different instructions are performed for different conditions. If you have a 2 litre engine you must unscrew the 4 securing bolts and remove the safety cover before attempting to remove the oil filter. If your engine is not 2 litre you must smash the safety cover with a hammer before attempting to remove the oil filter. 4. Remove the oil filter 4.1 Remove safety cover 4.2 Remove oil filter 4.3 Dispose of filter 4.1 Remove safety cover If engine is 2L Unscrew 4 securing bolts Remove safety cover Else Smash cover with a hammer

13 Iteration (Repetition) An instruction or group of instructions needs to be repeated several times. 2 types of iteration: 1.You do not know how many times you will need to perform the instructions –Instructions contain words like while and until. 2.You do know how many times you need to perform the instructions. –Instructions contain words like for, each and every

14 "While" Iteration We don't know how many times we may have to add milk to get the perfect cuppa. 3. Add milk to cup 3.1. While drink is dark in colour Add a splash of milk Stir once with the spoon 3.2 Remove spoon from cup 4. Add sugar

15 "For" Iteration Before we start chopping we do know how many times instruction will need to be performed. 3. Process vegetables 3.1. Select 4 juicy carrots 3.2. Chop carrots For each carrot Cut the carrot lengthways Cut the carrot widthways 3.3 Add carrots to pan

16 boolean variables are either true or false boolean isEnrolled = false; boolean hasPassed = grade > 40; boolean Variables and Expressions boolean variables can also store the result of relational expressions

17 Exercise int a=10, b=4, c=7, d=4; boolean z = a == b; boolean y = d == b; boolean x = a != b; boolean w = a < b; boolean v = a >= b; boolean t = y; boolean u = d >= b; boolean s = !y; What values do the variables s to z store?

18 Exercise int a=10, b=4, c=7, d=4; boolean z = a == b || d == b; boolean y = a > b && d < c; boolean x = a != b && c != d; boolean w = a <= b || b != d; boolean v = x || w; boolean t = !(x && y); boolean u = x && y && z; boolean s = w == z; What values do the variables s to z store?

Activity Diagrams Remember the algorithm for calculating simple hourly pay (week 1 workshop) ? 1.Get all unknown data values. 1.1 Get employee’s hourly rate 1.2 Get number of weekday hours worked 1.3 Get number of Sunday hours worked 2.Calculate total pay. 2.1 Calculate week-day pay = hourly rate times week-day hours 2.2 Calculate Sunday pay = 1.5 * hourly rate time Sunday hours 2.3 Calculate total pay = week-day pay plus Sunday pay 3.Output total pay. 19 4CS001 - Lecture 3

An activity diagram consists of activities (enclosed in rounded rectangles). Arrows show the sequence in which activities are followed (the control flow). Should be mostly down or to the right. A filled circle and a bulls eye mark the start and end respectively. Activity Diagrams

Simple Hourly Pay 21 4CS001 - Lecture 3 Get employee's hourly rate Get number of Sunday hours Calculate Weekday pay Calculate Sunday pay Calculate total pay Get number of week day hours Output the total pay

Consider this example of a fixed sequence of instructions. int nrPhotoCopies = 60; int costPerCopy = 0.5; int totalCost = costPerCopy * nrPhotoCopies; System.out.print ("The total cost is " ); System.out.println (totalCost); Suppose now that there is a discount of 10% if the number of copies required is greater than 100 otherwise it is the full price. To solve this we need to make some sort of decision so we need different routes through the program Activity Diagrams

An activity diagram consists of activities (enclosed in rounded rectangles). Arrows show the sequence in which activities are followed (the control flow). Diamonds indicate branches to alternative actions (decision points). Selection guards (expressions between square brackets) determine the control flow. A filled circle and a bulls eye mark the start and end respectively. [boolean expression] Activity Diagrams – 2 more “boxes”

We need a way to express giving a discount if the number of copies are greater than 100 [nrCopies>100] Input number of copies Photocopy - Example Cost = Cost – 0.1 * CostCost = price * nrCopiesInput price per copy [nrCopies<=100] Output the Cost

The if statement is used to decide which instructions are executed. This mini algorithm can be expressed as:- The discount is only deducted if the condition is true. totalCost = costPerCopy * nrPhotoCopies; if(nrPhotoCopies > 100) totalCost = totalCost – 0.1*totalCost; if Statement discount

if …. then Statement The ThenClause can either be: –A single instruction or a number of instructions The statement(s) must be enclosed in { and } ( ThenClauseBooleanExp if) int totalCost = costPerCopy * nrPhotoCopies; if (nrPhotoCopies > 100) { int discount = 0.1 * totalCost; totalCost = totalCost – discount; } // end if

if…. then….else Consider an example where a student must achieve at least 40% to pass a test. –An algorithm is required to tell a student whether a test has been passed. –If the result is 40% or more then the test has been passed, otherwise the test is failed. –Algorithm for this is 1 Get the mark 2 IF the mark is greater than or equal to 40 THEN the test is passed ELSE the test is failed

Algorithm as Activity Diagram [true] Input mark Output “Passed” Output “failed” mark >= 40 [false] else branch if branch

Exercise-Temperature Conversion We need an algorithm for a program to convert Celsius to Fahrenheit, and the reverse. The formulae for both conversions are: To solve this we devise a pseudo code algorithm that: –Gets the temperature (could be Fahrenheit or Celsius) as a double, and –Gets an integer which has the value “1” to choose converting from Celsius to Fahrenheit, or “2” for converting Fahrenheit to Celsius. Then we express the algorithm as an Activity Diagram. F = 9*C/ C = (F – 32)*5/9

Temperature Conversion 30 Input temperature [N] Fahrenheit = (9*temp/5)+32 Celsius = (temp-32)*5/9 Input indicatorOutput Fahrenheit indicator = 1 [Y] if (FAH) branch Else (CELS) branch Output Celsius

if …. then …. else The instructions in the ThenClause are executed if the Boolean expression evaluates to true. The instructions in the ElseClause are executed if the Boolean expression evaluates to false. ( ThenClauseBooleanExp if) ElseClause else

An aside – Logical Operators The standard comparison operators are: Logical combination operators 32 4CS001 - Lecture 3 Is less than is equal to is greater than >= != <= Is greater than is NOT equal to is less than or equal to or equal to && || ! and or not e.g. if (a<b && a<c) {…} "if a is less than b and a is less than c"

Common error 33 4CS001 - Lecture 3 // Assignment: a “becomes equal to” 10. a = 10; // Comparison: if a “is equal to” 10 if (a == 10) { } if (a = 10){ } What does this line of code do?

Using comparison operators if (a == 10) { a = (a+x); } if ((a < c) || (a < 10)) { a = 5 } 34 4CS001 - Lecture 3

Review Today you have seen –How Selection can be performed in Java using “if” and “if... then … else” statements. –How selection and flow of control can be shown in an Activity Diagram. –How to perform a “Dry Run” on code to understand the flow of control and changing of variable values. –How useful Boolean expressions can be.

36 Homework Read Chapter 5 of Currie. Attempt the new Jafa exercises. Do the workshop for week 3. Become familiar with how to use Jeliot. Do the find the mistakes and dry run exercise.