ECE 122. Engineering Problem Solving with Java

Similar documents
Loops. CSE 114, Computer Science 1 Stony Brook University

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

Arrays. Outline 1/7/2011. Arrays. Arrays are objects that help us organize large amounts of information. Chapter 7 focuses on:

CS313D: ADVANCED PROGRAMMING LANGUAGE

The for Loop. Lesson 11

Accelerating Information Technology Innovation

Lecture 7 Tao Wang 1

Lesson 06 Arrays. MIT 11053, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL

CS111: PROGRAMMING LANGUAGE II

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

Repetition Structures

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

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

Loops! Loops! Loops! Lecture 5 COP 3014 Fall September 25, 2017

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

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

Loops and Files. Chapter 04 MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz

Computer Programming I - Unit 5 Lecture page 1 of 14

Chapter 5: Control Structures II (Repetition) Objectives (cont d.) Objectives. while Looping (Repetition) Structure. Why Is Repetition Needed?

Problem: Read 10 numbers from the keyboard and store them

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

CPE 112 Spring 2015 Exam II (100 pts) March 4, Definition Matching (8 Points)

C++ Programming: From Problem Analysis to Program Design, Fourth Edition. Chapter 5: Control Structures II (Repetition)

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

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

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

Last Class. While loops Infinite loops Loop counters Iterations

Chapter 4: Control structures. Repetition

Problem Solving With Loops

REPETITION CONTROL STRUCTURE LOGO

Chapter 4: Control structures

Le L c e t c ur u e e 3 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Control Statements

Repetition, Looping. While Loop

Method OverLoading printf method Arrays Declaring and Using Arrays Arrays of Objects Array as Parameters

Instructor: SIR MUHAMMAD NAVEED Created by: ARSLAN AHMED SHAAD ( ) MUHAMMAD BILAL ( ) ISIT:

Review for Test 1 (Chapter 1-5)

204111: Computer and Programming

LECTURE 5 Control Structures Part 2

PROGRAMMING FUNDAMENTALS

*Starting Out with C++: From Control Structures through Objects, 7/E* by *Tony Gaddis* COMPUTER PROGRAMMING LECTURE 05 LOOPS IMRAN IHSAN

Lecture 14. 'for' loops and Arrays

Programming with Java

H212 Introduction to Software Systems Honors

TOPICS TO COVER:-- Array declaration and use.

Name Section: M/W T/TH Number Definition Matching (8 Points)

CS1004: Intro to CS in Java, Spring 2005

5.1. Chapter 5: The Increment and Decrement Operators. The Increment and Decrement Operators. Looping. ++ is the increment operator.

Java. Programming: Chapter Objectives. Why Is Repetition Needed? Chapter 5: Control Structures II. Program Design Including Data Structures

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

Building Java Programs

Building Java Programs

Administration. Objects and Arrays. Objects. Agenda. What is an Object? What is a Class?

5.1. Chapter 5: The Increment and Decrement Operators. The Increment and Decrement Operators. The Increment and Decrement Operators

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

CMPT 125: Lecture 4 Conditionals and Loops

STUDENT LESSON A12 Iterations

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

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

Repetition CSC 121 Fall 2014 Howard Rosenthal

Control Statements. Musa M. Ameen Computer Engineering Dept.

Control Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003

CompSci 125 Lecture 11

Repetition and Loop Statements Chapter 5

Introduction to Programming Using Java (98-388)

CSE 114 Computer Science I

CSC128 FUNDAMENTALS OF COMPUTER PROBLEM SOLVING Chapter 4: Repetition Control Structure

Conditionals and Loops

Class C{ int a; } what variables below are objects : a. C c; b. String str; c. Scanner scanner; d. int num; e. float f;

An Introduction to Programming with C++ Sixth Edition. Chapter 7 The Repetition Structure

Increment and the While. Class 15

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

Introduction. C provides two styles of flow control:

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

Control Structures of C++ Programming (2)

C Programming for Engineers Structured Program

Introduction to the Java Basics: Control Flow Statements

Review. Primitive Data Types & Variables. String Mathematical operators: + - * / % Comparison: < > <= >= == int, long float, double boolean char

CS110D: PROGRAMMING LANGUAGE I

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

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

Chapter 9 Introduction to Arrays. Fundamentals of Java

Recap: Assignment as an Operator CS 112 Introduction to Programming

Flow Control. CSC215 Lecture

COMSC-051 Java Programming Part 1. Part-Time Instructor: Joenil Mistal

Name Section: M/W T/TH Number Definition Matching (6 Points)

The University of Alabama in Huntsville Electrical and Computer Engineering CPE Example of Objective Test Questions for Test 4

Example: Monte Carlo Simulation 1

Loops / Repetition Statements

Repeating Instructions. C# Programming: From Problem Analysis to Program Design 2nd Edition. David McDonald, Ph.D. Director of Emerging Technologies

Chapter 4 Loops. Lecture notes for computer programming 1 Faculty of Engineering and Information Technology Prepared by: Iyad Albayouk

Repetition, Looping CS101

AP Computer Science A

Example. Write a program which sums two random integers and lets the user repeatedly enter a new answer until it is correct.

Introduction to Java & Fundamental Data Types

CS 112 Introduction to Programming

Outline. Overview. Control statements. Classes and methods. history and advantage how to: program, compile and execute 8 data types 3 types of errors

CS171:Introduction to Computer Science II

Solving Problems Flow Control in C++ CS 16: Solving Problems with Computers I Lecture #3

More on control structures

Chapter 5: Loops and Files

Transcription:

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 as while and do-while Structure provides more compact representation Arrays Efficient representation of large amount of data

The for loop 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

Logic of a for loop initialization condition evaluated true false statement increment Does initializing, pretest, increment and posttest..

The for Statement A for loop is functionally equivalent to the following while loop structure: initialization; while ( condition ) { statement; increment; } Know how to write the same functionality in ALL loops.

The for Statement An example of a for loop: for (int count=1; count <= 5; count++) System.out.println (count); The initialization section can be used to declare a variable Like a while loop, the condition of a for loop is tested prior to executing the loop body Therefore, the body of a for loop will execute zero or more times

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 Question: Can I use num outside of the loop?

The for Statement 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, and therefore creates an infinite loop If the increment is left out, no increment operation is performed continue keyword break keyword

Break & Continue Continue statement means skip to the end of the loop and do the next iteration Break means skip to the end of the loop and exit the loop. for(int idx = 0; idx < 10; idx++) { if(idx < 4) continue; if(idx > 7) break; System.out.println( Counter is + idx); }

Example of break int sum = 0; int item = 0; while (item < 5) { } item ++; sum += item; if (sum >= 6) break; System.out.println("The sum is " + sum); Break makes it difficult to determine how many times the loop Is executed

Example of continue int sum = 0; int item = 0; while (item < 5) { item++; if (item == 2) continue; sum += item; } System.out.println("The sum is " + sum); Continue can be used for special conditions

For Loop Advice Don t use the index counter after exit from the loop. Don t modify the index value inside the loop Use continue and break with caution. Having one place where the exit criteria of the loop is stated is a good thing

For Loop Advice Try to limit nesting to no more than three levels of loops in one section of code Try to keep the bodies of loops fairly small, ideally within one page view. Be even more careful about using breaks or continues in very long loop bodies for (int num=100; num > 0; num -= 5) { if (num == 10); break; }

From while to for int i = startvalue; while (i < endvalue) {... i++; } for (int i=startvalue; i<endvalue; i++) {... }

Nesting for-loops Inside the loop body of a for-loop, we can put another forloop Each time through the 1 st for-loop, we execute the 2 nd loop until its guard is false Handy for printing tables like this: 1 1 1 1 1 1 2 2 2 2 2 2 3 3 3 3 3 3 4 4 4 4 4 4

Simple example for (int i=0; i<5; i++) { for (int j=0; j<3; j++) { System.out.print(i+ ); } System.out.println(); } How many values are printed out by these loops?

Arrays An array is an ordered list of values The entire array has a single name Each value has a numeric index 0 1 2 3 4 5 6 7 8 9 scores 79 87 94 82 67 98 87 81 74 91 An array of size N is indexed from zero to N-1 This array holds 10 values that are indexed from 0 to 9

Arrays A particular value in an array is referenced using the array name followed by the index in brackets For example, the expression scores[2] scores 0 1 2 3 4 5 6 7 8 9 79 87 94 82 67 98 87 81 74 91 refers to the value 94 (the 3rd value in the array) Expression represents a place to store a single integer Can be used wherever an integer variable can be used

Arrays For example, an array element can be assigned a value, printed, or used in a calculation just like any other variable, BUT the array name and the specific entry or item in the array must be unambiguously used in the expression: scores[2] = 89; a = scores[10]; scores[first] = scores[first] + 2; mean = (scores[0] + scores[1])/2; System.out.println ("Top = " + scores[5]); Need both array name and index together!

Arrays The values held in an array are called array elements An array stores multiple values of the same type the element type The element type can be a primitive type or an object reference We can create an array of integers, an array of characters, an array of String objects, etc In Java, the array itself is an object that must be instantiated (will show ahead)

Arrays Another way to depict the scores array: scores 79 87 94 82 67 98 87 81 74 91 This is telling you that scores (itself) is a Reference! Scores points to the array.

Declaring Arrays The scores array could be declared as follows: int[] scores = new int[10]; Note the syntax, the reference and the new object! It also says that there will be 10 scores referenced. The type of the variable scores is int[] ( an array of integers or an array of ints. ) Note that the array type does not specify its size, but each object of that type has a specific size The reference variable scores is set to a new array object that can hold 10 integers

Declaring Arrays Some other examples of array declarations: float[] prices = new float[500]; boolean[] flags; flags = new boolean[20]; char[] codes = new char[1750];

Summary For loop generally requires an index Indicates number of times loop will be executed For loop contains an initializer, condition, and condition modifier Arrays represent data is a series of memory locations All data has same array name Specific locations located with subscripts For loops and arrays go together well Fixed number of loop iterations and array size