Flow of Control. Conditional Statements. Boolean Expressions. CMPT 125: Lecture 4 Conditionals and Loops
|
|
- Stephen Douglas
- 7 years ago
- Views:
Transcription
1 Flow of Control CMPT 125: Lecture 4 Conditionals and Loops Tamara Smyth, tamaras@cs.sfu.ca School of Computing Science, Simon Fraser University January 17, 2009 The order in which statements are executed is called the flow of control. Unless otherwise specified, the flow of control is linear, that is, statements are executed in the order in which they occur. Java begins a program on the first statement of the main method. A change in the flow of control can be accomplished by: invoking a method conditional statements loops or some combination. 1 CMPT 125: Conditionals and Loops, Lecture 4 2 Conditional Statements Boolean Expressions A conditional statement allow us to choose which statement will be executed next. Java has three conditional statements: 1. if- 2. if 3. switch These statements allow us to decide which statement to execute next based on a condition, that is, the outcome of a boolean expression. Recall that a boolean is a data type that evaluates to either true or false. A boolean statement also evaluates to true or false, and may consist solely of a single variable, or a larger statement involving a logical operator. boolean hungry = false; //hungry is a boolean if (hungry) System.out.println( Let s go eat! ); system.out.println( Let s go for a drink instead. ); The if statement allows a program to choose whether to execute a particular statement. if (num > 20) System.out.println( Count is over 20. ); system.out.println( Count is less than or equal to 20. ); CMPT 125: Conditionals and Loops, Lecture 4 3 CMPT 125: Conditionals and Loops, Lecture 4 4
2 Evaluating Boolean Expressions Logical NOT Boolean expressions are evaluated using: equality operators: == test whether two values ARE equal!= test whether two values ARE NOT equal relational operators: > test whether one value is greater than another < test whether one value is less than another >= greater than or equal <= less than or equal logical operators:! logical NOT && logical AND logical OR Logical operators take boolean operands The logical NOT is unary, and has only two possible values: true or false. boolean hungry = false; if (!hungry) system.out.println( Let s go for a drink instead. ); OUTPUT: Let s go for a drink instead. The! is used to perform the logical NOT, or logical complement, that is, it returns the opposite value. boolean hungry = true; if (!hungry) System.out.println( Let s go for a drink instead. ); System.out.println( Let s go eat. ); OUTPUT: Let s go eat. CMPT 125: Conditionals and Loops, Lecture 4 5 CMPT 125: Conditionals and Loops, Lecture 4 6 Logical AND, OR Precedence of Operators Logical AND, OR are binary operators that use two operands, both of which are boolean. The result of a logical AND operation is true if and only if both operands are true, but false otherwise. The result of a logical OR operation is true if one, or both, of the operands are true, but false otherwise. There are four possible combinations of two logical operands a and b: a b a && b a b false false false false false true false true true false false true true true true true Operators in order of precedence: 1. logical NOT (highest) 2. logical AND 3. logical OR if (!done && (count > MAX)) System.out.println( Completed ); To print or not to print. Let s look at the truth table which tells us all the possible combinations of values for the variables involved. done count > MAX!done!done && (count > MAX) false false true false false true true true true false false false true true false false CMPT 125: Conditionals and Loops, Lecture 4 7 CMPT 125: Conditionals and Loops, Lecture 4 8
3 Example code using if-, if Short Circuiting Operations public class testnum public static void main(string[] args) int num = Integer.parseInt(args[0]); if (num > 5) System.out.println(num + " > 5"); if (num > 4) System.out.println(num + " > 4"); if (num > 2) System.out.println(num + " > 2"); System.out.println(num + " is 2 or less"); The AND and OR operators may be short-circuited meaning that is the left operand is sufficient to decide the boolean result, the right operand is not evaluated. You can use this to your advantage by ensuring variables will not result in an expression that is undefined, e.g. preventing a division by zero. if (count!= 0 && total/count > MAX) System.out.println( Testing ); An equivalent way of achieving the same result would involve nesting the if statements: if (count!= 0) if (total/count > MAX) System.out.println( Testing ); CMPT 125: Conditionals and Loops, Lecture 4 9 CMPT 125: Conditionals and Loops, Lecture 4 10 Block Statement A Loop, or Repetitive Statement An if statement consists of the reserved word if followed by a boolean expression, followed by one or more statements. That is, a single statement can be replaced with a block statement, a collection of statements enclosed in braces. if (guess == answer) System.out.println( You re right! ); System.out.println( I m sorry. ); System.out.println( The correct answer is + answer); It is common practice, and very important to the human reader, to indent the statement(s) following the boolean expression to show they are part of the if statement. A loop, or repetitive statement, allows us to execute a programming statement more than once. Like a conditional, a loop is based on the evaluation of a boolean expression Java has three loop statements: 1. while 2. do 3. for CMPT 125: Conditionals and Loops, Lecture 4 11 CMPT 125: Conditionals and Loops, Lecture 4 12
4 The while Statement The Conditional Operator A while statement is followed by a boolean expression, and evaluates a statement, or a block of code, repeatedly, while the condition remains true. public static void main(string[] args) int sum = 0, value, count = 0; Scanner scan = new Scanner(System.in); System.out.println("Enter an integer (0 to quit): "); value = scan.nextint(); while(value!= 0) count++; sum += value; System.out.println("The sum so far is " + sum); System.out.println("Enter an integer (0 to quit): "); value = scan.nextint(); if (count==0) System.out.println("No values were entered."); DecimalFormat fmt = new DecimalFormat("0.###"); System.out.println("The average is " + fmt.format((double)sum/count)); Avoid infinite loops! CMPT 125: Conditionals and Loops, Lecture 4 13 When using the conditional operator, a boolean condition is followed by the? operator which is followed by two expressions separated by the : operator. boolean condition? 1st expression Figure 1: The conditional operator. : 2nd expression The first of the two expression is evaluated if the boolean condition is true, and if false, the second expression is evaluated. The following is an example use of the conditional operator A ternary operator because it requires three operands. (total > MAX)? total + 1 : total * 2; The Conditional operator returns a value, and therefore might be used as follows: total = (total > MAX)? total + 1 : total * 2; CMPT 125: Conditionals and Loops, Lecture 4 14 Comparing Floats Comparing Characters Two floating point values are equal, according to the == operator, only if all the binary digits of their underlying representations match. Since this is unlikely to be the case (perhaps due to rounding errors), it is best not to use this operator for comparing floating point values. A better way computes the absolute value of the difference between the two, and then compare the result to some tolerance level. Equality and relational operators may also be used on character data. Because of the Unicode character set, it is possible to determine if one is less than another. if (ch1 > ch2) System.out.println(ch1 + is greater than + ch2); System.out.println(ch1 + is NOT greater than + ch2); if (Math.abs(f1-f2) < TOLERANCE) System.out.println( Effectively equal. ); CMPT 125: Conditionals and Loops, Lecture 4 15 CMPT 125: Conditionals and Loops, Lecture 4 16
5 Comparing Objects The switch Statement The String class contains an equals method that returns true if two strings have exactly the same characters, and false otherwise. if (name1.equals(name2)) System.out.println( The names are the same. ); System.out.println( The names are NOT the same. ); It is valid to test two String objects using using the equality operator, but it will test whether they reference the same object: String name1 = new String( string ); String name2 = new String( string ); if (name1 == name2) System.out.println( These variables contain + the same address. ); System.out.println( These variables contain + different addresses. ); OUTPUT: These variables contain different addresses. CMPT 125: Conditionals and Loops, Lecture 4 17 The switch statement evaluates an expression to determine a value. It then matches that value with one of several possible cases. switch(grade) case A : System.out.println( Excellent Work! ); break; case B : System.out.println( Good Work. ); break; case C : System.out.println( Satisfactory Work. ); break; default: System.out.println( Error in identifying your grade! ); If no case matches the evaluated expression, execution continues with the default case. When a break statement is encountered, the program exits the switch statement, and continues with the next statement. CMPT 125: Conditionals and Loops, Lecture 4 18 Nested Loops The body of a loop can contain another loop. public class Palindrome public static void main(string[] args) String str, another = "y"; int left, right; Scanner scan = new Scanner(System.in); while(another.equalsignorecase("y")) System.out.println("Enter a palindrome"); str = scan.nextline(); left = 0; right = str.length() - 1; while(str.charat(left) == str.charat(right) && left < right) left++; right--; System.out.println(); if (left<right) System.out.println("The string is NOT a palindrome."); System.out.println("The string IS a palindrome."); System.out.print("Test another palindrome (y/n)?"); another = scan.nextline(); CMPT 125: Conditionals and Loops, Lecture 4 19 CMPT 125: Conditionals and Loops, Lecture 4 20
6 Iterators The do statement An iterator is an object that has methods that allow you to process a collection of items one at a time. Since it is a repetitive process, it is related to loops. An iterator in Java is defined using the Iterator interface. The Scanner class has methods such as hasnext, hasnextint, hasnextdouble, to determine if the next input token is of a particular type. The Scanner class as an iterator is useful when processing a data file or processing parts of a character string. A delimiter is used to separate tokens in a Scanner object. The do loop executes the statement in the loop until the condition, written at the end of of the loop, becomes false. int count = 0; do count++; System.out.println(count); while (count < 5); A do statement executes its loop body at least once. This may give you reason to choose a do, rather than a while loop. filescan.usedelimeter( ; ); CMPT 125: Conditionals and Loops, Lecture 4 21 CMPT 125: Conditionals and Loops, Lecture 4 22 The for statement Iterators and for loops The do and while loops are usually used when you don t know exactly how many times you want to execute the loop body. The for loop is suited to situations where you know precisely how many times the loop should be executed. for (int count = 0; count < 10; count++) System.out.println(count); The header of a for loop contains three parts separated by semicolons: 1. initialization: executed before the loop begins. 2. boolean condition: evaluated before the loop body; if true the loop is executed. 3. increment: executed after each loop iteration. It is also possible to decrement a value: A variation of the for loop lets us process the items in an iterator with a different syntax. Consider the iterator Booklist that manages Book objects: for(book mybook : BookList) System.out.println(myBook); is equivalent to Book mybook; while (BookList.hasNext()) mybook = BookList.next(); System.out.println(myBook); This version can also be used on arrays. for (int count = 10; count > 0; count--) System.out.println(count); CMPT 125: Conditionals and Loops, Lecture 4 23 CMPT 125: Conditionals and Loops, Lecture 4 24
Chapter 2: Elements of Java
Chapter 2: Elements of Java Basic components of a Java program Primitive data types Arithmetic expressions Type casting. The String type (introduction) Basic I/O statements Importing packages. 1 Introduction
More informationIntroduction to Java
Introduction to Java The HelloWorld program Primitive data types Assignment and arithmetic operations User input Conditional statements Looping Arrays CSA0011 Matthew Xuereb 2008 1 Java Overview A high
More informationConditionals (with solutions)
Conditionals (with solutions) For exercises 1 to 27, indicate the output that will be produced. Assume the following declarations: final int MAX = 25, LIMIT = 100; int num1 = 12, num2 = 25, num3 = 87;
More information1) Which of the following is a constant, according to Java naming conventions? a. PI b. Test c. x d. radius
Programming Concepts Practice Test 1 1) Which of the following is a constant, according to Java naming conventions? a. PI b. Test c. x d. radius 2) Consider the following statement: System.out.println("1
More informationIntroduction to Java. CS 3: Computer Programming in Java
Introduction to Java CS 3: Computer Programming in Java Objectives Begin with primitive data types Create a main class with helper methods Learn how to call built-in class methods and instance methods
More informationFile class in Java. Scanner reminder. Files 10/19/2012. File Input and Output (Savitch, Chapter 10)
File class in Java File Input and Output (Savitch, Chapter 10) TOPICS File Input Exception Handling File Output Programmers refer to input/output as "I/O". The File class represents files as objects. The
More informationMULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.
Exam Name MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question. 1) The JDK command to compile a class in the file Test.java is A) java Test.java B) java
More informationBuilding Java Programs
Building Java Programs Chapter 3 Lecture 3-3: Interactive Programs w/ Scanner reading: 3.3-3.4 self-check: #16-19 exercises: #11 videos: Ch. 3 #4 Interactive programs We have written programs that print
More information5.2 Q2 The control variable of a counter-controlled loop should be declared as: a.int. b.float. c.double. d.any of the above. ANS: a. int.
Java How to Program, 5/e Test Item File 1 of 5 Chapter 5 Section 5.2 5.2 Q1 Counter-controlled repetition requires a.a control variable and initial value. b.a control variable increment (or decrement).
More informationCSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals
CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals 1 Recall From Last Time: Java Program import java.util.scanner; public class EggBasket { public static void main(string[]
More informationLOOPS CHAPTER CHAPTER GOALS
jfe_ch04_7.fm Page 139 Friday, May 8, 2009 2:45 PM LOOPS CHAPTER 4 CHAPTER GOALS To learn about while, for, and do loops To become familiar with common loop algorithms To understand nested loops To implement
More informationCS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013
Oct 4, 2013, p 1 Name: CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013 1. (max 18) 4. (max 16) 2. (max 12) 5. (max 12) 3. (max 24) 6. (max 18) Total: (max 100)
More informationReading Input From A File
Reading Input From A File In addition to reading in values from the keyboard, the Scanner class also allows us to read in numeric values from a file. 1. Create and save a text file (.txt or.dat extension)
More informationBuilding Java Programs
Building Java Programs Chapter 3 Lecture 3-3: Interactive Programs w/ Scanner reading: 3.3-3.4 self-check: #16-19 exercises: #11 videos: Ch. 3 #4 Interactive programs We have written programs that print
More informationSystem.out.println("\nEnter Product Number 1-5 (0 to stop and view summary) :
Benjamin Michael Java Homework 3 10/31/2012 1) Sales.java Code // Sales.java // Program calculates sales, based on an input of product // number and quantity sold import java.util.scanner; public class
More informationObject Oriented Software Design
Object Oriented Software Design Introduction to Java - II Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa October 28, 2010 G. Lipari (Scuola Superiore Sant Anna) Introduction
More informationCompSci 125 Lecture 08. Chapter 5: Conditional Statements Chapter 4: return Statement
CompSci 125 Lecture 08 Chapter 5: Conditional Statements Chapter 4: return Statement Homework Update HW3 Due 9/20 HW4 Due 9/27 Exam-1 10/2 Programming Assignment Update p1: Traffic Applet due Sept 21 (Submit
More informationHandout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.
Handout 1 CS603 Object-Oriented Programming Fall 15 Page 1 of 11 Handout 1 Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner. Java
More informationLecture 2 Notes: Flow of Control
6.096 Introduction to C++ January, 2011 Massachusetts Institute of Technology John Marrero Lecture 2 Notes: Flow of Control 1 Motivation Normally, a program executes statements from first to last. The
More informationObject Oriented Software Design
Object Oriented Software Design Introduction to Java - II Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa September 14, 2011 G. Lipari (Scuola Superiore Sant Anna) Introduction
More informationJ a v a Quiz (Unit 3, Test 0 Practice)
Computer Science S-111a: Intensive Introduction to Computer Science Using Java Handout #11 Your Name Teaching Fellow J a v a Quiz (Unit 3, Test 0 Practice) Multiple-choice questions are worth 2 points
More informationMIDTERM 1 REVIEW WRITING CODE POSSIBLE SOLUTION
MIDTERM 1 REVIEW WRITING CODE POSSIBLE SOLUTION 1. Write a loop that computes (No need to write a complete program) 100 1 99 2 98 3 97... 4 3 98 2 99 1 100 Note: this is not the only solution; double sum
More informationJAVA - QUICK GUIDE. Java SE is freely available from the link Download Java. So you download a version based on your operating system.
http://www.tutorialspoint.com/java/java_quick_guide.htm JAVA - QUICK GUIDE Copyright tutorialspoint.com What is Java? Java is: Object Oriented Platform independent: Simple Secure Architectural- neutral
More information9 Control Statements. 9.1 Introduction. 9.2 Objectives. 9.3 Statements
9 Control Statements 9.1 Introduction The normal flow of execution in a high level language is sequential, i.e., each statement is executed in the order of its appearance in the program. However, depending
More informationBasics of Java Programming Input and the Scanner class
Basics of Java Programming Input and the Scanner class CSC 1051 Algorithms and Data Structures I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website: www.csc.villanova.edu/~map/1051/
More informationAP Computer Science Java Mr. Clausen Program 9A, 9B
AP Computer Science Java Mr. Clausen Program 9A, 9B PROGRAM 9A I m_sort_of_searching (20 points now, 60 points when all parts are finished) The purpose of this project is to set up a program that will
More informationKeywords are identifiers having predefined meanings in C programming language. The list of keywords used in standard C are : unsigned void
1. Explain C tokens Tokens are basic building blocks of a C program. A token is the smallest element of a C program that is meaningful to the compiler. The C compiler recognizes the following kinds of
More informationName: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.
Name: Class: Date: Exam #1 - Prep True/False Indicate whether the statement is true or false. 1. Programming is the process of writing a computer program in a language that the computer can respond to
More informationBuilding Java Programs
Building Java Programs Chapter 4 Lecture 4-1: Scanner; if/else reading: 3.3 3.4, 4.1 Interactive Programs with Scanner reading: 3.3-3.4 1 Interactive programs We have written programs that print console
More informationBoolean Expressions & the if Statement
Midterm Results Boolean Expressions & the if Statement September 24, 2007 Average: 91.6 Median: 94 Standard Deviation: 18.80 Maximum: 129 (out of 130) ComS 207: Programming I (in Java) Iowa State University,
More informationFirst Java Programs. V. Paúl Pauca. CSC 111D Fall, 2015. Department of Computer Science Wake Forest University. Introduction to Computer Science
First Java Programs V. Paúl Pauca Department of Computer Science Wake Forest University CSC 111D Fall, 2015 Hello World revisited / 8/23/15 The f i r s t o b l i g a t o r y Java program @author Paul Pauca
More informationSelection Statements
Chapter 5 Selection Statements 1 Statements So far, we ve used return statements and expression ess statements. e ts. Most of C s remaining statements fall into three categories: Selection statements:
More informationJDK 1.5 Updates for Introduction to Java Programming with SUN ONE Studio 4
JDK 1.5 Updates for Introduction to Java Programming with SUN ONE Studio 4 NOTE: SUN ONE Studio is almost identical with NetBeans. NetBeans is open source and can be downloaded from www.netbeans.org. I
More informationEmbedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C
Embedded Systems A Review of ANSI C and Considerations for Embedded C Programming Dr. Jeff Jackson Lecture 2-1 Review of ANSI C Topics Basic features of C C fundamentals Basic data types Expressions Selection
More informationTopic 11 Scanner object, conditional execution
Topic 11 Scanner object, conditional execution "There are only two kinds of programming languages: those people always [complain] about and those nobody uses." Bjarne Stroustroup, creator of C++ Copyright
More informationIntroduction to Java Applications. 2005 Pearson Education, Inc. All rights reserved.
1 2 Introduction to Java Applications 2.2 First Program in Java: Printing a Line of Text 2 Application Executes when you use the java command to launch the Java Virtual Machine (JVM) Sample program Displays
More informationTranslating to Java. Translation. Input. Many Level Translations. read, get, input, ask, request. Requirements Design Algorithm Java Machine Language
Translation Translating to Java Introduction to Computer Programming The job of a programmer is to translate a problem description into a computer language. You need to be able to convert a problem description
More informationMoving from CS 61A Scheme to CS 61B Java
Moving from CS 61A Scheme to CS 61B Java Introduction Java is an object-oriented language. This document describes some of the differences between object-oriented programming in Scheme (which we hope you
More informationJavaScript: Control Statements I
1 7 JavaScript: Control Statements I 7.1 Introduction 2 The techniques you will learn here are applicable to most high-level languages, including JavaScript 1 7.2 Algorithms 3 Any computable problem can
More informationCOSC 1020 3.0 Introduction to Computer Science I Section A, Summer 2005. Question Out of Mark A Total 16. B-1 7 B-2 4 B-3 4 B-4 4 B Total 19
Term Test #2 COSC 1020 3.0 Introduction to Computer Science I Section A, Summer 2005 Family Name: Given Name(s): Student Number: Question Out of Mark A Total 16 B-1 7 B-2 4 B-3 4 B-4 4 B Total 19 C-1 4
More informationObject-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007
Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007 The Java Type System By now, you have seen a fair amount of Java. Time to study in more depth the foundations of the language,
More informationSample CSE8A midterm Multiple Choice (circle one)
Sample midterm Multiple Choice (circle one) (2 pts) Evaluate the following Boolean expressions and indicate whether short-circuiting happened during evaluation: Assume variables with the following names
More informationOutline. Conditional Statements. Logical Data in C. Logical Expressions. Relational Examples. Relational Operators
Conditional Statements For computer to make decisions, must be able to test CONDITIONS IF it is raining THEN I will not go outside IF Count is not zero THEN the Average is Sum divided by Count Conditions
More informationChapter 2 Introduction to Java programming
Chapter 2 Introduction to Java programming 1 Keywords boolean if interface class true char else package volatile false byte final switch while throws float private case return native void protected break
More information1.00/1.001 - Session 2 Fall 2004. Basic Java Data Types, Control Structures. Java Data Types. 8 primitive or built-in data types
1.00/1.001 - Session 2 Fall 2004 Basic Java Data Types, Control Structures Java Data Types 8 primitive or built-in data types 4 integer types (byte, short, int, long) 2 floating point types (float, double)
More informationqwertyuiopasdfghjklzxcvbnmqwerty uiopasdfghjklzxcvbnmqwertyuiopasd fghjklzxcvbnmqwertyuiopasdfghjklzx cvbnmqwertyuiopasdfghjklzxcvbnmq
qwertyuiopasdfghjklzxcvbnmqwerty uiopasdfghjklzxcvbnmqwertyuiopasd fghjklzxcvbnmqwertyuiopasdfghjklzx cvbnmqwertyuiopasdfghjklzxcvbnmq Introduction to Programming using Java wertyuiopasdfghjklzxcvbnmqwertyui
More informationWriting Control Structures
Writing Control Structures Copyright 2006, Oracle. All rights reserved. Oracle Database 10g: PL/SQL Fundamentals 5-1 Objectives After completing this lesson, you should be able to do the following: Identify
More informationCS 121 Intro to Programming:Java - Lecture 11 Announcements
CS 121 Intro to Programming:Java - Lecture 11 Announcements Next Owl assignment up, due Friday (it s short!) Programming assignment due next Monday morning Preregistration advice: More computing? Take
More informationUnit 6. Loop statements
Unit 6 Loop statements Summary Repetition of statements The while statement Input loop Loop schemes The for statement The do statement Nested loops Flow control statements 6.1 Statements in Java Till now
More informationIntroduction to Python
Caltech/LEAD Summer 2012 Computer Science Lecture 2: July 10, 2012 Introduction to Python The Python shell Outline Python as a calculator Arithmetic expressions Operator precedence Variables and assignment
More information13 File Output and Input
SCIENTIFIC PROGRAMMING -1 13 File Output and Input 13.1 Introduction To make programs really useful we have to be able to input and output data in large machinereadable amounts, in particular we have to
More informationExample of a Java program
Example of a Java program class SomeNumbers static int square (int x) return x*x; public static void main (String[] args) int n=20; if (args.length > 0) // change default n = Integer.parseInt(args[0]);
More informationJava Basics: Data Types, Variables, and Loops
Java Basics: Data Types, Variables, and Loops If debugging is the process of removing software bugs, then programming must be the process of putting them in. - Edsger Dijkstra Plan for the Day Variables
More informationTopics. Parts of a Java Program. Topics (2) CS 146. Introduction To Computers And Java Chapter Objectives To understand:
Introduction to Programming and Algorithms Module 2 CS 146 Sam Houston State University Dr. Tim McGuire Introduction To Computers And Java Chapter Objectives To understand: the meaning and placement of
More informationInformatica e Sistemi in Tempo Reale
Informatica e Sistemi in Tempo Reale Introduction to C programming Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa October 25, 2010 G. Lipari (Scuola Superiore Sant Anna)
More informationProgramming Languages CIS 443
Course Objectives Programming Languages CIS 443 0.1 Lexical analysis Syntax Semantics Functional programming Variable lifetime and scoping Parameter passing Object-oriented programming Continuations Exception
More informationDecision-making Computer Science Lesson to Prepare for UIL Computer Science Contest
Decision-making Computer Science Lesson to Prepare for UIL Computer Science Contest Lesson Plan Title: Decision-making Goal of Lesson: To provide students an opportunity to learn how to use if statements
More informationCSE 1223: Introduction to Computer Programming in Java Chapter 7 File I/O
CSE 1223: Introduction to Computer Programming in Java Chapter 7 File I/O 1 Sending Output to a (Text) File import java.util.scanner; import java.io.*; public class TextFileOutputDemo1 public static void
More informationComp 248 Introduction to Programming
Comp 248 Introduction to Programming Chapter 2 - Console Input & Output Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal, Canada These slides has been
More informationChapter 5. Selection 5-1
Chapter 5 Selection 5-1 Selection (Decision) The second control logic structure is selection: Selection Choosing between two or more alternative actions. Selection statements alter the sequential flow
More informationJava Interview Questions and Answers
1. What is the most important feature of Java? Java is a platform independent language. 2. What do you mean by platform independence? Platform independence means that we can write and compile the java
More informationInstall Java Development Kit (JDK) 1.8 http://www.oracle.com/technetwork/java/javase/downloads/index.html
CS 259: Data Structures with Java Hello World with the IntelliJ IDE Instructor: Joel Castellanos e-mail: joel.unm.edu Web: http://cs.unm.edu/~joel/ Office: Farris Engineering Center 319 8/19/2015 Install
More informationChapter 3 Operators and Control Flow
Chapter 3 Operators and Control Flow I n this chapter, you will learn about operators, control flow statements, and the C# preprocessor. Operators provide syntax for performing different calculations or
More informationQUIZ-II QUIZ-II. Chapter 5: Control Structures II (Repetition) Objectives. Objectives (cont d.) 20/11/2015. EEE 117 Computer Programming Fall-2015 1
QUIZ-II Write a program that mimics a calculator. The program should take as input two integers and the operation to be performed. It should then output the numbers, the operator, and the result. (For
More informationSources: On the Web: Slides will be available on:
C programming Introduction The basics of algorithms Structure of a C code, compilation step Constant, variable type, variable scope Expression and operators: assignment, arithmetic operators, comparison,
More informationScoping (Readings 7.1,7.4,7.6) Parameter passing methods (7.5) Building symbol tables (7.6)
Semantic Analysis Scoping (Readings 7.1,7.4,7.6) Static Dynamic Parameter passing methods (7.5) Building symbol tables (7.6) How to use them to find multiply-declared and undeclared variables Type checking
More informationInteractive Applications (CLI) and Math
Interactive Applications (CLI) and Math Interactive Applications Command Line Interfaces The Math Class Example: Solving Quadratic Equations Example: Factoring the Solution Reading for this class: L&L,
More informationPart I. Multiple Choice Questions (2 points each):
Part I. Multiple Choice Questions (2 points each): 1. Which of the following is NOT a key component of object oriented programming? (a) Inheritance (b) Encapsulation (c) Polymorphism (d) Parallelism ******
More informationBasic Java Constructs and Data Types Nuts and Bolts. Looking into Specific Differences and Enhancements in Java compared to C
Basic Java Constructs and Data Types Nuts and Bolts Looking into Specific Differences and Enhancements in Java compared to C 1 Contents Hello World Program Statements Explained Java Program Structure in
More informationComputer Programming I
Computer Programming I COP 2210 Syllabus Spring Semester 2012 Instructor: Greg Shaw Office: ECS 313 (Engineering and Computer Science Bldg) Office Hours: Tuesday: 2:50 4:50, 7:45 8:30 Thursday: 2:50 4:50,
More informationHandout 3 cs180 - Programming Fundamentals Spring 15 Page 1 of 6. Handout 3. Strings and String Class. Input/Output with JOptionPane.
Handout 3 cs180 - Programming Fundamentals Spring 15 Page 1 of 6 Handout 3 Strings and String Class. Input/Output with JOptionPane. Strings In Java strings are represented with a class type String. Examples:
More informationJava Crash Course Part I
Java Crash Course Part I School of Business and Economics Institute of Information Systems HU-Berlin WS 2005 Sebastian Kolbe skolbe@wiwi.hu-berlin.de Overview (Short) introduction to the environment Linux
More informationDebugging. Common Semantic Errors ESE112. Java Library. It is highly unlikely that you will write code that will work on the first go
Debugging ESE112 Java Programming: API, Psuedo-Code, Scope It is highly unlikely that you will write code that will work on the first go Bugs or errors Syntax Fixable if you learn to read compiler error
More informationChapter 2. println Versus print. Formatting Output withprintf. System.out.println for console output. console output. Console Input and Output
Chapter 2 Console Input and Output System.out.println for console output System.out is an object that is part of the Java language println is a method invoked dby the System.out object that can be used
More informationWA2099 Introduction to Java using RAD 8.0 EVALUATION ONLY. Student Labs. Web Age Solutions Inc.
WA2099 Introduction to Java using RAD 8.0 Student Labs Web Age Solutions Inc. 1 Table of Contents Lab 1 - The HelloWorld Class...3 Lab 2 - Refining The HelloWorld Class...20 Lab 3 - The Arithmetic Class...25
More informationjava.util.scanner Here are some of the many features of Scanner objects. Some Features of java.util.scanner
java.util.scanner java.util.scanner is a class in the Java API used to create a Scanner object, an extremely versatile object that you can use to input alphanumeric characters from several input sources
More informationJAVA.UTIL.SCANNER CLASS
JAVA.UTIL.SCANNER CLASS http://www.tutorialspoint.com/java/util/java_util_scanner.htm Copyright tutorialspoint.com Introduction The java.util.scanner class is a simple text scanner which can parse primitive
More informationWhile Loop. 6. Iteration
While Loop 1 Loop - a control structure that causes a set of statements to be executed repeatedly, (reiterated). While statement - most versatile type of loop in C++ false while boolean expression true
More informationJAVA ARRAY EXAMPLE PDF
JAVA ARRAY EXAMPLE PDF Created By: Umar Farooque Khan 1 Java array example for interview pdf Program No: 01 Print Java Array Example using for loop package ptutorial; public class PrintArray { public static
More informationComputers. Hardware. The Central Processing Unit (CPU) CMPT 125: Lecture 1: Understanding the Computer
Computers CMPT 125: Lecture 1: Understanding the Computer Tamara Smyth, tamaras@cs.sfu.ca School of Computing Science, Simon Fraser University January 3, 2009 A computer performs 2 basic functions: 1.
More informationStatements and Control Flow
Contents 1. Introduction 2. Types and Variables 3. Statements and Control Flow 4. Reading Input 5. Classes and Objects 6. Arrays 7. Methods 8. Scope and Lifetime 9. Utility classes 10. Introduction to
More information6. Control Structures
- 35 - Control Structures: 6. Control Structures A program is usually not limited to a linear sequence of instructions. During its process it may bifurcate, repeat code or take decisions. For that purpose,
More informationUIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming
UIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming 1 2 Foreword First of all, this book isn t really for dummies. I wrote it for myself and other kids who are on the team. Everything
More informationIntroduction to Java Lecture Notes. Ryan Dougherty redoughe@asu.edu
1 Introduction to Java Lecture Notes Ryan Dougherty redoughe@asu.edu Table of Contents 1 Versions....................................................................... 2 2 Introduction...................................................................
More informationJava Program Coding Standards 4002-217-9 Programming for Information Technology
Java Program Coding Standards 4002-217-9 Programming for Information Technology Coding Standards: You are expected to follow the standards listed in this document when producing code for this class. Whether
More informationBuilding Java Programs
Building Java Programs Chapter 5 Lecture 5-2: Random Numbers reading: 5.1-5.2 self-check: #8-17 exercises: #3-6, 10, 12 videos: Ch. 5 #1-2 1 The Random class A Random object generates pseudo-random* numbers.
More informationClasses and Objects in Java Constructors. In creating objects of the type Fraction, we have used statements similar to the following:
In creating objects of the type, we have used statements similar to the following: f = new (); The parentheses in the expression () makes it look like a method, yet we never created such a method in our
More informationVB.NET Programming Fundamentals
Chapter 3 Objectives Programming Fundamentals In this chapter, you will: Learn about the programming language Write a module definition Use variables and data types Compute with Write decision-making statements
More informationWe will learn the Python programming language. Why? Because it is easy to learn and many people write programs in Python so we can share.
LING115 Lecture Note Session #4 Python (1) 1. Introduction As we have seen in previous sessions, we can use Linux shell commands to do simple text processing. We now know, for example, how to count words.
More informationUsing Files as Input/Output in Java 5.0 Applications
Using Files as Input/Output in Java 5.0 Applications The goal of this module is to present enough information about files to allow you to write applications in Java that fetch their input from a file instead
More informationIn this Chapter you ll learn:
Now go, write it before them in a table, and note it in a book. Isaiah 30:8 To go beyond is as wrong as to fall short. Confucius Begin at the beginning, and go on till you come to the end: then stop. Lewis
More informationChapter 2: Algorithm Discovery and Design. Invitation to Computer Science, C++ Version, Third Edition
Chapter 2: Algorithm Discovery and Design Invitation to Computer Science, C++ Version, Third Edition Objectives In this chapter, you will learn about: Representing algorithms Examples of algorithmic problem
More informationScanner. It takes input and splits it into a sequence of tokens. A token is a group of characters which form some unit.
Scanner The Scanner class is intended to be used for input. It takes input and splits it into a sequence of tokens. A token is a group of characters which form some unit. For example, suppose the input
More informationChapter One Introduction to Programming
Chapter One Introduction to Programming 1-1 Algorithm and Flowchart Algorithm is a step-by-step procedure for calculation. More precisely, algorithm is an effective method expressed as a finite list of
More informationTwo-way selection. Branching and Looping
Control Structures: are those statements that decide the order in which individual statements or instructions of a program are executed or evaluated. Control Structures are broadly classified into: 1.
More informationThe following program is aiming to extract from a simple text file an analysis of the content such as:
Text Analyser Aim The following program is aiming to extract from a simple text file an analysis of the content such as: Number of printable characters Number of white spaces Number of vowels Number of
More informationIntroduction to Programming
Introduction to Programming Lecturer: Steve Maybank Department of Computer Science and Information Systems sjmaybank@dcs.bbk.ac.uk Spring 2015 Week 2b: Review of Week 1, Variables 16 January 2015 Birkbeck
More informationCSE 8B Midterm Fall 2015
Name Signature Tutor Student ID CSE 8B Midterm Fall 2015 Page 1 (XX points) Page 2 (XX points) Page 3 (XX points) Page 4 (XX points) Page 5 (XX points) Total (XX points) 1. What is the Big-O complexity
More informationSoftware Engineering Techniques
Software Engineering Techniques Low level design issues for programming-in-the-large. Software Quality Design by contract Pre- and post conditions Class invariants Ten do Ten do nots Another type of summary
More information