# CMPT 125: Lecture 4 Conditionals and Loops

Size: px
Start display at page:

Transcription

1 CMPT 125: Lecture 4 Conditionals and Loops Tamara Smyth, School of Computing Science, Simon Fraser University January 17,

2 Flow of Control 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. CMPT 125: Conditionals and Loops, Lecture 4 2

3 Conditional Statements A conditional statement allow us to choose which statement will be executed next. Java has three conditional statements: 1. if-else 2. else 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. CMPT 125: Conditionals and Loops, Lecture 4 3

4 Boolean Expressions 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! ); else 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. ); else system.out.println( Count is less than or equal to 20. ); CMPT 125: Conditionals and Loops, Lecture 4 4

5 Evaluating Boolean Expressions 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 CMPT 125: Conditionals and Loops, Lecture 4 5

6 Logical NOT 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. ); else System.out.println( Let s go eat. ); OUTPUT: Let s go eat. CMPT 125: Conditionals and Loops, Lecture 4 6

7 Logical AND, OR 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 CMPT 125: Conditionals and Loops, Lecture 4 7

8 Precedence of Operators 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 8

9 Example code using if-else, else if public class testnum public static void main(string[] args) int num = Integer.parseInt(args[0]); } } if (num > 5) System.out.println(num + " > 5"); else if (num > 4) System.out.println(num + " > 4"); else if (num > 2) System.out.println(num + " > 2"); else System.out.println(num + " is 2 or less"); CMPT 125: Conditionals and Loops, Lecture 4 9

10 Short Circuiting Operations 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 10

11 Block 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! ); else 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. CMPT 125: Conditionals and Loops, Lecture 4 11

12 A Loop, or Repetitive 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 12

13 The while Statement 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."); else 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

14 The Conditional Operator 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 : 2nd expression Figure 1: The conditional operator. 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

15 Comparing Floats 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. if (Math.abs(f1-f2) < TOLERANCE) System.out.println( Effectively equal. ); CMPT 125: Conditionals and Loops, Lecture 4 15

16 Comparing Characters 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); else System.out.println(ch1 + is NOT greater than + ch2); CMPT 125: Conditionals and Loops, Lecture 4 16

17 Comparing Objects 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. ); else 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. ); else System.out.println( These variables contain + different addresses. ); OUTPUT: These variables contain different addresses. CMPT 125: Conditionals and Loops, Lecture 4 17

18 The switch Statement 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

19 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."); else 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

20 } CMPT 125: Conditionals and Loops, Lecture 4 20

21 Iterators 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. filescan.usedelimeter( ; ); CMPT 125: Conditionals and Loops, Lecture 4 21

22 The do statement 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. CMPT 125: Conditionals and Loops, Lecture 4 22

23 The for statement 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: for (int count = 10; count > 0; count--) System.out.println(count); CMPT 125: Conditionals and Loops, Lecture 4 23

24 Iterators and for loops 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. CMPT 125: Conditionals and Loops, Lecture 4 24

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

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

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

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

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

### CMPT 125: Lecture 3 Data and Expressions

CMPT 125: Lecture 3 Data and Expressions Tamara Smyth, tamaras@cs.sfu.ca School of Computing Science, Simon Fraser University January 3, 2009 1 Character Strings A character string is an object in Java,

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

### CONTENTS: Compilation Data and Expressions COMP 202. More on Chapter 2

CONTENTS: Compilation Data and Expressions COMP 202 More on Chapter 2 Programming Language Levels There are many programming language levels: machine language assembly language high-level language Java,

### Java I/O and Control Structures

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

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

### CS1004: Intro to CS in Java, Spring 2005

CS1004: Intro to CS in Java, Spring 2005 Lecture #16: Java conditionals/loops, cont d. Janak J Parekh janak@cs.columbia.edu Administrivia Midterms returned now Weird distribution Mean: 35.4 ± 8.4 What

### In this chapter, you will:

Java Programming: Guided Learning with Early Objects Chapter 4 Control Structures I: Selection In this chapter, you will: Make decisions with the if and if else structures Use compound statements in an

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

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

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

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

### Introduction to Computer Science, Shimon Schocken, IDC Herzliya. Lectures Control Structures

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 Control structures A program

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

### Comparing Data. Comparing Floating Point Values. Comparing Float Values. CS257 Computer Science I Kevin Sahr, PhD

1 CS257 Computer Science I Kevin Sahr, PhD Lecture 6: Comparing Data and Complex Boolean Expressions Comparing Data 2 When comparing data it's important to understand the nuances of certain data types

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

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

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

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

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

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

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

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

### Repetition, Looping. While Loop

Repetition, Looping Last time we looked at how to use if-then statements to control the flow of a program. In this section we will look at different ways to repeat blocks of statements. Such repetitions

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

### Topics. Chapter 5. Equality Operators

Topics Chapter 5 Flow of Control Part 1: Selection Forming Conditions if/ Statements Comparing Floating-Point Numbers Comparing Objects The equals Method String Comparison Methods The Conditional Operator

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

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

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

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

### Iteration: Intro. Two types of loops: 1. Pretest Condition precedes body Iterates 0+ times. 2. Posttest Condition follows body Iterates 1+ times

Iteration: Intro Two types of loops: 1. Pretest Condition precedes body Iterates 0+ times 2. Posttest Condition follows body Iterates 1+ times 1 Iteration: While Loops Pretest loop Most general loop construct

### JAVA OPERATORS GENERAL

JAVA OPERATORS GENERAL Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups: Arithmetic Operators Relational Operators Bitwise Operators

### Iteration statements - Loops

Iteration statements - Loops : ) הוראות חזרה / לולאות ( statements Java has three kinds of iteration WHILE FOR DO... WHILE loop loop loop Iteration (repetition) statements causes Java to execute one or

### Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:

JAVA OPERATORS GENERAL Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups: Arithmetic Operators Relational Operators Bitwise Operators

All copyrights reserved - KV NAD, Aluva Dinesh Kumar Ram PGT(CS) KV NAD Aluva Overview Looping Introduction While loops Syntax Examples Points to Observe Infinite Loops Examples using while loops do..

### ECE 122. Engineering Problem Solving with Java

ECE 122 Engineering Problem Solving with Java Lecture 10 For Loops and Arrays Outline Problem: How can I perform the same operations a fixed number of times? Considering for loops Performs same operations

### AYBUKE BUYUKCAYLI KORAY OZUYAR MUSTAFA SOYLU. Week 21/02/ /02/2007 Lecture Notes: ASCII

AYBUKE BUYUKCAYLI KORAY OZUYAR MUSTAFA SOYLU Week 21/02/2007-23/02/2007 Lecture Notes: ASCII 7 bits = 128 characters 8 bits = 256characters Unicode = 16 bits Char Boolean boolean frag; flag = true; flag

### Programming: Java. Chapter Objectives. Control Structures. Chapter 4: Control Structures I. Program Design Including Data Structures

Chapter 4: Control Structures I Java Programming: Program Design Including Data Structures Chapter Objectives Learn about control structures Examine relational and logical operators Explore how to form

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

### CT 229 Java Syntax Continued

CT 229 Java Syntax Continued 29/09/2006 CT229 Lab Assignments One Week Extension for Lab Assignment 1. Due Date: Oct 8 th Before submission make sure that the name of each.java file matches the name given

### Repetition. Chapter 6

Chapter 6 Repetition Goals This chapter introduces the third major control structure repetition (sequential and selection being the first two). Repetition is discussed within the context of two general

### Repetition. Chapter 6

Chapter 6 Repetition Goals This chapter introduces the third major control structure repetition (sequential and selection being the first two). Repetition is discussed within the context of two general

### CS111: PROGRAMMING LANGUAGE II

1 CS111: PROGRAMMING LANGUAGE II Computer Science Department Lecture 1: Introduction Lecture Contents 2 Course info Why programming?? Why Java?? Write once, run anywhere!! Java basics Input/output Variables

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

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

### Java Review. Java Program Structure // comments about the class public class MyProgram { Variables

Java Program Structure // comments about the class public class MyProgram { Java Review class header class body Comments can be placed almost anywhere This class is written in a file named: MyProgram.java

### COMP-202. Recursion. COMP Recursion, 2011 Jörg Kienzle and others

COMP-202 Recursion Recursion Recursive Definitions Run-time Stacks Recursive Programming Recursion vs. Iteration Indirect Recursion Lecture Outline 2 Recursive Definitions (1) A recursive definition is

### Objectives. Chapter 4: Control Structures I (Selection) Objectives (cont d.) Control Structures. Control Structures (cont d.) Relational Operators

Objectives Chapter 4: Control Structures I (Selection) In this chapter, you will: Learn about control structures Examine relational and logical operators Explore how to form and evaluate logical (Boolean)

### ECE 122. Engineering Problem Solving with Java

ECE 122 Engineering Problem Solving with Java Lecture 8 More Conditional Statements Outline Problem: How do I make choices in my Java program? Understanding conditional statements Remember: Boolean logic

### ECE 122. Engineering Problem Solving with Java

ECE 122 Engineering Problem Solving with Java Lecture 8 More Conditional Statements Outline Problem: How do I make choices in my Java program? Understanding conditional statements Remember: Boolean logic

### COMP Primitive and Class Types. Yi Hong May 14, 2015

COMP 110-001 Primitive and Class Types Yi Hong May 14, 2015 Review What are the two major parts of an object? What is the relationship between class and object? Design a simple class for Student How to

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

### Problem Solving With Loops

To appreciate the value of loops, take a look at the following example. This program will calculate the average of 10 numbers input by the user. Without a loop, the three lines of code that prompt the

### Announcements. Lab Friday, 1-2:30 and 3-4:30 in Boot your laptop and start Forte, if you brought your laptop

Announcements Lab Friday, 1-2:30 and 3-4:30 in 26-152 Boot your laptop and start Forte, if you brought your laptop Create an empty file called Lecture4 and create an empty main() method in a class: 1.00

### Constants. Why Use Constants? main Method Arguments. CS256 Computer Science I Kevin Sahr, PhD. Lecture 25: Miscellaneous

CS256 Computer Science I Kevin Sahr, PhD Lecture 25: Miscellaneous 1 main Method Arguments recall the method header of the main method note the argument list public static void main (String [] args) we

### STUDENT LESSON A12 Iterations

STUDENT LESSON A12 Iterations Java Curriculum for AP Computer Science, Student Lesson A12 1 STUDENT LESSON A12 Iterations INTRODUCTION: Solving problems on a computer very often requires a repetition of

### Chapter 4: Control Structures I (Selection) Objectives. Objectives (cont d.) Control Structures. Control Structures (cont d.

Chapter 4: Control Structures I (Selection) In this chapter, you will: Objectives Learn about control structures Examine relational and logical operators Explore how to form and evaluate logical (Boolean)

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

### Chapter 5 Control Statements: Part 2 Section 5.2 Essentials of Counter-Controlled Repetition

Chapter 5 Control Statements: Part 2 Section 5.2 Essentials of Counter-Controlled Repetition 5.2 Q1: Counter-controlled repetition requires a. A control variable and initial value. b. A control variable

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

### Introduction to OOP with Java. Instructor: AbuKhleif, Mohammad Noor Sep 2017

Introduction to OOP with Java Instructor: AbuKhleif, Mohammad Noor Sep 2017 Lecture 03: Control Flow Statements: Selection Instructor: AbuKhleif, Mohammad Noor Sep 2017 Instructor AbuKhleif, Mohammad Noor

### Prof. Navrati Saxena TA: Rochak Sachan

JAVA Prof. Navrati Saxena TA: Rochak Sachan Operators Operator Arithmetic Relational Logical Bitwise 1. Arithmetic Operators are used in mathematical expressions. S.N. 0 Operator Result 1. + Addition 6.

### Computer Programming, I. Laboratory Manual. Experiment #6. Loops

Think Twice Code Once The Islamic University of Gaza Engineering Faculty Department of Computer Engineering Fall 2017 ECOM 2005 Khaleel I. Shaheen Computer Programming, I Laboratory Manual Experiment #6

CS313D: ADVANCED PROGRAMMING LANGUAGE Computer Science department Lecture 2 : C# Language Basics Lecture Contents 2 The C# language First program Variables and constants Input/output Expressions and casting

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

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

### Basic computer skills such as using Windows, Internet Explorer, and Microsoft Word. Chapter 1 Introduction to Computers, Programs, and Java

Basic computer skills such as using Windows, Internet Explorer, and Microsoft Word Chapter 1 Introduction to Computers, Programs, and Java Chapter 2 Primitive Data Types and Operations Chapter 3 Selection

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

### Example: Monte Carlo Simulation 1

Example: Monte Carlo Simulation 1 Write a program which conducts a Monte Carlo simulation to estimate π. 1 See https://en.wikipedia.org/wiki/monte_carlo_method. Zheng-Liang Lu Java Programming 133 / 149

### CONDITIONAL EXECUTION

CONDITIONAL EXECUTION yes x > y? no max = x; max = y; logical AND logical OR logical NOT &&! Fundamentals of Computer Science I Outline Conditional Execution if then if then Nested if then statements Comparisons

### COMP 202. Built in Libraries and objects. CONTENTS: Introduction to objects Introduction to some basic Java libraries string

COMP 202 Built in Libraries and objects CONTENTS: Introduction to objects Introduction to some basic Java libraries string COMP 202 Objects and Built in Libraries 1 Classes and Objects An object is an

### Controls Structure for Repetition

Controls Structure for Repetition So far we have looked at the if statement, a control structure that allows us to execute different pieces of code based on certain conditions. However, the true power

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

### Programming Constructs Overview. Method Call System.out.print( hello ); Method Parameters

Programming Constructs Overview Method calls More selection statements More assignment operators Conditional operator Unary increment and decrement operators Iteration statements Defining methods 27 October

### Chapter 3 Selections. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.

Chapter 3 Selections Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 1 Motivations If you assigned a negative value for radius

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

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

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

### Chapter 3 Selection Statements

Chapter 3 Selection Statements 3.1 Introduction Java provides selection statements that let you choose actions with two or more alternative courses. Selection statements use conditions. Conditions are

### Full file at

Java Programming: From Problem Analysis to Program Design, 3 rd Edition 2-1 Chapter 2 Basic Elements of Java At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class

### Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition

Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition Learn about repetition (looping) control structures Explore how to construct and use: o Counter-controlled

### Full file at

Chapter 3 Flow of Control Multiple Choice 1) An if selection statement executes if and only if: (a) the Boolean condition evaluates to false. (b) the Boolean condition evaluates to true. (c) the Boolean

### Chapter 7 User-Defined Methods. Chapter Objectives

Chapter 7 User-Defined Methods Chapter Objectives Understand how methods are used in Java programming Learn about standard (predefined) methods and discover how to use them in a program Learn about user-defined

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

CPS109 Course Notes 6 Alexander Ferworn Unrelated Facts Worth Remembering Use metaphors to understand issues and explain them to others. Look up what metaphor means. Table of Contents Contents 1 ITERATION...

### 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 Basic Programming Constructs

Java Basic Programming Constructs /* * This is your first java program. */ class HelloWorld{ public static void main(string[] args){ System.out.println( Hello World! ); A Closer Look at HelloWorld 2 This

### Introduction to the Java Basics: Control Flow Statements

Lesson 3: Introduction to the Java Basics: Control Flow Statements Repetition Structures THEORY Variable Assignment You can only assign a value to a variable that is consistent with the variable s declared

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

### L o o p s. for(initializing expression; control expression; step expression) { one or more statements }

L o o p s Objective #1: Explain the importance of loops in programs. In order to write a non trivial computer program, you almost always need to use one or more loops. Loops allow your program to repeat

### Boolean Expressions. So, for example, here are the results of several simple Boolean expressions:

Boolean Expressions Now we have the ability to read in some information, calculate some formulas and display the information to the user in a nice format. However, the real power of computer programs lies

### 3chapter C ONTROL S TATEMENTS. Objectives

3chapter C ONTROL S TATEMENTS Objectives To understand the flow of control in selection and loop statements ( 3.2 3.7). To use Boolean expressions to control selection statements and loop statements (

### Lecture Programming in C++ PART 1. By Assistant Professor Dr. Ali Kattan

Lecture 08-1 Programming in C++ PART 1 By Assistant Professor Dr. Ali Kattan 1 The Conditional Operator The conditional operator is similar to the if..else statement but has a shorter format. This is useful