Lecture 14. 'for' loops and Arrays

Similar documents
Combo Lecture Lecture 14/15. Instructor: Craig Duckett

Lecture 15. Arrays (and For Loops)

Lecture 17. For Array Class Shenanigans

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

Loops. CSE 114, Computer Science 1 Stony Brook University

Accelerating Information Technology Innovation

Last Class. While loops Infinite loops Loop counters Iterations

ECE 122. Engineering Problem Solving with Java

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018

Following is the general form of a typical decision making structure found in most of the programming languages:

Repetition Structures

CompSci 125 Lecture 11

CS111: PROGRAMMING LANGUAGE II

Control Flow Statements

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

Condition-Controlled Loop. Condition-Controlled Loop. If Statement. Various Forms. Conditional-Controlled Loop. Loop Caution.

COMP 250: Java Programming I. Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette

Introduction to the Java Basics: Control Flow Statements

Object Oriented Programming. Java-Lecture 6 - Arrays

The Java language has a wide variety of modifiers, including the following:

Lecture 17. Instructor: Craig Duckett. Passing & Returning Arrays

Assignment 2.4: Loops

Warmup : Name that tune!

Java Loop Control. Programming languages provide various control structures that allow for more complicated execution paths.

Top-Down Program Development

Repetition. Chapter 6

Repetition. Chapter 6

Administration. Conditional Statements. Agenda. Syntax. Flow of control. Lab 2 due now on floppy Lab 3 due tomorrow via FTP

(A) 99 ** (B) 100 (C) 101 (D) 100 initial integers plus any additional integers required during program execution

AP CS Unit 3: Control Structures Notes

Lecture 14 CSE11 Fall 2013 For loops, Do While, Break, Continue

Java Coding 3. Over & over again!

Controls Structure for Repetition

Lecture 10. Instructor: Craig Duckett

Conditionals, Loops, and Style

Introduction to Java & Fundamental Data Types

McGill University School of Computer Science COMP-202A Introduction to Computing 1

STUDENT LESSON A12 Iterations

Computer Science is...

CONTENTS: Array Usage Multi-Dimensional Arrays Reference Types. COMP-202 Unit 6: Arrays

CS Introduction to Programming Midterm Exam #1 - Prof. Reed Fall 2009

CSE115 / CSE503 Introduction to Computer Science I Dr. Carl Alphonce 343 Davis Hall Office hours:

For that purpose, java provides control structures that serve to specify what has to be done by our program, when and under which circumstances.

CMPT 125: Lecture 4 Conditionals and Loops

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

Lecture Set 4: More About Methods and More About Operators

(A) 99 (B) 100 (C) 101 (D) 100 initial integers plus any additional integers required during program execution

COMP-202: Foundations of Programming. Lecture 4: Flow Control Loops Sandeep Manjanna, Summer 2015

Java I/O and Control Structures

Lecture 6. Instructor: Craig Duckett

Exercise 4: Loops, Arrays and Files

13 th Windsor Regional Secondary School Computer Programming Competition

Loops and Expression Types

Chapter 6 SINGLE-DIMENSIONAL ARRAYS

Array. Lecture 12. Based on Slides of Dr. Norazah Yusof

Last Class. More on loops break continue A bit on arrays

Conditionals, Loops, and Style. Control flow thus far. if statement. Control flow. Common branching statement Evaluate a boolean expression

Scope of this lecture. Repetition For loops While loops

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

CONTENTS: While loops Class (static) variables and constants Top Down Programming For loops Nested Loops

Chapter 4: Control Structures I

Bjarne Stroustrup. creator of C++

Example: Computing prime numbers

Lecture 8 " INPUT " Instructor: Craig Duckett

CS111: PROGRAMMING LANGUAGE II

SAMPLE QUESTIONS FOR DIPLOMA IN INFORMATION TECHNOLOGY; YEAR 1

CSEN 202 Introduction to Computer Programming

CS 102 / CS Introduction to Programming Midterm Exam #1 - Prof. Reed Fall 2010

Flow Control. Key Notion. Statement Categories. 28-Oct-10

Lesson 7 Part 2 Flags

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

Computer Programming: C++

Lecture Set 4: More About Methods and More About Operators

COMP-202: Foundations of Programming. Lecture 8: for Loops, Nested Loops and Arrays Jackie Cheung, Winter 2016

Java I/O and Control Structures Algorithms in everyday life

H212 Introduction to Software Systems Honors

Glossary. (Very) Simple Java Reference (draft, v0.2)

Flow Control. Boaz Kantor Introduction to Computer Science, Fall semester IDC Herzliya

I. True/False: (2 points each)

Loops! Step- by- step. An Example while Loop. Flow of Control: Loops (Savitch, Chapter 4)

int j = 0, sum = 0; for (j = 3; j <= 79; j++) { sum = sum + j; System.out.println(sum); //Show the progress as we iterate thru the loop.

CS 231 Data Structures and Algorithms Fall Arrays Lecture 07 - September 19, Prof. Zadia Codabux

Arrays: Higher Dimensional Arrays. CS0007: Introduction to Computer Programming

COMP-202 Unit 4: Programming with Iterations

Oct Decision Structures cont d

AP COMPUTER SCIENCE A

AP Computer Science Homework Set 1 Fundamentals

CS1004: Intro to CS in Java, Spring 2005

Handout 4 Conditionals. Boolean Expressions.

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

All copyrights reserved - KV NAD, Aluva. Dinesh Kumar Ram PGT(CS) KV NAD Aluva

CP122 CS I. Iteration

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

Java Application Development

CSC 1051 Data Structures and Algorithms I

cis20.1 design and implementation of software applications I fall 2007 lecture # I.2 topics: introduction to java, part 1

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

Building Java Programs

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

Computer Programming I - Unit 5 Lecture page 1 of 14

Transcription:

Lecture 14 'for' loops and Arrays

For Loops for (initiating statement; conditional statement; next statement) // usually incremental body statement(s); The for statement provides a compact way to iterate over a range of values. Programmers often refer to it as the "for loop" because of the way in which it repeatedly loops until a particular condition is satisfied. The general form of the for statement can be expressed as above. Yay! You can use this instead of a counting-while-loop!!

For Loops for (initiating statement; conditional statement; next statement) // usually incremental body statement(s); class ForLoopDemo public static void main(string[] args) for(int count = 1; count < 11; count++) System.out.println("Count is: " + count); The output of this program is: Count is: 1 Count is: 2 Count is: 3 Count is: 4 Count is: 5 Count is: 6 Count is: 7 Count is: 8 Count is: 9 Count is: 10

For Loops There are three clauses in the for statement. The init-stmt statement is done before the loop is started, usually to initialize an iteration variable ( counter ). After initialization this part of the loop is no longer touched. The condition expression is tested before each time the loop is done. The loop isn't executed if the Boolean expression is false (the same as the while loop). The next-stmt statement is done after the body is executed. It typically increments an iteration variable ( adds 1 to the counter ). for(int count = 1; count < 11; count++) System.out.println("Count is: " + count);

For or While? The for loop is shorter, and combining the intialization, test, and increment in one statement makes it easier to read and verify that it's doing what you expect. The for loop is better when you are counting something. If you are doing something an indefinite number of times, the while loop is be the better choice.

For or While? class WhileDemo public static void main(string[] args) int count = 1; while (count < 11) System.out.println("Count is: " + count); count++; class ForLoopDemo public static void main(string[] args for(int count = 1; count < 11; count++) System.out.println("Count is: " + count);

Do-While Loops The Java programming language also provides a do-while statement, which can be expressed as follows: do statement(s) while (expression); The difference between do-while and while is that do-while evaluates its expression at the bottom of the loop instead of the top. Therefore, the statements within the do block are always executed at least once, as shown in the following DoWhileDemo program: class DoWhileDemo public static void main(string[] args) int count = 1; do System.out.println("Count is: " + count); count++; while (count < 11);

While or Do-While?

If-else Statements if(boolean_expression) statement 1 //Executes when true else //<-- No Conditional statement 2 //Executes when false public class IfElseTest public static void main(string args[]) int x = 30; if( x < 20 ) System.out.print( The number is less than 20."); else System.out.print( The number is NOT less than 20!");

Several If Statements int grade = 98; if(grade >=0 && grade < 60) System.out.println( Sorry. You did not pass. ); if(grade >= 60 && grade < 70) System.out.println( You just squeaked by. ); if(grade >= 70 && grade < 80) System.out.println( You are doing better. ); if(grade >= 80 && grade < 90) System.out.println( Not too bad a job! ); if(grade >= 90 && grade <= 100) System.out.println( You are at the top of your class! );

int grade = 68; Cascading If Statements if(grade >=0 && grade < 60) System.out.println("Sorry. You did not pass."); else if(grade >= 60 && grade < 70) System.out.println("You just squeaked by."); else if(grade >= 70 && grade < 80) System.out.println("You are doing better."); else if(grade >= 80 && grade < 90) System.out.println("Not too bad a job!"); else //(grade >= 90 && grade <= 100) System.out.println("You are at the top of your class!");

Cascading If Statements int grade = 68; if(grade >=0 && grade < 60) System.out.println("Sorry. You did not pass."); else if(grade >= 60 && grade < 70) System.out.println("You just squeaked by."); else if(grade >= 70 && grade < 80) System.out.println("You are doing better."); else if(grade >= 80 && grade < 90) System.out.println("Not too bad a job!"); else // <-- No conditional System.out.println("You are at the top of your class!");

Cascading If Statement if (this.frontisblocked()) this.turnaround(); else if (this.canpickthing()) this.turnright(); else if (this.leftisblocked()) this.turnleft(); else this.move();

Switch statement The switch statement is similar to the cascading-if statement in that both are designed to choose one of several alternatives. The switch statement is more restrictive in its use, however, because it uses a single value to choose the alternative to execute. The cascading-if can use any expressions desired. This restriction is also the switch statement s strength: the coder knows that the decision is based on a single value. switch ( expression ) case value1 : statement(s) when expression == value1; break; case value2 : statement(s) when expression == value2; break; case value3 : statement(s) when expression == value3; break; default : statement(s) if no previous match;

Switch Statement

int score = 8; Switch Statement switch (score) case 10: System.out.println ("Excellent."); // intentional fall-through case 9: System.out.println ( Well above average."); break; case 8: System.out.println ( Above average."); break; case 7: case 6: System.out.print ("Average. You should seek help."); break; default : System.out.println ("Not passing.");

Control Statement Review

Introduction to Arrays So far, you have been working with variables that hold only one value. The integer variables you have set up have held only one number (and later in the quarter we will see how string variables will hold one long string of text). An array is a collection to hold more than one value at a time. It's like a list of items. Think of an array as like the columns in a spreadsheet. You can have a spreadsheet with only one column, or several columns. grades The data held in a single-list (one-dimensional) array might look like this: 0 100 1 89 2 96 3 100 4 98

Declaring Arrays grades 0 100 1 89 2 96 3 100 4 98 int[ ] grades; The difference between setting up a normal integer variable and an array is a pair of square brackets after the data type. The square brackets tells Java that you want to set up an integer array. The name of the array above is grades. The sqauare brackets don't say how many positions the array should hold. To do that, you have to set up a new array object: grades = new int[5]; In between the square brackets you need the pre-defined size of the array. The size is how many positions the array should hold. If you prefer, you can put all that on one line: NOTE: Arrays must be of the same data type, i.e., all integers (whole numbers) or all doubles (floating-point numbers) or all strings (text characters) you cannot mix-and-match data types in an array. int[ ] grades = new int[5];

Putting Values into Arrays grades 0 100 1 89 2 96 3 100 4 98 You can also declare the int separately and call it by its given name, like this: int summer2012 = 5; int[ ] grades = new int[summer2012]; We are telling Java to set up an array with 5 positions in it. After this line is executed, Java will assign default values for the array (0 for an integer array). To assign values to the various positions in an array, you do it in the normal way: grades[0] = 100; grades[1] = 89; grades[2] = 96; grades[3] = 100; grades[4] = 98; grades [0] = 100; Length of the grades [1] = 89; array is equal to grades [2] = 96; the number of grades [3] = 100; slots declared grades [4] = 98; This is called the index If you know what values are going to be in the array, you can set them up like this instead: int[ ] grades = 100, 89, 96, 100, 98 ; // Java treats as a // new instance

Array notes Arrays have a built in value length: Int []myarray = new int [5]; MyArray.length returns 5 Constructing an array with new makes space for length * datatype memory In Java (and most other modern languages), indices are zero based the first value is in myarray[0], the last in myarray[length-1]. This means you can write loops with just a <: for (int j=0; j < myarray.length; j++)