The for Loop. Lesson 11

Similar documents
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.

ECE 122. Engineering Problem Solving with Java

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

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

Loops. CSE 114, Computer Science 1 Stony Brook University

Introduction. C provides two styles of flow control:

Object-Oriented Programming in Java

Repetition Structures

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #16 Loops: Matrix Using Nested for Loop

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

CS 106 Introduction to Computer Science I

Unit 7. 'while' Loops

APCS Semester #1 Final Exam Practice Problems

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

Review Chapter 6 in Bravaco. Short Answers 1. This type of method does not return a value. a. null b. void c. empty d. anonymous

Repetition CSC 121 Fall 2014 Howard Rosenthal

CS110D: PROGRAMMING LANGUAGE I

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

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

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

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

CS1150 Principles of Computer Science Loops (Part II)

Definite Loops. Computer Science S-111 Harvard University David G. Sullivan, Ph.D. Using a Variable for Counting

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

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

Fundamentals of Programming Session 13

Chapter 4 Loops. int x = 0; while ( x <= 3 ) { x++; } System.out.println( x );

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

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

STUDENT LESSON A12 Iterations

Tutorial 3: Conditionals and Iteration COMP 202: Intro to Computing 1

CS 106 Introduction to Computer Science I

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

3 The L oop Control Structure

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 8: SEP. 29TH INSTRUCTOR: JIAYIN WANG

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

Function Call Stack and Activation Records

Chapter 2: Functions and Control Structures

INTRODUCTION TO C++ PROGRAM CONTROL. Dept. of Electronic Engineering, NCHU. Original slides are from

Chapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Scope of this lecture. Repetition For loops While loops

Introduction to Java & Fundamental Data Types

Slide 1 CS 170 Java Programming 1 The Switch Duration: 00:00:46 Advance mode: Auto

Technical Questions. Q 1) What are the key features in C programming language?

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

Introduction to the Java Basics: Control Flow Statements

There are algorithms, however, that need to execute statements in some other kind of ordering depending on certain conditions.

Iterative Languages. Scoping

1 Unit 8 'for' Loops

Decision Making in C

Assignment Definition And General Feedback By Michael Panitz at Cascadia Community College (

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

Problem Solving With Loops

A Bad Idea Monday, April 16, :23 AM

For Loop. Variations on Format & Specific Examples

Programming Lecture 4

Problem Solving through Programming In C Prof. Anupam Basu Department of Computer Science & Engineering Indian Institute of Technology, Kharagpur

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

Accelerating Information Technology Innovation

Programming Lecture 4

Flow Control. CSC215 Lecture

LOOPS. Repetition using the while statement

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

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

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

CSE 114 Computer Science I

(Refer Slide Time: 00:26)

Loops / Repetition Statements

Chapter 5 Loops Liang, Introduction to Java Programming, Tenth Edition, Global Edition. Pearson Education Limited

3chapter C ONTROL S TATEMENTS. Objectives

REPETITION CONTROL STRUCTURE LOGO

Statements execute in sequence, one after the other, such as the following solution for a quadratic equation:

Recap: Assignment as an Operator CS 112 Introduction to Programming

Other Loop Options EXAMPLE

In Java, data type boolean is used to represent Boolean data. Each boolean constant or variable can contain one of two values: true or false.

Unit 3 Decision making, Looping and Arrays

Repetition with for loops

Chapter 3. More Flow of Control. Copyright 2008 Pearson Addison-Wesley. All rights reserved.

CS1150 Principles of Computer Science Methods

1007 Imperative Programming Part II

C++ Reference NYU Digital Electronics Lab Fall 2016

Loops / Repetition Statements. There are three loop constructs in C. Example 2: Grade of several students. Example 1: Fixing Bad Keyboard Input

Learning to Program with Haiku

7. Arrays, More Java Looping

CS 112 Introduction to Programming

If you don t, it will return the same thing as == But this may not be what you want... Several different kinds of equality to consider:

Chapter Overview. More Flow of Control. Flow Of Control. Using Boolean Expressions. Using Boolean Expressions. Evaluating Boolean Expressions

Computer Programming I - Unit 5 Lecture page 1 of 14

Programming Lecture 4

CS125 : Introduction to Computer Science. Lecture Notes #6 Compound Statements, Scope, and Advanced Conditionals

! definite loop: A loop that executes a known number of times. " The for loops we have seen so far are definite loops. ! We often use language like

Mobile App:IT. Methods & Classes

Module 4: Decision-making and forming loops

Motivations. Chapter 5: Loops and Iteration. Opening Problem 9/13/18. Introducing while Loops

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

Primitive data, expressions, and variables

COMP-202: Foundations of Programming. Lecture 3: Boolean, Mathematical Expressions, and Flow Control Sandeep Manjanna, Summer 2015

Lab 09: Advanced SQL

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

Transcription:

The for Loop Lesson 11

Have you ever played Tetris? You know that the game never truly ends. Blocks continue to fall one at a time, increasing in speed as you go up in levels, until the game breaks from bad coding or the player loses. How many lines of code would it take to create a game that goes on forever!? I mean, can you imagine copying hundreds of lines of code over and over and over again until it seems like the game will take a sufficiently long time? There's definitely got to be a way to avoid rewriting the same code over and over again right?

The for loop Lucky for us, there is a way to get our code to repeat, and that's by using loops. Java has two main ways of looping, and those are the "for loop" and the "while loop". We will focus on the for loop for Lesson 11. The for loop has been programming language staples for a long time now, as they have existed is many, many languages.

The For Loop, one of the most common types of loops. The "For" part of "For Loop" seems to have lost its meaning. But you can think of it like this: "Loop FOR a set number of times." The structure of the For Loop is this: for ( start_value; end_value; increment_number ) //YOUR_CODE_HERE

for ( start_value; end_value; increment_number ) //YOUR_CODE_HERE So after the word "for" (in lowercase) you have a pair of round brackets. Inside of the round brackets you need three things: The Initializing Expression aka- the start_value for the loop The Control Expression aka- the end_value for the loop, The Step Expression - tells us how our variable changes as we proceed, how to increment_number through the loop. This is called the increment number, and is usually 1. But it doesn't have to be. You can go up in chunks of 10, if you want.

for ( start_value; end_value; increment_number ) //YOUR_CODE_HERE After the round brackets you need a pair of curly brackets. The curly brackets are used to section off the code that you want to execute repeatedly. An example might clear things up.

Simple example: Suppose we want to sum up all the integers from 3 to 79. One of the statements that will help us do this is: sum = sum + j; However, this only works if we repeatedly execute this line of code, first with j = 3, then with j = 4, j = 5, and finally with j = 79. The full structure of the for-loop that will do this is: 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. System.out.println( The final sum is + sum); // prints 3157

Special features of the for-loop The break command: If the keyword break is executed inside a for-loop, the loop is immediately exited (regardless of the control statement). Execution continues with the statement immediately following the closing brace of the for-loop. Declaring the loop variable: It is possible to declare the loop variable in the initializing portion of the parenthesis of a for-loop as follows: for (int j = 3; j <= 79; j++)...

for (int j = 3; j <= 79; j++)... In this case the scope of j is confined to the interior of the loop. If we write j in statement outside the loop (without redeclaring it to be an int), it won t compile. The same is true of any other variable declared inside the loop. Its scope is limited to the interior of the loop and is not recognized outside the loop as is illustrated in the following code: for (j = 3; j <= 79; j++) double d = 102.34;... System.out.println(d); //won t compile because of this line because it is declared on the inside of the loop.

No braces: If there is only one line of code or just one basic structure (an if-structure or another loop) inside a loop, then the braces are unnecessary. In this case it is still correct (and highly recommended) to still have the braces but you can leave them off. for (j = 3; j <= 79; j++) sum = sum + j; is equivalent to for (j = 3; j <= 79; j++) sum = sum + j;

When the loop finishes: It is often useful to know what the loop variable is after the loop finishes: for (j = 3; j <= 79; j++)... some code... System.out.println(j); //80 On the last iteration of the loop, j increments up to 80 and this is when the control statement j <= 79 finally is false. Thus, the loop is exited.

Nested loops: Nested loops is the term used when one loop is placed inside another as in the following example: for(int j = 0; j < 5; j++) System.out.println( Outer loop ); // executes 5 times for(int k = 0; k < 8; k++) System.out.println(...Inner loop ); // executes 40 times The inner loop iterates eight times for each of the five iterations of the outer loop. Therefore, the code inside the inner loop will execute 40 times.

Warning: A very common mistake is to put a semicolon immediately after the parenthesis of a for loop as is illustrated by the following code: for (j =3; j <= 79; j++); //This block of code is only executed once because of the inappropriately //placed semicolon above.... some code...

Assignment Exercise 11 questions. Try to figure them out without putting them into JCreator, then check your answers by running them in JCreator. Due tomorrow Extension Activity 11 (Online)