# Java I/O and Control Structures

Size: px
Start display at page:

## Transcription

1 Java I/O and Control Structures CSC 2014 Java Bootcamp Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Some slides in this presentation are adapted from the slides accompanying Java Software Solutions by Lewis & Loftus Java Bootcamp Dr. Papalaskari Villanova University

2 Algorithms in everyday life Source:

3 Algorithms An algorithm is a specific set of instructions for carrying out a procedure or solving a problem, usually with the requirement that the procedure terminate at some point. Specific algorithms sometimes also go by the name method, procedure, or technique. The word "algorithm" is a distortion of al-khwārizmī, a Persian mathematician who wrote an influential treatise about algebraic methods. Sources: and Wikipedia ( )

4 Algorithm Example: Input-Compute-Output pattern GPA problem: Write a program that computes and outputs the GPA, given the credits and quality points earned. Pseudocode: describe steps in simple, unambiguous language Variables: qp, credits, gpa Algorithm: 1. Input qp 2. Input credits 3. gpa = qp / credits 4. Print gpa

5 Java Program è Variables: qp, credits, gpa Algorithm: 1. Input qp 2. Input credits 3. gpa = qp / credits 4. Print gpa Next: A closer look at input in Java //********************************************* // GPA.java Author: Joyce/Papalaskari // Demonstrates the use of Scanner input and s //********************************************* import java.util.scanner; public class GPA public static void main (String[] args) // // Inputs the quality points and credits an // double qp, credits, gpa; Scanner scan = new Scanner(System.in); // get input System.out.print ("Enter Quality Points > qp = scan.nextint(); System.out.print ("Enter Credits > "); credits = scan.nextint(); // output information entered System.out.println ("\nquality Points: " System.out.println ("Credits: " + // calculate and output GPA gpa = qp / credits; System.out.println ("\n\tgpa: " + gpa); } }

6 Interactive Programs Input/Output Programs can use data obtained during runtime, eg: int age; String name; Scanner scan = new Scanner(System.in); output method System.out.print( Enter your name ); name = scan.nextline(); input method System.out.print( Enter your age ); age = scan.nextint(); );

7 Interactive Programs Input/Output In Java, you first need to create a Scanner object int age; String name; Scanner object Scanner scan = new Scanner(System.in); System.out.print( Enter your name ); name = scan.nextline(); input method (for String) System.out.print( Enter your age ); age = scan.nextint(); input method (for int)

8 Reading Input The Scanner class is part of the java.util class library, and must be imported into a program in order to be used The import statement goes at beginning of your program (above class definition) import java.util.scanner;

9 Using the Scanner class 1. import the class, i.e., add this before the class definition of your program: import java.util.scanner; 2. In your main method, before doing any input, declare and initialize the Scanner object Scanner scan = new Scanner(System.in); 3. Input away! System.out.print( Enter your name ); name = scan.nextline(); System.out.print( Enter your age ); age = scan.nextint();string

10 Example import java.util.scanner;!! public class TellMeAboutYou!! public static void main(string[] args)!! int age;! String name;!! Scanner scan = new Scanner(System.in);!! System.out.print("Enter your name");! name = scan.nextline();!! System.out.print("Enter your age");! age = scan.nextint();!! System.out.println("Pleased to meet you, " + name + "!");! System.out.println("Your age in dog years: " + age*10.5);! }! } name = scan.nextline();! Enter your name: Fiona Enter your age: 17 Pleased to meet you, Fiona! Your age in dog years is Inspired by:

11 Input methods nextint() à input an int nextdouble() à input a double nextline() à input a String (until end of line) next() à input a String token (one word or other delimited chunk of text) White space (space, tab, new line) are used to separate input tokens

12 Control flow Sequence of statements that are actually executed in a program statement 1 statement 2 statement 3 statement 4

13 Control flow Sequence of statements that are actually executed in a program Conditional and Repetition statements: enable us to alter control flow statement 1 statement 1 statement 2 true statement 2 condition 1 false statement 3 condition 2 true statement 4 statement 4 false statement 3 This slide dapted from Wayne&Sedgewick Princeton course:

14 Java Conditional statements alter the linear flow of control. They use boolean expressions to determine what to do next. Example: A boolean expression if (credits == 0) System.out.println ("GPA: None"); if true, do this else if more than one statement, enclose in braces } gpa = qp / credits; if false, do these System.out.println ("\n\tgpa: " + gpa);

15 Java relational operators relational operators can be used with numeric types and produce boolean results: == equal to!= not equal to < less than > greater than <= less than or equal to >= greater than or equal to Note the difference between the equality operator (==) and the assignment operator (=)

16 Conditional statements if ( condition ) statement; // no else clause if ( condition ) statement1; else statement2; condition evaluated false condition evaluated false true true statement statement 1 statement2

17 Example: How do we fix output to use singular/plural as appropriate? For example: Enter the total amount to be given as change: 18 That amount can be given as: 0 quarters get rid of this! 1 dimes 1 nickels 3 pennies

18 Nested loops statement 1 statement 1; if (condition 1) true condition 1 false statement 2; statement 2 else if (condition 2) condition 2 true statement 4 statement 4; false else statement 3; statement 3 statement 5; statement 5 This slide dapted from Wayne&Sedgewick Princeton course:

19 Another example: Create an application called Vacation that prompts for and inputs an integer representing someone s age and then suggests an appropriate vacation destination. One of three destinations should be suggested depending on whether the answer is less than 20, between 20 and 50, or over 50. For example, a run of the program might look like this: How old is the traveler > 15 You should consider Hershey Park.

20 Java Logical Operators logical operators can be used with boolean operands to express more complex boolean conditions:! Logical NOT && Logical AND Logical OR

21 Vacation example revisited: Create an application called Vacation that prompts for and inputs an integer representing someone s age and then suggests an appropriate vacation destination. One of three destinations should be suggested depending on whether the answer is less than 20, between 20 and 50, or over 50. For example, a run of the program might look like this: How old is the traveler > 15 You should consider Hershey Park.

22 Boolean Expressions The reserved words true and false are the only valid values for a boolean type Example: boolean variables: boolean aboveagelimit = false; boolean useplural = hours > 1; boolean expression using a relational operator

23 Example total 103 if (total < MAX+5 &&!found) System.out.println ("Processing "); MAX 100 found false All logical operators have lower precedence than the relational operators The! operator has higher precedence than && and

24 Logical NOT The logical NOT operation is also called logical negation or logical complement If some boolean condition a is true, then!a is false; if a is false, then!a is true Logical expressions can be shown using a truth table: a!a true false false true

25 Logical AND and Logical OR The logical AND expression a && b is true if both a and b are true, and false otherwise The logical OR expression a b is true if a or b or both are true, and false otherwise

26 Logical AND and Logical OR A truth table shows all possible true-false combinations of the terms Since && and each have two operands, there are four possible combinations of conditions a and b a b a && b a b true true true true true false false true false true false true false false false false

27 Quick Check 1 What do the following statements do? if (total!= stock + warehouse) inventoryerror = true; total 20 stock 8 warehouse 12 inventoryerror false if (found!done) System.out.println("Ok"); found false done true

28 Quick Check 2 Try again with different values if (total!= stock + warehouse) inventoryerror = true; total 20 stock 7 warehouse 12 inventoryerror false if (found!done) System.out.println("Ok"); found false done false

29 Quick Check 3 Try again with different values if (total!= stock + warehouse) inventoryerror = true; total 20 stock 8 warehouse 12 inventoryerror true if (found!done) System.out.println("Ok"); found true done false

30 Boolean Expressions using truth tables let s try this one: found done!done found!done false false false true true false true true

31 Boolean Expressions using truth tables another example: total < MAX found!found total < MAX &&!found false false false true true false true true

32 How much of a boolean expression do we need to evaluate before determining its value? *** Short-Circuited Operators The processing of && and is short-circuited in cases where the left operand is sufficient to determine the result (the right operand is not evaluated at all) This can be both useful and dangerous! if (count!= 0 && total/count > MAX) System.out.println ("Testing.");

33 Indentation Revisited Remember that indentation is for the human reader, and is ignored by the computer if (total > MAX) System.out.println ("Error!!"); errorcount = errorcount + 1;; Despite what is implied by the indentation, the increment will occur whether the condition is true or not

34 Selection structures in Java Conditional statement: if (n > 0) System.out.print("positive"); else System.out.print("negative"); Other selection structures (Chapter 6 in text) the conditional operator the switch statement

35 The Conditional Operator Syntax condition? expression1 : expression2 If the condition is true, expression1 is evaluated; if it is false, expression2 is evaluated The value of the entire conditional operator is the value of the selected expression Example: Rewrite this à if (n > 0) System.out.print("positive"); else System.out.print("negative");

36 The conditional operator is not a statement WRONG!

37 More examples: int bit = (ans == Y )? 1: 0); String status = (age < 18? "child" : "adult"); The conditional operator requires three operands so it is sometimes called the ternary operator

38 Quick Check System.out.println ("Your change is " + num + "Dimes")); Rewrite this statement so that "Dime" is printed if num equals 1.

39 The switch Statement: multi-way branches Recall: Logic of an if-else statement

40 The switch Statement: multi-way branches switch statement logic expression evaluated statement1 case: 1 case: 2 statement2 case: 3 statement3 Note: this is a simplified flowchart of the logic of the switch statement

41 The switch Statement - example public String tostring() String result = ""; switch (facevalue) case 1: result = "one"; break; case 2: result = "two"; break; case 3: result = "three"; break; } return result; }

42 The switch Statement in general switch ( expression ) case value1 : statement-list1 case value2 : statement-list2 case value3 : statement-list3... default: statement-list-n } integer, char, or enumerated types (Java 7 also allows Strings) NO floating point values NO ranges of values (eg: 0<x<10) If expression matches value2, control jumps to here If none of the values match the expression, control jumps to here

43 So the logic of the switch is more like this: expression evaluated statements1 statements2 statements3 Note: this is still a simplified flowchart of the logic of the switch statement

44 GradeReport.java //******************************************************************** // GradeReport.java Author: Lewis/Loftus // // Demonstrates the use of a switch statement. //******************************************************************** import java.util.scanner; public class GradeReport // // Reads a grade from the user and prints comments accordingly. // public static void main (String[] args) int grade, category; continue Scanner scan = new Scanner (System.in); System.out.print ("Enter a numeric grade (0 to 100): "); grade = scan.nextint(); category = grade / 10; System.out.print ("That grade is ");

45 Sample Run continue Enter a numeric grade (0 to 100): 91 switch (category) That grade is well above average. Excellent. case 10: System.out.println ("a perfect score. Well done."); break; case 9: System.out.println ("well above average. Excellent."); break; case 8: System.out.println ("above average. Nice job."); break; case 7: System.out.println ("average."); break; case 6: System.out.println ("below average. You should see the"); System.out.println ("instructor to clarify the material " + "presented in class."); break; default: System.out.println ("not passing."); } } } Hands on: try removing one of the break statements

46 Control flow: Repetition Sequence of statements that are actually executed in a program Conditional and Repetition statements: enable us to alter control flow statement 1 true boolean 1 false statement 2 statement 1 statement 3 boolean 2 true statement 2 statement 4 false statement 3 This slide dapted from Doug Clark s course

47 Example Investment problem: You put \$10,000 into a bank account that earns 5% interest per year. year interest balance 0 \$10, \$ \$10, \$ \$11, \$ \$ \$ \$12, How many years does it take for the account balance to be double the original? This example is adapted from Cay Horstmann s Big Java, Early Objects, 5 th edition

48 Example Investment problem: You put \$10,000 into a bank account that earns 5% interest per year. How many years does it take for the account balance to be double the original? Algorithm:

49 The while Statement A while statement has the following syntax: while ( condition ) statement; If the condition is true, the statement is executed Then the condition is evaluated again, and if it is still true, the statement is executed again The statement is executed repeatedly until the condition becomes false

50 Logic of a while Loop condition evaluated true false statement

51 Example A counting loop that prints the numbers 1, 2, 3, Algorithm: initialize a counter to 1 while the counter <= upper limit print counter increment counter

52 The while Statement int count = 1; while (count <= 3) System.out.println (count); count++; }

53 The while Statement count 1 Initialize count int count = 1; while (count <= 3) System.out.println (count); count++; }

54 The while Statement count 1 int count = 1; count <= 3 is true while (count <= 3) System.out.println (count); count++; }

55 The while Statement int count = 1; while (count <= 3) Print count System.out.println (count); count++; } Output: 1 count 1

56 The while Statement int count = 1; while (count <= 3) System.out.println (count); count++; } Output: 1 count 2 Increment count

57 The while Statement count 2 int count = 1; count <= 3 is true while (count <= 3) System.out.println (count); count++; } Output: 1

58 The while Statement int count = 1; while (count <= 3) Print count System.out.println (count); count++; } Output: 1 2 count 2

59 The while Statement int count = 1; while (count <= 3) System.out.println (count); count++; } Output: 1 2 count 3 Increment count

60 The while Statement count 3 int count = 1; count <= 3 is true while (count <= 3) System.out.println (count); count++; } Output: 1 2

61 The while Statement int count = 1; while (count <= 3) Print count System.out.println (count); count++; } Output: count 3

62 The while Statement int count = 1; while (count <= 3) System.out.println (count); count++; } Output: count 4 Increment count

63 The while Statement count 4 int count = 1; count <= 3 is false while (count <= 3) System.out.println (count); count++; } Output: 1 2 3

64 The while Statement unraveled int count = 1; while (count <= 3) System.out.println(count); count++; } Output: int count = 1; count TEST:(count <= 3)è true 1 System.out.println(count); count++; } TEST:(count <= 3)è true System.out.println(count); count++; } TEST:(count <= 3)è true System.out.println(count); count++; } TEST:(count <= 3)è false EXIT LOOP count 2 count 3 count 4

65 Example Table of squares and cubes: N N 2 N

66

67 Example Table of powers: Compute the powers of 2 and the powers of 3 and print a table like this: N 2 N 3 N

68

69 What s wrong with this code? int count = 1; while (count <= 10) System.out.println (count); count++;

70 What s wrong with this code? int count = 1; while (count <= 10); System.out.println (count); count++; }

71 If the condition of a while loop is false initially, the statement is never executed System.out.println( input a number >5 ); int num = scan.nextint(); // input validation while (num <= 5) System.out.println ( type a number >5 ); num = scan.nextint(); } Therefore, the body of a while loop will execute zero or more times

72 Nested loops Example: Investment problem repetition è the repeated action (calculating the number of years it take for investment to double) involves repetition General pattern for algorithms: A nested loop while (condition for repeating action) initialize variables while (condition for reaching goal) calculations print results

73 Quick Check How many times will the string "Here" be printed? count1 = 1; while (count1 <= 10) count2 = 1; while (count2 < 20) System.out.println ("Here"); count2 = count2++; } count1 = count1++; } Copyright 2012 Pearson Education, Inc.

74 More repetition structures: do & for loops Repetition structure in Java, so far: while loop int count = 0; while (count < 5) } System.out.println (count); count++; Other repetition structures (Chapter 6 in text) the do loop the for loop

75 The do Statement in Java A do statement has the following syntax: do statement-list; } while (condition); //end do The statement-list is executed once initially, and then the condition is evaluated The statement-list is executed repeatedly until the condition becomes false

76 The while and do loops are similar. int count = 0; while (count < 5) System.out.println (count); count++; } int count = 0; do System.out.println (count); count++; } while (count < 5);

77 Similar but not the same: while Loop do Loop condition evaluated true statement int count = 0; while (count < 5) System.out.println (count); count++; } false true statement condition evaluated false int count = 0; do System.out.println (count); count++; } while (count < 5); The body of a do loop executes at least once

78 For some things the do loop is more appropriate: System.out.println( input a number >5 ); int num = scan.nextint(); while (num <= 5) System.out.println ( type a number >5 ); num = scan.nextint(); } do System.out.println ( type a number >5 ); num = scan.nextint(); } while (num <= 5) input validation

79 For some things the do loop is more appropriate: boolean more = true; while (more) System.out.print( Enter Quality Points "); qp = scan.nextint(); System.out.print ("Enter Credits "); credits = scan.nextint(); gpa = (double) qp /credits; System.out.println("GPA = " + gpa); System.out.print ("Again? 1=yes, 0=no "); more = (1 == scan.nextint()); } System.out.println("Thank you. Goodbye. "); do System.out.print( Enter Quality Points "); qp = scan.nextint(); System.out.print ("Enter Credits "); credits = scan.nextint(); gpa = (double) qp /credits; System.out.println("GPA = " + gpa); System.out.print ("Again? 1=yes, 0=no "); } while (1 == scan.nextint()) System.out.println("Thank you. Goodbye. "); repeating a computation

80 Another example: ReverseNumber.java //******************************************************************** // ReverseNumber.java Author: Lewis/Loftus Sample Run // Demonstrates the use of a do loop. //******************************************************************** Enter a positive integer: 2896 import java.util.scanner; That number reversed is 6982 public class ReverseNumber // // Reverses the digits of an integer mathematically. // public static void main (String[] args) int number, lastdigit, reverse = 0; Scanner scan = new Scanner (System.in); System.out.print ("Enter a positive integer: "); number = scan.nextint(); do lastdigit = number % 10; reverse = (reverse * 10) + lastdigit; number = number / 10; } while (number > 0); } } System.out.println ("That number reversed is " + reverse); Copyright 2012 Pearson Education, Inc.

81 for: a loop with built in counter initialization condition evaluated true false statement increment

82 for: a loop with built in counter initialization int count = 0; Example condition evaluated true statement false while (count < 5) System.out.println (count); increment } count++;

83 for: a loop with built in counter for (int count = 0; count < 5; count++) System.out.println (count); initialization int count = 0; Example condition evaluated true statement false while (count < 5) System.out.println (count); increment } count++;

84 The for Statement A for loop is functionally equivalent to the following while loop structure: initialization; while ( condition ) statement; increment; } for ( initialization ; condition ; increment ) statement;

85 The for Statement A for statement has the following syntax: The initialization is executed once before the loop begins The statement is executed until the condition becomes false for ( initialization ; condition ; increment ) statement; The increment portion is executed at the end of each iteration

86 The for Statement A for statement has the following syntax: The initialization is executed once before the loop begins The statement is executed until the condition becomes false for (int count = 0; count < 5; count++) System.out.println (count); The increment portion is executed at the end of each iteration

87 The for Statement The increment section can perform any calculation: for (int num=100; num > 0; num -= 5) System.out.println (num); A for loop is well suited for executing statements a specific number of times that can be calculated or determined in advance

88 Example: Stars.java //******************************************************************** // Stars.java Author: Lewis/Loftus // // Demonstrates the use of nested for loops. //******************************************************************** public class Stars // // Prints a triangle shape using asterisk (star) characters. // } public static void main (String[] args) final int MAX_ROWS = 10; } for (int row = 1; row <= MAX_ROWS; row++) for (int star = 1; star <= row; star++) System.out.print ("*"); } System.out.println(); Output * ** *** **** ***** ****** ******* ******** ********* ********** Exercise: can you make it print the row number in (1, 2, 3 ) at the beginning of each line?

### Java I/O and Control Structures Algorithms in everyday life

Introduction Java I/O and Control Structures Algorithms in everyday life CSC 2014 Java Bootcamp Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Source: http://xkcd.com/627/

### Improved algorithm. Java code. Control flow and conditionals CSC 1051 Villanova University. Dr Papalaskari 1. Java Programè Algorithm

, conditionals, boolean expressions, block statements, nested statements CSC 1051 Algorithms and Data Structures I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course

### Conditional Statements

Conditional Statements 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/ Some

### Control flow, conditionals, boolean expressions, block statements, nested statements. Course website:

Control flow, conditionals, boolean expressions, block statements, nested statements CSC 1051 Algorithms and Data Structures I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

### Java code. Updated program. Control flow and conditionals CSC 1051 Villanova University. Dr Papalaskari 1. Java Programè Algorithm. Improved algorithm

Control flow, conditionals, boolean expressions, block statements, nested statements CSC 1051 Algorithms and Data Structures I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

### Selection and Repetition Revisited

Selection and Repetition Revisited CSC 1051 Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website: www.csc.villanova.edu/~map/1051/

### Selection and Repetition

Selection and Repetition Revisited CSC 1051 Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website: www.csc.villanova.edu/~map/1051/

### Selection and Repetition Revisited

Selection and Repetition Revisited CSC 1051 Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website: www.csc.villanova.edu/~map/1051/

### Selection and Repetition

Selection and Repetition Revisited CSC 1051 Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website: www.csc.villanova.edu/~map/1051/

### Algorithms and Java basics: pseudocode, variables, assignment, and interactive programs

Algorithms and Java basics: pseudocode, variables, assignment, and interactive programs CSC 1051 Algorithms and Data Structures I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova

### Algorithms and Conditionals

Algorithms and Conditionals CSC 1051 Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website: www.csc.villanova.edu/~map/1051/

### CSC 1051 Algorithms and Data Structures I. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

Algorithms 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/f13/ Some slides in

### Algorithms and Java basics: pseudocode, variables, assignment, and interactive programs

Algorithms and Java basics: pseudocode, variables, assignment, and interactive programs CSC 1051 Algorithms and Data Structures I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova

### Algorithms in everyday life. Algorithms. Algorithms and Java basics: pseudocode, variables, assignment, and interactive programs

Data and Algorithms Algorithms and Java basics: pseudocode, variables, assignment, and interactive programs Algorithms in everyday life CSC 1051 Algorithms and Data Structures I Dr. Mary-Angela Papalaskari

### Algorithms in everyday life. Algorithms. Algorithms and Java basics: pseudocode, variables, assignment, and interactive programs

Data and Algorithms Algorithms and Java basics: pseudocode, variables, assignment, and interactive programs Algorithms in everyday life CSC 1051 Algorithms and Data Structures I Dr. Mary-Angela Papalaskari

### Selection Statements and operators

Selection Statements and operators CSC 1051 Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website: www.csc.villanova.edu/~map/1051/

### CSC 1051 Algorithms and Data Structures I. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

Algorithms 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/ Some slides in this

### CSC 1051 Data Structures and Algorithms I

Repetition CSC 1051 Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website: www.csc.villanova.edu/~map/1051/ Some slides in this

### CSC 1051 Villanova University. CSC 1051 Data Structures and Algorithms I. Course website:

Repetition CSC 1051 Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website: www.csc.villanova.edu/~map/1051/ Some slides in this

### CSC 1051 Data Structures and Algorithms I

Repetition CSC 1051 Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website: www.csc.villanova.edu/~map/1051/ Some slides in this

### Selection Statements and operators

Selection Statements and operators CSC 1051 Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website: www.csc.villanova.edu/~map/1051/

### CSC 1051 Data Structures and Algorithms I

Repetition CSC 1051 Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website: www.csc.villanova.edu/~map/1051/ Some slides in this

### Chapter 3. Selections

Chapter 3 Selections 1 Outline 1. Flow of Control 2. Conditional Statements 3. The if Statement 4. The if-else Statement 5. The Conditional operator 6. The Switch Statement 7. Useful Hints 2 1. Flow of

### Conditionals and Loops

Conditionals and Loops Conditionals and Loops Now we will examine programming statements that allow us to: make decisions repeat processing steps in a loop Chapter 5 focuses on: boolean expressions conditional

### Program Development. Java Program Statements. Design. Requirements. Testing. Implementation

Program Development Java Program Statements Selim Aksoy Bilkent University Department of Computer Engineering saksoy@cs.bilkent.edu.tr The creation of software involves four basic activities: establishing

### Java Flow of Control

Java Flow of Control SEEM 3460 1 Flow of Control Unless specified otherwise, the order of statement execution through a method is linear: one statement after another in sequence Some programming statements

### COMP-202 Unit 4: Programming With Iterations. CONTENTS: The while and for statements

COMP-202 Unit 4: Programming With Iterations CONTENTS: The while and for statements Introduction (1) Suppose we want to write a program to be used in cash registers in stores to compute the amount of money

### 2: Basics of Java Programming

2: Basics of Java Programming 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/

### COMP 202. Programming With Iterations. CONTENT: The WHILE, DO and FOR Statements. COMP Loops 1

COMP 202 Programming With Iterations CONTENT: The WHILE, DO and FOR Statements COMP 202 - Loops 1 Repetition Statements Repetition statements or iteration allow us to execute a statement multiple times

### Conditional Programming

COMP-202 Conditional Programming Chapter Outline Control Flow of a Program The if statement The if - else statement Logical Operators The switch statement The conditional operator 2 Introduction So far,

### Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;

Control Statements Control Statements All programs could be written in terms of only one of three control structures: Sequence Structure Selection Structure Repetition Structure Sequence structure The

### Java Coding 3. Over & over again!

Java Coding 3 Over & over again! Repetition Java repetition statements while (condition) statement; do statement; while (condition); where for ( init; condition; update) statement; statement is any Java

### CMPT 125: Lecture 4 Conditionals and Loops

CMPT 125: Lecture 4 Conditionals and Loops Tamara Smyth, tamaras@cs.sfu.ca School of Computing Science, Simon Fraser University January 17, 2009 1 Flow of Control The order in which statements are executed

### Conditionals and Loops Chapter 4. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Conditionals and Loops Chapter 4 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013 2 Scope Flow of control Boolean expressions if and switch statements Comparing data while, do, and for

### Introduction to Arrays

Introduction to Arrays CSC 1051 Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website: www.csc.villanova.edu/~map/1051/ Some

### Top-Down Program Development

Top-Down Program Development Top-down development is a way of thinking when you try to solve a programming problem It involves starting with the entire problem, and breaking it down into more manageable

### Java Bootcamp - Villanova University. CSC 2014 Java Bootcamp. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

Arrays CSC 2014 Java Bootcamp Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Some slides in this presentation are adapted from the slides accompanying Java Software Solutions

### COMP 202 Java in one week

CONTENTS: Basics of Programming Variables and Assignment Data Types: int, float, (string) Example: Implementing a calculator COMP 202 Java in one week The Java Programming Language A programming language

### Using Classes and Objects Chapters 3 Creating Objects Section 3.1 The String Class Section 3.2 The Scanner Class Section 2.6

Using Classes and Objects Chapters 3 Creating Objects Section 3.1 The String Class Section 3.2 The Scanner Class Section 2.6 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013 2 Scope Creating

### BRANCHING if-else statements

BRANCHING if-else statements Conditional Statements A conditional statement lets us choose which statement t t will be executed next Therefore they are sometimes called selection statements Conditional

### Lab 8: IF statement. Conditionals and Loops. Copyright 2012 Pearson Education, Inc.

Lab 8: IF statement. Conditionals and Loops The if condition Statement A conditional statement lets us choose which statement will be executed next if is a Java reserved word The condition must be a boolean

### Review Chapters 1 to 4. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Review Chapters 1 to 4 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013 Introduction to Java Chapters 1 and 2 The Java Language Section 1.1 Data & Expressions Sections 2.1 2.5 Instructor:

### CSCI 2010 Principles of Computer Science. Basic Java Programming. 08/09/2013 CSCI Basic Java 1

CSCI 2010 Principles of Computer Science Basic Java Programming 1 Today s Topics Using Classes and Objects object creation and object references the String class and its methods the Java standard class

### Programming with Java

Programming with Java Data Types & Input Statement Lecture 04 First stage Software Engineering Dep. Saman M. Omer 2017-2018 Objectives q By the end of this lecture you should be able to : ü Know rules

### Program Development. Chapter 3: Program Statements. Program Statements. Requirements. Java Software Solutions for AP* Computer Science A 2nd Edition

Chapter 3: Program Statements Presentation slides for Java Software Solutions for AP* Computer Science A 2nd Edition Program Development The creation of software involves four basic activities: establishing

### Chapter 3: Program Statements

Chapter 3: Program Statements Presentation slides for Java Software Solutions for AP* Computer Science 3rd Edition by John Lewis, William Loftus, and Cara Cocking Java Software Solutions is published by

### Chapter 4: Conditionals and Loops

Chapter 4: Conditionals and Loops CS 121 Department of Computer Science College of Engineering Boise State University August 21, 2017 Chapter 4: Conditionals and Loops CS 121 1 / 69 Chapter 4 Topics Flow

### Control Structures: if and while A C S L E C T U R E 4

Control Structures: if and while A C S - 1903 L E C T U R E 4 Control structures 3 constructs are essential building blocks for programs Sequences compound statement Decisions if, switch, conditional operator

### CSC 1051 Data Structures and Algorithms I. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

Last Class CSC 1051 Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website: www.csc.villanova.edu/~map/1051/ Some slides in this

### CSC 1051 Algorithms and Data Structures I. Midterm Examination February 24, Name: KEY 1

CSC 1051 Algorithms and Data Structures I Midterm Examination February 24, 2014 Name: KEY 1 Question Value Score 1 10 2 10 3 10 4 10 5 10 6 10 7 10 8 10 9 10 10 10 TOTAL 100 Please answer questions in

### Chapter 4: Conditionals and Loops

Chapter 4: Conditionals and Loops CS 121 Department of Computer Science College of Engineering Boise State University March 2, 2016 Chapter 4: Conditionals and Loops CS 121 1 / 76 Chapter 4 Topics Flow

### CS 302: INTRODUCTION TO PROGRAMMING. Lectures 7&8

CS 302: INTRODUCTION TO PROGRAMMING Lectures 7&8 Hopefully the Programming Assignment #1 released by tomorrow REVIEW The switch statement is an alternative way of writing what? How do you end a case in

### Using Classes and Objects

Using Classes and Objects CSC 1051 Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website: www.csc.villanova.edu/~map/1051/ Today

### Introduction to Computer Science Unit 2. Notes

Introduction to Computer Science Unit 2. Notes Name: Objectives: By the completion of this packet, students should be able to describe the difference between.java and.class files and the JVM. create and

### Chapter. Let's explore some other fundamental programming concepts

Data and Expressions 2 Chapter 5 TH EDITION Lewis & Loftus java Software Solutions Foundations of Program Design 2007 Pearson Addison-Wesley. All rights reserved Data and Expressions Let's explore some

### School of Computer Science CPS109 Course Notes 5 Alexander Ferworn Updated Fall 15

Table of Contents 1 INTRODUCTION... 1 2 IF... 1 2.1 BOOLEAN EXPRESSIONS... 3 2.2 BLOCKS... 3 2.3 IF-ELSE... 4 2.4 NESTING... 5 3 SWITCH (SOMETIMES KNOWN AS CASE )... 6 3.1 A BIT ABOUT BREAK... 7 4 CONDITIONAL

### Lesson 7 Part 2 Flags

Lesson 7 Part 2 Flags A Flag is a boolean variable that signals when some condition exists in a program. When a flag is set to true, it means some condition exists When a flag is set to false, it means

### Topic 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

### Lecture 3: Variables and assignment

Lecture 3: Variables and assignment CSC 1051 Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website: www.csc.villanova.edu/~map/1051/

### H212 Introduction to Software Systems Honors

Introduction to Software Systems Honors Lecture #04: Fall 2015 1/20 Office hours Monday, Wednesday: 10:15 am to 12:00 noon Tuesday, Thursday: 2:00 to 3:45 pm Office: Lindley Hall, Room 401C 2/20 Printing

### Chapter 4: Control Structures I

Chapter 4: Control Structures I Java Programming: From Problem Analysis to Program Design, Second Edition Chapter Objectives Learn about control structures. Examine relational and logical operators. Explore

### Module 3 SELECTION STRUCTURES 2/15/19 CSE 1321 MODULE 3 1

Module 3 SELECTION STRUCTURES 2/15/19 CSE 1321 MODULE 3 1 Motivation In the programs we have written thus far, statements are executed one after the other, in the order in which they appear. Programs often

### Iterators and File Input

Iterators and File Input CSC 1051 Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website: www.csc.villanova.edu/~map/1051/ Some

### AP CS Unit 3: Control Structures Notes

AP CS Unit 3: Control Structures Notes The if and if-else Statements. These statements are called control statements because they control whether a particular block of code is executed or not. Some texts

### CSC 1051 Algorithms and Data Structures I. Midterm Examination October 7, Name:

CSC 1051 Algorithms and Data Structures I Midterm Examination October 7, 2013 Name: Question Value Score 1 10 2 10 3 10 4 10 5 10 6 10 7 10 8 10 9 10 10 10 TOTAL 100 Please answer questions in the spaces

### ECE 122 Engineering Problem Solving with Java

ECE 122 Engineering Problem Solving with Java Lecture 3 Expression Evaluation and Program Interaction Outline Problem: How do I input data and use it in complicated expressions Creating complicated expressions

### Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal Lesson Goals Understand Control Structures Understand how to control the flow of a program

### CS111: PROGRAMMING LANGUAGE II

CS111: PROGRAMMING LANGUAGE II Computer Science Department Lecture 1(c): Java Basics (II) Lecture Contents Java basics (part II) Conditions Loops Methods Conditions & Branching Conditional Statements A

### More Programming Constructs -- Introduction

More Programming Constructs -- Introduction We can now examine some additional programming concepts and constructs Chapter 5 focuses on: internal data representation conversions between one data type and

### Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal Lesson Goals Understand Control Structures Understand how to control the flow of a program

### Basics of Java Programming variables, assignment, and input

Basics of Java Programming variables, assignment, and input 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/

### CSC 1051 Algorithms and Data Structures I. Midterm Examination February 25, Name: KEY A

CSC 1051 Algorithms and Data Structures I Midterm Examination February 25, 2016 Name: KEY A Question Value Score 1 10 2 10 3 10 4 10 5 10 6 10 7 10 8 10 9 10 10 10 TOTAL 100 Please answer questions in

### CSC 1051 Algorithms and Data Structures I. Midterm Examination February 26, Name: Key

CSC 1051 Algorithms and Data Structures I Midterm Examination February 26, 2015 Name: Key Question Value 1 10 Score 2 10 3 10 4 10 5 10 6 10 7 10 8 10 9 10 10 10 TOTAL 100 Please answer questions in the

### Important Java terminology

1 Important Java terminology The information we manage in a Java program is either represented as primitive data or as objects. Primitive data פרימיטיביים) (נתונים include common, fundamental values as

### Data Conversion & Scanner Class

Data Conversion & Scanner Class Quick review of last lecture August 29, 2007 ComS 207: Programming I (in Java) Iowa State University, FALL 2007 Instructor: Alexander Stoytchev Numeric Primitive Data Storing

### COMP 202. Java in one week

COMP 202 CONTENTS: Basics of Programming Variables and Assignment Data Types: int, float, (string) Example: Implementing a calculator Java in one week The Java Programming Language A programming language

### Control Structures in Java if-else and switch

Control Structures in Java if-else and switch Lecture 4 CGS 3416 Spring 2017 January 23, 2017 Lecture 4CGS 3416 Spring 2017 Selection January 23, 2017 1 / 26 Control Flow Control flow refers to the specification

### Tester vs. Controller. Elementary Programming. Learning Outcomes. Compile Time vs. Run Time

Tester vs. Controller Elementary Programming EECS1022: Programming for Mobile Computing Winter 2018 CHEN-WEI WANG For effective illustrations, code examples will mostly be written in the form of a tester

### Last Class. While loops Infinite loops Loop counters Iterations

Last Class While loops Infinite loops Loop counters Iterations public class January31{ public static void main(string[] args) { while (true) { forloops(); if (checkclassunderstands() ) { break; } teacharrays();

### Elementary Programming

Elementary Programming EECS1022: Programming for Mobile Computing Winter 2018 CHEN-WEI WANG Learning Outcomes Learn ingredients of elementary programming: data types [numbers, characters, strings] literal

### true false Imperative Programming III, sections , 3.0, 3.9 Introductory Programming Control flow of programs While loops: generally Loops

Introductory Programming Imperative Programming III, sections 3.6-3.8, 3.0, 3.9 Anne Haxthausen a IMM, DTU 1. Loops (while, do, for) (sections 3.6 3.8) 2. Overview of Java s (learnt so far) 3. Program

### The for Loop, Accumulator Variables, Seninel Values, and The Random Class. CS0007: Introduction to Computer Programming

The for Loop, Accumulator Variables, Seninel Values, and The Random Class CS0007: Introduction to Computer Programming Review General Form of a switch statement: switch (SwitchExpression) { case CaseExpression1:

### Oct Decision Structures cont d

Oct. 29 - Decision Structures cont d Programming Style and the if Statement Even though an if statement usually spans more than one line, it is really one statement. For instance, the following if statements

### COMP-202: Foundations of Programming. Lecture 3: Boolean, Mathematical Expressions, and Flow Control Sandeep Manjanna, Summer 2015

COMP-202: Foundations of Programming Lecture 3: Boolean, Mathematical Expressions, and Flow Control Sandeep Manjanna, Summer 2015 Announcements Slides will be posted before the class. There might be few

### I/O Streams. program. Standard I/O. File I/O: Setting up streams from files. program. File I/O and Exceptions. Dr. Papalaskari 1

File I/O and Exceptions CSC 1051 Data Structures and Algorithms I I/O Streams Programs read information from input streams and write information to output streams Dr. Mary-Angela Papalaskari Department

### I/O Streams. program. Standard I/O. File I/O: Setting up streams from files. program. File I/O and Exceptions. Dr. Papalaskari 1

File I/O and Exceptions CSC 1051 Data Structures and Algorithms I I/O Streams Programs read information from input streams and write information to output streams Dr. Mary-Angela Papalaskari Department

### Computational Expression

Computational Expression Variables, Primitive Data Types, Expressions Janyl Jumadinova 28-30 January, 2019 Janyl Jumadinova Computational Expression 28-30 January, 2019 1 / 17 Variables Variable is a name

### Introduction to Java Applications

2 Introduction to Java Applications OBJECTIVES In this chapter you will learn: To write simple Java applications. To use input and output statements. Java s primitive types. Basic memory concepts. To use

### Expression statements are formed by adding a semicolon to the end of certain types of expressions.

Expression statements are formed by adding a semicolon to the end of certain types of expressions. Variable declaration statements declare variables. int width, height, area; String hello = "Hello, world!";

### Introduction to Java & Fundamental Data Types

Introduction to Java & Fundamental Data Types LECTURER: ATHENA TOUMBOURI How to Create a New Java Project in Eclipse Eclipse is one of the most popular development environments for Java, as it contains

### Loops. CSE 114, Computer Science 1 Stony Brook University

Loops CSE 114, Computer Science 1 Stony Brook University http://www.cs.stonybrook.edu/~cse114 1 Motivation Suppose that you need to print a string (e.g., "Welcome to Java!") a user-defined times N: N?

### Entry Point of Execution: the main Method. Elementary Programming. Learning Outcomes. Development Process

Entry Point of Execution: the main Method Elementary Programming EECS1021: Object Oriented Programming: from Sensors to Actuators Winter 2019 CHEN-WEI WANG For now, all your programming exercises will

### Flow of Control. Flow of control The order in which statements are executed. Transfer of control

1 Programming in C Flow of Control Flow of control The order in which statements are executed Transfer of control When the next statement executed is not the next one in sequence 2 Flow of Control Control

### CSC 1051 Algorithms and Data Structures I. Midterm Examination October 6, Name:

CSC 1051 Algorithms and Data Structures I Midterm Examination October 6, 2016 Name: Question Value Score 1 20 2 20 3 20 4 20 5 20 TOTAL 100 Please answer questions in the spaces provided. If you make a

### V2 2/4/ Ch Programming in C. Flow of Control. Flow of Control. Flow of control The order in which statements are executed

Programming in C 1 Flow of Control Flow of control The order in which statements are executed Transfer of control When the next statement executed is not the next one in sequence 2 Flow of Control Control

### Repe\$\$on CSC 121 Spring 2017 Howard Rosenthal

Repe\$\$on CSC 121 Spring 2017 Howard Rosenthal Lesson Goals Learn the following three repetition structures in Java, their syntax, their similarities and differences, and how to avoid common errors when

### Introduction to Computer Science Unit 2. Exercises

Introduction to Computer Science Unit 2. Exercises Note: Curly brackets { are optional if there is only one statement associated with the if (or ) statement. 1. If the user enters 82, what is 2. If the

### Lectures 3-1, 3-2. Control Structures. Control Structures, Shimon Schocken IDC Herzliya, slide 1

Introduction to Computer Science Shimon Schocken IDC Herzliya Lectures 3-1, 3-2 Control Structures Control Structures, Shimon Schocken IDC Herzliya, www.intro2cs.com slide 1 Shorthand operators (increment