3. S/E with Control Structures 3.1 Relational Operators and Expressions 3.2 If and if-else Statements 3.3 The Type Double 3.4 Program Design with the While.

Slides:



Advertisements
Similar presentations
Control Structures.
Advertisements

Chapter 4: Control Structures I (Selection)
3-1 Chapter 3 Flow of Control (part a - branching)
Control Structures Selections Repetitions/iterations
Flow of Control Usually the order of statement execution through a method is linear: one after another flow of control: the order statements are executed.
1 Chapter 3:Operators and Expressions| SCP1103 Programming Technique C | Jumail, FSKSM, UTM, 2006 | Last Updated: July 2006 Slide 1 Operators and Expressions.
Discussion1 Quiz. Q1 Which of the following are invalid Java identifiers (variable names)? a) if b) n4m3 c) Java d) e) DEFAULT_VALUE f) bad-choice.
Logic & program control part 2: Simple selection structures.
CS-1010 Dr. Mark L. Hornick 1 Selection Statements and conditional expressions.
Chapter 4 Control Structures I. Objectives ► Examine relational and logical operators ► Explore how to form and evaluate logical (Boolean) expressions.
Slide 1 Summary Two basic concepts: variables and assignments Some C++ practical issues: division rule, operator precedence  Sequential structure of a.
5-1 Flow of Control Recitation-01/25/2008  CS 180  Department of Computer Science  Purdue University.
Introduction to Computers and Programming Lecture 5 New York University.
Week 10 Recap CSE 115 Spring For-each loop When we have a collection and want to do something to all elements of that collection we use the for-each.
Conditions What if?. Flow of Control The order of statement execution is called the flow of control Unless specified otherwise, the order of statement.
COMP 14 Introduction to Programming Miguel A. Otaduy May 18, 2004.
ECE122 L7: Conditional Statements February 20, 2007 ECE 122 Engineering Problem Solving with Java Lecture 7 Conditional Statements.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
General Computer Science for Engineers CISC 106 Lecture 33 Dr. John Cavazos Computer and Information Sciences 05/11/2009.
Boolean Expressions and If Flow of Control / Conditional Statements The if Statement Logical Operators The else Clause Block statements Nested if statements.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie June 30, 2005.
CSci 125 Lecture 10 Martin van Bommel. Simple Statements Expression followed by semicolon Assignments total = n1 + n2; Function calls printf(”Hello.\n”);
Chapter 3: Program Statements
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 7.1 Test-Driving the Wage Calculator Application.
Programming in Java (COP 2250) Lecture 11 Chengyong Yang Fall, 2005.
© 2006 Pearson Education 1 Obj: to use compound Boolean statements HW: p.184 True/False #1 – 6 (skip 3)  Do Now: 1.Test your “Charge Account Statement”
CSCI 1100/1202 January 28, The switch Statement The switch statement provides another means to decide which statement to execute next The switch.
Chapter 3: Program Statements
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
© 2000 Scott S Albert Selection Structures Structured Programming 256 Chapter 4.
If…else statements. Boolean Expressions Boolean expression - An expression whose value is either true or false true = 1 false = 0 Datatype: boolean.
Basic Control Structures
Programming 1 DCT 1033 Control Structures I (Selection) if selection statement If..else double selection statement Switch multiple selection statement.
Computing with C# and the.NET Framework Chapter 3 Software Engineering with Control Structures.
Flow of Control Unless indicated otherwise, the order of statement execution through a method is linear: one after the other in the order they are written.
ICT Introduction to Programming Chapter 4 – Control Structures I.
Chapter#3 Part1 Structured Program Development in C++
School of Computer Science & Information Technology G6DICP - Lecture 4 Variables, data types & decision making.
CS 240 – Computer Programming I Lab Kalpa Gunaratna –
Conditionals Opening Discussion zWhat did we talk about last class? zDo you have any questions about the assignment? zPass by value limitations.
Control statements Mostafa Abdallah
Copyright 2008 by Pearson Education Building Java Programs Chapter 4 Lecture 4-1: if and if/else Statements reading: 4.2 self-check: #4-5, 7, 10, 11 exercises:
1 Program Development  The creation of software involves four basic activities: establishing the requirements creating a design implementing the code.
CS-1010 Dr. Mark L. Hornick 1 Selection and Iteration and conditional expressions.
Sum of Arithmetic Sequences. Definitions Sequence Series.
Operators A binary operator combines two values to get one result: x OP y where OP is any binary operators such as +, -, *, /, ==, !=, >, &&, or even =.
ECE 122 Feb. 8, if Statement A condition is an expression that can be either true, or false. “if” statement allows a program to make a decision.
 Type Called bool  Bool has only two possible values: True and False.
if ( condition ) statement; if is a Java reserved word The condition must be a boolean expression. It must evaluate to either true or false.
Relational Operator and Operations
Sequence, Selection, Iteration The IF Statement
Operator Precedence Operators Precedence Parentheses () unary
Boolean Expressions & the ‘if’ Statement
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,
C# and the .NET Framework
Logical Operators & Truth Tables.
Alice in Action with Java
Chapter 3: Program Statements
Bools and simple if statements
Flow Control Statements
Summary Two basic concepts: variables and assignments Basic types:
The if Statement Control structure: logical design that controls order in which set of statements execute Sequence structure: set of statements that execute.
Expressions.
Conditionals and Loops
Flow of Control Flow of control is the order in which a program performs actions. Up to this point, the order has been sequential. A branching statement.
SEQUENCE Start Initial situation Step 1 Step 2 Step 3 End
The boolean type and boolean operators
CprE 185: Intro to Problem Solving (using C)
Presentation transcript:

3. S/E with Control Structures 3.1 Relational Operators and Expressions 3.2 If and if-else Statements 3.3 The Type Double 3.4 Program Design with the While Loop 3.5 Debugging 3.6 Getting Started with Objects and Applets: Drawing Shapes

Objectives Learn the basic sequence, selection, and repetition statements Identify objects and their responsibilities Simple debugging techniques Handle floating-point numbers Study applets, draw various shapes

3.1 Relational Operators and Expressions Relational operators include:, >=, ==, and != Each relational operator takes two operands and gives a boolean value: true or false Be careful not to confuse == with = Relational operators have precedence lower than arithmetic operators but higher than assignment operators

Figure 3.2 Java relational and equality operators is true292 != 377not equal to!= is false9 == equal to== is false9 >= 99greater than or equal to>= is false-98 > -12greater than> is true464 <= 7213less than or equal to<= is false31 < 25less than< ExampleMeaningOperator Symbol

Control Flow The order Java executes the statements of a program is sequential if not told otherwise int item1 = 25; int item2 = 12; item2 = item1 + 15; Conditional statement like the if and if-else statements allow us to make decision They change the default control flow

Figure 3.3 The sequence control flow Entry int item1 = 25; int item2 = 12; Item2 = item1+15; Exit

3.2 The if and if-else statements The syntax if ( condition ) if_true_statement ; [ else if_false_statement ; ] condition must be boolean : true or false If condition is true, if_true_statement is executed; if the condition is false, if_false_statement is executed One or the other will be executed, but not both

Figure 3.4 Control flow for the if statement condition False if_true_statement

The if Statement: Example hours = Integer.parseInt(input); if (hours > 40) System.out.println(“You worked overtime “ + “this week”); System.out.println(“You worked “ + hours + “ hours”);

Figure 3.5 Control Flow for Example 3.2 hours = Integer.parselnt(input); Hours>40 System.out.println( “you worked ” + hours + “ hours”); False System.out.println(“You “ + “worked overtime this week”) True

Figure 3.6 Flow chart for the if-else statement Condition if_true_statementif_false_statement TrueFalse

The if-else Statement: Example if (hours <= 40) wage = hourlyRate * hours; else wage = hourlyRate * 40 + hourlyRate * 1.5 * (hours - 40);

Block Statements Several statements can be grouped together into a block statement A block is delimited by braces ( { … } ) A block statement can be used wherever a statement is called for in the Java syntax For example, in an if-else statement, the if-portion, or the else-portion, or both, could be block statements

Figure 3.7 Flow chart for if statement with block, step 1 Z <= 10 True False x = 2; y = 7;

Figure 3.8 Flow chart if statement with block, step 2 Z <= 10 x = 2; True False y = 7;

Block Statements Use a consistent style for blocks if (x < 10) { y = 5; z = 8; } else { y = 9; z = -2; } if (x < 10) { y = 5; z = 8; } else { y = 9; z = -2; }

3.3 The Type Double Scientific (floating-point) notation for real numbers: and can be written respectively as E E is the mantissa, 3 and -2 are the exponents, with the implicit base of 10 Scientific notation is good for numbers with very small or very large absolute value Java has type double that provides 16 decimal digits accurately.

public class Triangle { private double side1, side2, side3; public Triangle(double a, double b, double c) { side1 = a; side2 = b; side3 = c; } public double circumference() { return side1 + side2 + side3; } public double area() { double s = circumference() / 2.0; return Math.sqrt(s*(s - side1)*(s - side2)*(s - side3)); }

Double Value Output When printed using print or println methods of System.out, Java prints double values using the most convenient format Scientific format for numbers greater than 10,000,000 or less than -10,000,000, and for numbers between and.001. Java treats decimal literals as type double Java does not print trailing zeroes Type double is accurate to 16 significant digits The 17th digit may be rounded

Input and Formatted Output import javax.swing.*; import java.text.*; … public static void main(String[] args) { NumberFormat nf = NumberFormat.getCurrentcyInstance(); String s = JOptionPane.showInputDialog(“Hours worked? “); double hours = Double.parseDouble(s); JOptionPane.showMessageDialog (null, “Your pay is “ + nf.format(hours * 5.5)); System.exit(0); }

Formatted Output The NumberFormat class has static methods that return formatter object getCurrencyInstance() getPercentInstance() Each formatter object has a method called format that returns a string with the specific information in the appropriate format The DecimalForma t class can be used to format a floating point value in generic way The DecimalFormat class takes a string that represents a pattern for the formatted number

Data Conversions Sometimes it is convenient to convert data from one type to another Conversion must be handled carefully to avoid losing information Widening conversions are safest because they tend to go from a small data type to a larger one (such as a short to an int ) Narrowing conversions can lose information because they tend to go from a larger data type to a smaller one (such as an int to a short )

Data Conversions In Java, data conversions can occur in three ways: –assignment conversion –arithmetic promotion –casting Assignment conversion occurs when a value of one type is assigned to a variable of another type –Only widening conversion can happen via assignment Arithmetic promotion happens automatically when operators in expressions converts their operands Casting is the most powerful, and dangerous, technique for conversion result = (float) total / count;

Figure 3.9 Conversion of mixed-mode expression 2.54 Original expression After Conversion

3.4 The While Loop Repetition statements allow us to execute a statement multiple times repetitively They are often referred to as loops Like if-else statements, they are controlled by boolean expressions’ Java has three kinds of repetition statements: the while loop, the do loop, and the for loop The while loop has this syntax while ( condition ) while_true_statement ;

The While Loop If the condition is true, the statement is executed Then the condition is evaluated again The statement is executed repetitively until the condition becomes false If the condition is false initially, then the statement is never executed The body of a while loop must eventually make the condition false If not, it is an infinite loop, which is a common logical error unless you are absolutely sure it is not

Figure 3.10 Flow chart for the while loop Condition while_true_statement FalseTrue

Problem Solving The purpose of writing a program is to solve a problem The general steps in problem solving are: –Understand the problem –Dissect the problem –Design a solution –Consider alternatives to the solution and refine it –Implement the solution –Test the solution and fix and problems that exist

Problem Solving Many software development project failed because the developers didn’t understand the problems to be solved Avoid assumptions and clarify ambiguities As problems and their solutions becomes larger, we must organize our development into manageable pieces We will dissect our solutions into pieces called classes and objects, taking an object-oriented approach

Program Development The creation of software involves four basic activities: –establishing the requirements –creating a design –implementing the code –testing the implementation Real development process is much more involved than this, but these four steps are a good starting point

Requirements Requirements specify the tasks a program must accomplish (what to do, not how to do it) They often include description of the user interface The initial requirements must be critiqued, modified, and expanded It is often difficult to establish detailed, unambiguous, and complete requirements Careful attention to the requirements can save significant time and money in the overall project

Design An algorithm is a step-by-step process for solving a problem A program follow one or more algorithms The design of a program specifies the algorithms and data needed In object-oriented development, the design establishes the classes, their data and methods The details of a method may be expressed in pseudocode, which is code-like, but does not necessarily follow any specific syntax

Implementation Implementation is the process of translating a design into source code Most novice programmers think that writing code is the heart of software development, but it is actually the least creative step Almost all important decisions are made during requirements analysis and design Implementation should focus on coding details, including guidelines, clarity, maintainability, expandability, and documentation

Testing A program should be executed multiple times with various input in an attempt to find errors Debugging is the process of discovering the cause of a problem and fix it Debugging can only indicate the presence of errors (bugs), but not the absence Don’t ever think there is only one more bug to fix tests should focus on design details as well as overall requirements

Figure 3.11 Pseudocode for the sum of test scores problem Read the quantity of scores; while (count < quantity) { Read the next score; Add the score to the total so far; Increment the count of scores; } Display the quantity and the total;

3.5 Debugging Syntax error –caught by the compiler –easy to fix Run-time error –reported at run-time by interpreter –often depending on input and environment –usually cause program to terminate immaturely Logical error –program runs but results are wrong –can be very difficult to find and/or fix Requirement error –disastrous

3.6 Getting Started with Applets A java application is a stand-alone program with a main method An applet is a Java program that is intended to be transported over the web and executed using a web browser An applet doesn’t have a main method Instead, there are several special methods that serve specific purposes The paint method, for instance, is automatically executed and is used to draw the applets contents

Drawing Shapes The paint method accepts a parameter that is an object of the Graphics class A Graphics object defines a graphical context on which we can draw shapes and text The Graphics class has several methods for drawing shapes The class that defines the applet extends the Apple t class This makes use of inheritance, an object-oriented concept to be explored later

Figure 3.12 Drawing a line (70,80) (130,230)

Figure 3.13 Drawing a rectangle (50,50)

Figure 3.14 An oval with its bounding rectangle

Figure 3.15 Degree measure around a circle 0º0º 270º 180º 90º

Figure 3.16 An arc from the oval of Figure º45º

Figure 3.17 The structure of a rounded rectangle

Dimension d = getSize(); int w = d.width; int h = d.height; g.drawRect(2*w/3,0,w/3,h/3); Figure 3.19 Drawing a rectangle relative to the applet's size