Loops (cont.). Loop Statements  while statement  do statement  for statement while ( condition ) statement; do { statement list; } while ( condition.

Slides:



Advertisements
Similar presentations
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
Advertisements

Methods. int month; int year class Month Defining Classes A class contains data declarations (static and instance variables) and method declarations (behaviors)
CSE 1301 Lecture 6B More Repetition Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie July 5, 2005.
Loops – While Loop Repetition Statements While Reading for this Lecture, L&L, 5.5.
COMP 14 Introduction to Programming Miguel A. Otaduy May 25, 2004.
CS 106 Introduction to Computer Science I 02 / 12 / 2007 Instructor: Michael Eckmann.
Loops – While, Do, For Repetition Statements Introduction to Arrays
Aalborg Media Lab 23-Jun-15 Software Design Lecture 6 “Conditionals and Loops”
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie July 8, 2005.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Primitive Data Types There are exactly eight primitive data types in Java four of them represent integers: byte (class Byte), short (class Short), int.
COMP 14 Introduction to Programming Miguel A. Otaduy May 20, 2004.
Java Program Statements Selim Aksoy Bilkent University Department of Computer Engineering
Loops Repetition Statements. Repetition statements allow us to execute a statement multiple times Often they are referred to as loops Like conditional.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
ECE122 L9: While loops March 1, 2007 ECE 122 Engineering Problem Solving with Java Lecture 9 While Loops.
Java Programming: From the Ground Up
ASP.NET Programming with C# and SQL Server First Edition Chapter 3 Using Functions, Methods, and Control Structures.
Classes and Methods Computer Engineering Department Java Course Asst. Prof. Dr. Ahmet Sayar Kocaeli University - Fall 2014.
Loops: Handling Infinite Processes CS 21a: Introduction to Computing I First Semester,
© 2006 Pearson Education Chapter 3 Part 2 More about Strings and Conditional Statements Loops (for and while) 1.
Repetitive Structures BBS514 Structured Programming (Yapısal Programlama)1.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Chapter 5 Loops.
1 Additional Control Structures. 2 Chapter 9 Topics  Switch Statement for Multi-way Branching  Do-While Statement for Looping  For Statement for Looping.
Copyright © 2012 Pearson Education, Inc. Chapter 6 More Conditionals and Loops Java Software Solutions Foundations of Program Design Seventh Edition John.
Flow Control in Java. Controlling which instruction to execute next Sequential  Similar to walking, one step after another Branching  Similar to a fork.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
Chapter 5 Conditionals and Loops. © 2004 Pearson Addison-Wesley. All rights reserved5-2 The switch Statement The switch statement provides another way.
Topics Logical Operators (Chapter 5) Comparing Data (Chapter 5) The conditional operator The switch Statement The for loop Nested Loops.
Java iteration statements ● Iteration statements are statements which appear in the source code only once, but it execute many times. ● Such kind of statements.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
User Defined Methods Methods are used to divide complicated programs into manageable pieces. There are predefined methods (methods that are already provided.
Think Possibility 1 Iterative Constructs ITERATION / LOOPS C provides three loop structures: the for-loop, the while-loop, and the do-while-loop. Each.
Loops Copyright © 2012 Pearson Education, Inc.. Conditionals and Loops (Chapter 5) So far, we’ve looked at: –making decisions with if –how to compare.
Repetition Statements (Loops). 2 Introduction to Loops We all know that much of the work a computer does is repeated many times. When a program repeats.
LECTURE # 8 : REPETITION STATEMENTS By Mr. Ali Edan.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
1 Flow of Control Chapter 5. 2 Objectives You will be able to: Use the Java "if" statement to control flow of control within your program.  Use the Java.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Decisions and Iterations.
Feedback  Lab2, Hw1  Groups  Group Project Requirements.
Repetition Statements b Repetition statements allow us to execute a statement multiple times repetitively b They are often simply referred to as loops.
Programming in Java (COP 2250) Lecture 12 & 13 Chengyong Yang Fall, 2005.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
Chapter 7 User-Defined Methods.
Chapter 4 Repetition Statements (loops)
CHAPTER 4 REPETITION CONTROL STRUCTURE / LOOPING
Chapter 6 More Conditionals and Loops
Loop Structures.
Lecture 07 More Repetition Richard Gesick.
Methods.
The switch Statement The switch statement provides another way to decide which statement to execute next The switch statement evaluates an expression,
While loops The while loop executes the statement over and over as long as the boolean expression is true. The expression is evaluated first, so the statement.
MSIS 655 Advanced Business Applications Programming
Chapter 6 More Conditionals and Loops
CSS161: Fundamentals of Computing
Outline Altering flow of control Boolean expressions
CS1100 Computational Engineering
Additional Control Structures
3.5- The while Statement The while statement has the following syntax:
Module 4 Loops and Repetition 2/1/2019 CSE 1321 Module 4.
BBIT 212/ CISY 111 Object Oriented Programming (OOP)
Repetition Statements
Outline Boolean Expressions The if Statement Comparing Data
Chap 7. Advanced Control Statements in Java
Module 4 Loops and Repetition 9/19/2019 CSE 1321 Module 4.
Presentation transcript:

Loops (cont.)

Loop Statements  while statement  do statement  for statement while ( condition ) statement; do { statement list; } while ( condition ); for ( initialization ; condition ; increment ) statement;

Flowchart of a while Loop statement true condition evaluated false while ( condition ) statement;

Example // set initial value of month so that the while condition // below is false initially int month = -1; while (month 12) { System.out.print( “Enter a month (1 to 12): “); month = scan.nextInt(); } System.out.print( “Enter a month (1 to 12): “); int month = scan.nextInt(); while (month 12) { System.out.println( month + “ is not a valid month.” ); System.out.print( “Enter a month (1 to 12): “); month = scan.nextInt(); }

The do Statement: Syntax do { statement; } while ( condition );Both do and do andwhilearereservedwords The statement is executed once initially, then the condition is evaluated The statement is repetitively executed until the condition becomes false

Flowchart of a do Loop true condition evaluated statement false do { statement; } while ( condition );

Comparing the while and do Loops statement true condition evaluated false while loop true condition evaluated statement false do loop  A do loop is similar to a while loop, except that the condition is evaluated after the body of the loop is executed  Therefore the body of a do loop will execute at least once

Example int month; // no need to initialize month do { System.out.print( “Enter a month (1 to 12): “); month = scan.nextInt(); } while (month 12); // beginning of the next statement

The for Statement: Syntax for ( initialization ; condition ; increment ) statement;Reservedword The initialization portion is executed once before the loop begins The statement is executed until the condition becomes false The increment portion is executed at the end of each iteration Both semi-colons are always required

The for Statement: Syntax Each expression in the header of a for loop is optional –if the initialization is left out, no initialization is performed –if the condition is left out, it is always considered to be true –if the increment is left out, no increment operation is performed

Flowchart of a for loop statement true condition evaluated false increment initialization for ( initialization ; condition ; increment ) statement;

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

The for Statement: Example counter++ Establish initial value of control variable. Determine if final value of control variable has been reached. counter <= max sum+= counter true false int counter = 1 Body of loop (this may be multiple statements) Increment the control variable. int sum = 0; for (int counter = 1; counter <= max; counter++) sum += counter; // beginning of the next statement

Summary: Loop Statements Syntax  while statement  do statement  for statement while ( condition ) statement; do { statement list; } while ( condition ); for ( initialization ; condition ; increment ) statement;

15 Comments about Loop Statements Choosing which loop statement to use will depend on the specific situation and personal taste Checking and updating the condition –in most cases, the body of a loop must eventually make the condition false if not, it is an infinite loop, which will execute until the user interrupts the program –Ctrl-C in command line this is a common type of logical error, and you should always double check to ensure that your loops will terminate normally –pay attention to the condition to avoid an “off by 1” problem

Designing a Loop: A (Rough) Template Think of state (captured by variables) that you need to keep track across multiple iterations –e.g., counter, sum –e.g., boolean variables: thisRoundIsOver, canBeDivided … Initialize state (variables) Inside the loop –process the processing may depend on the current state –update state e.g., increase the counter, add to sum, set the flag Termination condition: in general, it is a boolean expression involving the state variables

Example: Check if a Number is Prime // check if a positive integer n is prime boolean canBeDivided = false; for (int i = 2; i < n && !canBeDivided; i++) { if (n % i == 0) canBeDivided = true; } if (!canBeDivided) { System.out.println (n + “ is not a prime!”); } else { System.out.println (n + “ is a prime!”); }

Example: Reverse a Number number reverse The state is captured by number and reverse number reverse 21

Example: Reverse a Number number reverse { lastDigit = number % 10; reverse = reverse * 10 + lastDigit; } 55 number % 10reverse = reverse * 10 + number % 10 number = number / 10; reverse = 0; while (number > 0) int reverse, lastDigit; int intReverse (int number) { }

Example: Reverse a Number number reverse reverse = 0; while (number > 0) { lastDigit = number % 10; reverse = reverse * 10 + lastDigit; number = number / 10; } 5

Example: Play Games // initialize global state variables // such as statistics boolean userQuits = false; do { // initialize state variables for one game // such as number of guesses allowed boolean thisRoundIsOver = false; do { // get user input // process input, update states // determine if thisRoundIsOver // userQuits implies thisRoundIsOver } while ( !thisRoundIsOver ); // update statistics of preceding game } while ( !userQuits ); // report total statistics

Using Break : Loop-and-a-Half Idiom Initialize total to zero Initialize counter to zero While (true) { Input next grade (possibly the sentinel) If ( the user has entered the sentinel) break; Add this grade into the running total Add one to the grade counter } If the counter is not equal to zero Set the average to the total divided by the counter Print the average Else Print “No grades were entered” Initialize total to zero Initialize counter to zero Input the first grade (possibly the sentinel) While (grade != sentinel) { Add this grade into the running total Add one to the grade counter Input next grad (possibly the sentinel) } If the counter is not equal to zero Set the average to the total divided by the counter Print the average Else Print “No grades were entered”

23 Exercise : AverageGrade Write a program to compute the average of a sequence of (numerical) student grades entered by the user –If the user types something else than a number between 0.0 and 4.0, the program should abort.

Exercise : Reverse a Number Write a program that outputs a reverse of the positive integers the user types. –If the user types something else, the program should abort.

25 Exercise : PalindromeTester Write a program to read in a sequence of strings; for each string, determine whether it is a palindrome

Exercise : Stars Write a program to print a triangle formed by * * ** *** The program should read in the number of rows from the user; the row should be between 1 to 10

Methods

A useful program can be long and contains many statements A method groups a sequence of statements and should provide a well-defined, easy-to-understand functionality –a method takes input, performs actions, and produces output Recall: In Java, each method is defined within specific class

Method Declaration: Header A method declaration begins with a method header methodname returntype parameter list The parameter list specifies the type and name of each parameter The name of a parameter in the method declaration is called a formal argument class MyClass { static int min ( int num1, int num2 ) … properties

Method Declaration: Body The header is followed by the method body: static int min(int num1, int num2) { int minValue = num1 < num2 ? num1 : num2; return minValue; } class MyClass { … … }

31 The return Statement The return type of a method indicates the type of value that the method sends back to the calling location –A method that does not return a value has a void return type The return statement specifies the value that will be returned –Its expression must conform to the return type

Calling a Method Each time a method is called, the values of the actual arguments in the invocation are assigned to the formal arguments static int min (int num1, int num2) { int minValue = (num1 < num2 ? num1 : num2); return minValue; } int num = min (2, 3);

33 Method Overloading A class may define multiple methods with the same name---this is called method overloading –usually perform the same task on different data types Example: The PrintStream class defines multiple println methods, i.e., println is overloaded: println (String s) println (int i) println (double d) … The following lines use the System.out.print method for different data types: System.out.println ("The total is:"); double total = 0; System.out.println (total);

34 Method Overloading: Signature The compiler must be able to determine which version of the method is being invoked This is by analyzing the parameters, which form the signature of a method –the signature includes the type and order of the parameters if multiple methods match a method call, the compiler picks the best match if none matches exactly but some implicit conversion can be done to match a method, then the method is invoke with implicit conversion. –the return type of the method is not part of the signature

Method Overloading double tryMe (int x) { return x +.375; } Version 1 double tryMe (int x, double y) { return x * y; } Version 2 result = tryMe (25, 4.32)Invocation

More Examples double tryMe ( int x ) { return x + 5; } double tryMe ( double x ) { return x *.375; } double tryMe (double x, int y) { return x + y; } tryMe( 1 ); tryMe( 1.0 ); tryMe( 1.0, 2); tryMe( 1, 2); tryMe( 1.0, 2.0); Which tryMe will be called?

Variable Scoping

Three variable types There are can be three types of variables in a method –local variables those declared in the method –formal arguments –class variables those defined in the class but not in the method

Example of Variable Types public class Box { private int length, width; … public int widen (int extra_width) { private int temp1; size += extra_width; … } public int lenghten (int extra_lenth) { private int temp2; size += extra_length; … } … } class variables formal arguments local variables

Scope of Variables Class variables are valid in all methods of the class A formal argument is valid within its method Local variables are valid from the point of declaration to the end of the enclosing block public class Box { private int length, width; … public int widen (int extra_width) { private int temp1; size += extra_width; … } public int lenghten (int extra_lenth) { private int temp2; size += extra_length; … } … }

Two Types of Parameter Passing If a modification of the formal argument has no effect on the actual argument, –it is call by value If a modification of the formal argument can change the value of the actual argument, –it is call by reference

Call-By-Value and Call-By-Reference in Java Depend on the type of the formal argument If a formal argument is a primitive data type, a modification on the formal argument has no effect on the actual argument –this is call by value, e.g. num1 = min(2, 3); num2 = min(x, y); If a formal argument is not a primitive data type, an operation on the formal argument can change the actual argument –this is call by reference –more discussion in the later part of the course…