OBJECT ORIENTED PROGRAMMING I LECTURE 11 GEORGE KOUTSOGIANNAKIS

Slides:



Advertisements
Similar presentations
CSE 1301 Lecture 6B More Repetition Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison.
Advertisements

Flow of Control Part 2: Looping
CS 106 Introduction to Computer Science I 02 / 18 / 2008 Instructor: Michael Eckmann.
Computer Science 1620 Loops.
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.
Additional control structures. The if-else statement The if-else statement chooses which of two statements to execute The if-else statement has the form:
Chapter 4 - Control Structures: Part 1 Outline 4.4Control Structures 4.5The if Selection Structure 4.6The if/else Selection Structure 4.7The while Repetition.
Chapter 6 - Repetition. Introduction u Many applications require certain operations to be carried out more than once. Such situations require repetition.
Switch structure Switch structure selects one from several alternatives depending on the value of the controlling expression. The controlling expression.
Loop variations do-while and for loops. Do-while loops Slight variation of while loops Instead of testing condition, then performing loop body, the loop.
Loops – While, Do, For Repetition Statements Introduction to Arrays
CS 106 Introduction to Computer Science I 10 / 04 / 2006 Instructor: Michael Eckmann.
ECE122 L11: For loops and Arrays March 8, 2007 ECE 122 Engineering Problem Solving with Java Lecture 11 For Loops and Arrays.
COMP 14 Introduction to Programming Miguel A. Otaduy May 20, 2004.
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.
COMP 110 Introduction to Programming Mr. Joshua Stough September 24, 2007.
CONTROL STATEMENTS Lakhbir Singh(Lect.IT) S.R.S.G.P.C.G. Ludhiana.
Chapter 4: Control Structures II
11 Chapter 4 LOOPS AND FILES. 22 THE INCREMENT AND DECREMENT OPERATORS To increment a variable means to increase its value by one. To decrement a variable.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 3 GEORGE KOUTSOGIANNAKIS Copyright: Illinois Institute of Technology/George Koutsogiannakis 1.
Java Programming: From the Ground Up
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 9 Multidimensional Arrays and the ArrayList Class.
Arrays BCIS 3680 Enterprise Programming. Overview 2  Array terminology  Creating arrays  Declaring and instantiating an array  Assigning value to.
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
Chapter 5 Loops.
Chapter 4 Loops Write code that prints out the numbers Very often, we want to repeat a (group of) statement(s). In C++, we have 3 major ways of.
Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
Chapter 4: Control Structures II
Chapter 5: Control Structures II
CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 9 GEORGE KOUTSOGIANNAKIS Copyright: 2014 Illinois Institute of Technology- George Koutsogiannakis 1.
Java iteration statements ● Iteration statements are statements which appear in the source code only once, but it execute many times. ● Such kind of statements.
CONTROL STATEMENTS LOOPS. WHY IS REPETITION NEEDED?  There are many situations in which the same statements need to be executed several times.  Example:
Iteration & Loop Statements 1 Iteration or Loop Statements Dept. of Computer Engineering Faculty of Engineering, Kasetsart University Bangkok, Thailand.
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.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 5 GEORGE KOUTSOGIANNAKIS Copyright: 2016 Illinois Institute of Technology/George Koutsogiannakis 1.
COMP Loop Statements Yi Hong May 21, 2015.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
CS 116: Object Oriented Programming II. Topics Vectors Multidimensional Arrays ArrayList.
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.
CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 11 GEORGE KOUTSOGIANNAKIS 1 Copyright: 2015 Illinois Institute of Technology_ George Koutsogiannakis.
Introduction to Programming G50PRO University of Nottingham Unit 6 : Control Flow Statements 2 Paul Tennent
Chapter 7 Control Structures. Java has very flexible three looping mechanisms. You can use one of the following three loops:  while Loop  do...while.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
CS 106 Introduction to Computer Science I 02 / 15 / 2008 Instructor: Michael Eckmann.
Lecture 4b Repeating With Loops
REPETITION CONTROL STRUCTURE
OBJECT ORIENTED PROGRAMMING I LECTURE 12 GEORGE KOUTSOGIANNAKIS
OBJECT ORIENTED PROGRAMMING II LECTURE 15 GEORGE KOUTSOGIANNAKIS
Yanal Alahmad Java Workshop Yanal Alahmad
CS116 OBJECT ORIENTED PROGRAMMING II LECTURE 1 Part II
Chapter 6 More Conditionals and Loops
Chapter 5: Control Structures II
Loop Structures.
Lecture 4 - Loops UniMAP EKT120 Sem 1 08/09.
Programming Fundamentals
Lecture 07 More Repetition Richard Gesick.
Chapter 5: Control Structures II
Lecture 4B More Repetition Richard Gesick
Loops The loop blocks you've used in Scratch can all be recreated in C! Loops allow for the repetition of code until a condition is met. There are three.
Arrays, For loop While loop Do while loop
Outline Altering flow of control Boolean expressions
OBJECT ORIENTED PROGRAMMING I LECTURE 9 GEORGE KOUTSOGIANNAKIS
OBJECT ORIENTED PROGRAMMING II LECTURE 13_2 GEORGE KOUTSOGIANNAKIS
Arrays October 6, 2006 ComS 207: Programming I (in Java)
LOOPS The loop is the control structure we use to specify that a statement or group of statements is to be repeatedly executed. Java provides three kinds.
Presentation transcript:

OBJECT ORIENTED PROGRAMMING I LECTURE 11 GEORGE KOUTSOGIANNAKIS CS 201 OBJECT ORIENTED PROGRAMMING I LECTURE 11 GEORGE KOUTSOGIANNAKIS Copyright: 2016 Illinois Institute of Technology_ George Koutsogiannakis

Last Week’s Topics Event-Controlled Loops Using while Type-Safe Input Using Scanner Constructing Loop Conditions Reading a Text File Looping Techniques

New Topics Event-Controlled Loops Using do/while Count-Controlled Loops Using for Nested Loops Concept of Arrays. Declaring and Instantiating Arrays Accessing Array Elements

The do/while Loop Unlike the while loop, the condition for the do/while loop is evaluated at the end of the loop Thus, do/while loop executes at least once Some uses for a do/while loop: Validate user input Ask if the user wants to repeat an operation, such as play a game again.

do/while Flow of Control The do/while loop body is executed, then the condition is checked. If the condition is true, the loop body is repeated. If the condition is false, the loop body is not repeated.

do/while Syntax //initialize variables do { // body of loop   } while ( condition ); //process the results

Example:Validate User Input We can use a do/while loop to check whether the user input is valid. We prompt the user inside the do/while loop. If the user input is not valid, we want to reprompt until the user enters a valid value. Thus, we form the condition so that it is true if user enters invalid data.

To Repeat an Operation Example code using a do/while loop to prompt the user to play a game again: do { // code to play a game System.out.print( "Play again (yes/no)? ") String answer = scan.next( ); } while ( answer.equalsIgnoreCase( "yes" ) );

do/while loop Example public class TestDoWhile { public static void main(String[] args) int count=11; int sum=0; do count++; sum=sum+count; } while(count<=10); System.out.println(sum);

do/while loop Example The output is 12 We enter the do and advance count to 12 from 11 We add 12 to 0 and sum=12 We reach the while condition and it evaluates to false. We are out of the while loop

Same code with while Loop public class TestDoWhile1 { public static void main(String[] args) int count=11; int sum=0; while(count<=10) count++; sum=sum+count; } System.out.println(sum);

Same code with while Loop Output is zero. We reach the while condition and it evaluates to false. Thus we are not allowed to execute inside the while loop. We exit the while loop.

The for Loop Ideal when before the loop begins, you know the number of iterations to perform. Examples: Find the sum of 5 numbers Find the maximum of 20 numbers Print the odd numbers from 1 to 10

for Loop Flow of Control The initialization statement is executed (once only). The loop condition is evaluated. If the condition is true, the loop body is executed. The loop update statement is then executed, and the loop condition is reevaluated.

The for Loop Syntax for ( initialization; loop condition; loop update ) { // loop body } Notes: semicolons separate terms in the loop header no semicolon follows the loop header curly braces are required only if more than one statement is in the loop body

Using a Loop Control Variable A loop control variable is convenient for counting for loops. We set its initial value in the initialization statement We check its value in the loop condition We increment or decrement its value in the loop update statement

Testing for Loops An important test for for loops is that the starting and ending values of the loop variable are set correctly. For example, to iterate 5 times, use this header: for ( int i = 0; i < 5; i++ ) or this header: for ( int i = 1; i <= 5; i++ )

Example For Loop public class ForLoop { public static void main(String[] args) { int count=0; int sum=0; for(count=0; count<=5; count++) sum=sum+count; } System.out.println(sum); Output=15 0+1+2+3+4+5=15 notice that there are 6 iterations in the loop

Processing a String (named word) In the reverse direction: Correct: for ( int i = word.length( ) - 1; i >= 0; i-- ) Incorrect: for ( int i = word.length( ); i >= 0; i-- ) ** There is no character at word.length( ) for ( int i = word.length( ) - 1; i > 0; i-- ) ** This does not process the character at index 0 Correct way: We iterate from word.length()=4 minus 1 which is 3 to 0 w o r d 0 1 2 3 The length is 4 but the index of the characters is from 0 to 3 We can not exceed the maximum index number in the loop!!!

Nested for Loop Execution The inner loop executes all its iterations for each single iteration of the outer loop Example: how can we produce this output? 1 1 2 1 2 3 1 2 3 4 1 2 3 4 5

Analysis The highest number we print on each line is the same as the line number. for line = 1 to 5 increment by 1 each iteration { for number = 1 to line by 1 print number and a space } print a new line

Arrays Arrays allow us to save data into a data structure and retrieve the data later on in the program as needed. Arrays are useful for many applications, including calculating statistics or representing the state of a game. For example the grades that we read off a file in last week’ s lab could had been stored in an array data structure and retrieved from there.

Arrays An array is a sequence of variables of the same data type. The data type can be any of Java's primitive types (int, short, byte, long, float, double, boolean, char), an array, or a user defined class (like Student type or People type etc). Each variable in the array is an element. We use an index to specify the position of each element in the array.

Declaring and Instantiating Arrays Arrays are objects, so creating an array requires two steps: declaring a reference to the array instantiating the array To declare a reference to the array, use this syntax: datatype [] arrayName; To instantiate an array, use this syntax: arrayName = new datatype[ size ]; where size is an expression that evaluates to an integer and specifies the number of elements. To do it in one line you write: datatype [] arrayName=new datatype[size] i.e. int [] my array=new int[10]; create san array that can store 10 int type elements.

Examples Declaring arrays: Instantiating these arrays: double [] dailyTemps; // elements are doubles String [] cdTracks; // elements are Strings boolean [] answers; // elements are booleans Auto [] cars; // elements are Auto references int [] cs101, bio201; // two integer arrays Instantiating these arrays: dailyTemps = new double[365]; // 365 elements cdTracks = new String[15]; // 15 elements int numberOfQuestions = 30; answers = new boolean[numberOfQuestions]; cars = new Auto[3]; // 3 elements cs101 = new int[5]; // 5 elements bio201 = new int[4]; // 4 elements

Default Values for Elements When an array is instantiated, the elements are assigned default values according to the array data type. Array data type Default value byte, short, int, long float, double 0.0 char space boolean false Any object reference (for example, a String) null

Assigning Initial Values to Arrays Arrays can be instantiated by specifying a list of initial values. Syntax: datatype [] arrayName = { value0, value1, … }; where valueN is an expression evaluating to the data type of the array and is the value to assign to the element at index N. Examples: int nine = 9; int [] oddNumbers = { 1, 3, 5, 7, nine, nine + 2, 13, 15, 17, 19 }; Auto sportsCar = new Auto( "Ferrari", 0, 0.0 ); Auto [] cars = { sportsCar, new Auto( ), new Auto("BMW", 100, 15.0 ) };

an Array of integer values When instantiated: After assigning values:

Accessing Array Elements See Example 8.1 CellBills.java Element Syntax Element 0 arrayName[0] Element i arrayName[i] Last element arrayName[arrayName.length - 1]

Example Entering elements into an array double [] myarray=new double[4]; myarray[0]=3.45; myarray[1]=4.23; myarray[2]=1.00; myarray[3]=0.23; Notice that the last index of the array is 3 and not 4 since we start the counting of the index from 0.

Inserting elements into an array using loops double[] myarray=new double[100]; for( int g=0; g<=myarray.length-1; g++) { myarray[g]= (g*3/5); }

Reading the elements of an array We assign the elements as we read them: double d=myarray[3]; reads the element at index 3 (4th element) and assigns it to variable d.

Reading the elements of an array using for loop for (int k=0; k<=myarray.length-1; k++) { double d=myarray[k]; System.out.println(d); } During each iteration through the loop an element is read and it is outputted.

Reading the elements of an array using for loop Alternatively : for (int k=0; k<=myarray.length-1; k++) { System.out.println(myarray[k]); } Will accomplish the same .

Study Guide Chapter 6 Chapter 8 Sections 6.8, 6.9 6.10