Lecture 4: Looping Tami Meredith. Back to Basics... Programming requires: 1. Identification of the problem. 2. Solving the problem: A. Selecting the data.

Slides:



Advertisements
Similar presentations
Week 5: Loops 1.  Repetition is the ability to do something over and over again  With repetition in the mix, we can solve practically any problem that.
Advertisements

Introduction to Computing Science and Programming I
Dr. Yang, Qingxiong (with slides borrowed from Dr. Yuen, Joe) LT4: Control Flow - Loop CS2311 Computer Programming.
Computer programming Lecture 3. Lecture 3: Outline Program Looping [Kochan – chap.5] –The for Statement –Relational Operators –Nested for Loops –Increment.
10-Jun-15 Just Enough Java. Variables A variable is a “box” that holds data Every variable has a name Examples: name, age, address, isMarried Variables.
1 Control Structures (and user input). 2 Flow of Control The order statements are executed is called flow of control By default, statements in a method.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 5 Looping.
CS 106 Introduction to Computer Science I 02 / 12 / 2007 Instructor: Michael Eckmann.
Introduction to Computers and Programming for Loops  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course. Introduction to.
Logical Operators Java provides two binary logical operators (&& and ||) that are used to combine boolean expressions. Java also provides one unary (!)
Chapter 5: Loops and Files.
Loops – While, Do, For Repetition Statements Introduction to Arrays
Aalborg Media Lab 23-Jun-15 Software Design Lecture 6 “Conditionals and Loops”
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition.
TODAY’S LECTURE Review Chapter 2 Go over exercises.
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.
Lecture 10 Instructor: Craig Duckett. Assignment 2 Revision TONIGHT DUE TONIGHT Wednesday, August 5 th Assignment 3 NEXT DUE NEXT Monday, August 10 th.
Chapter 2 - Algorithms and Design
Week 5 - Wednesday.  What did we talk about last time?  Exam 1!  And before that?  Review!  And before that?  if and switch statements.
Principles of Programming - NI July Chapter 5: Structured Programming In this chapter you will learn about: Sequential structure Selection structure.
Logic Our programs will have to make decisions on what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if and if-else.
Logic Our programs will have to make decisions in terms of what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if.
Chapter 3- Flow Control. Overview n Why flow control n Branches vs. Loops n Branch statements n Loop Statements n Complex loops n Boolean variables n.
CSCI 3328 Object Oriented Programming in C# Chapter 5: C# Control Statement – Part II – Exercises 1 Xiang Lian The University of Texas Rio Grande Valley.
Chapter 5: Structured Programming
Logic Our programs will have to make decisions on what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if and if-else.
Chapter 7 Selection Dept of Computer Engineering Khon Kaen University.
+ Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Chapter 5: Looping.
Control Structures - Selections - Repetitions/iterations (part 2) 1 -Based on slides from Deitel & Associates, Inc. - Revised by T. A. Yang.
Lecture 6: Midterm Review Tami Meredith. Programming Process How do we fill in the yellow box? Text Editor Compiler (javac) Interpreter (JVM: java) User.
Lecture 2: 1226 Review Tami Meredith. Programming Process How do we fill in the yellow box? Text Editor Compiler (javac) Interpreter (JVM: java) User.
Flow of Control Chapter 3. Outline Branching Statements Java Loop Statements Programming with Loops The Type boolean.
Sections © Copyright by Pearson Education, Inc. All Rights Reserved.
Lecture 12: Final Review Tami Meredith. Programming Requires 1. Identification of the problem Understanding it, identifying correct solutions 2. Solving.
Lecture 3: Branching Tami Meredith. Roadmap Brief Review of last class OOP and Methods: using the library procedures Strings Revisited: A useful Class/Data.
ITP © Ron Poet Lecture 6 1 More on if. ITP © Ron Poet Lecture 6 2 Remembering Tests  We often want to remember the result of a test, so that we can use.
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 5 Looping.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Beginning C For Engineers Fall 2005 Lecture 3: While loops, For loops, Nested loops, and Multiple Selection Section 2 – 9/14/05 Section 4 – 9/15/05 Bettina.
1 Control Structures (Chapter 3) 3 constructs are essential building blocks for programs Sequences  compound statement Decisions  if, switch, conditional.
Chapter 2: Fundamental Programming Structures in Java Adapted from MIT AITI Slides Control Structures.
Midterm Review Tami Meredith. Primitive Data Types byte, short, int, long Values without a decimal point,..., -1, 0, 1, 2,... float, double Values with.
Chapter 6: Looping. Objectives Learn about the loop structure Create while loops Use shortcut arithmetic operators Create for loops Create do…while loops.
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.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Lecture 7 – Repetition (Loop) FTMK, UTeM – Sem /2014.
Dr. Sajib Datta Jan 23,  A precedence for each operator ◦ Multiplication and division have a higher precedence than addition and subtraction.
Introduction to Programming G50PRO University of Nottingham Unit 6 : Control Flow Statements 2 Paul Tennent
C Program Control September 15, OBJECTIVES The essentials of counter-controlled repetition. To use the for and do...while repetition statements.
Flow Control. Comments u Comments: /* This is a comment */ –Use them! –Comments should explain: v special cases v the use of functions (parameters, return.
Copyright © 2014 Pearson Addison-Wesley. All rights reserved. 4 Simple Flow of Control.
Lecture 4b Repeating With Loops
EGR 2261 Unit 4 Control Structures I: Selection
Primitive Data, Variables, Loops (Maybe)
JavaScript: Control Statements.
MSIS 655 Advanced Business Applications Programming
Sentinel logic, flags, break Taken from notes by Dr. Neil Moore
The University of Texas – Pan American
Chapter 4 - Program Control
CSCI 3328 Object Oriented Programming in C# Chapter 5: C# Control Statement – Part II – Exercises UTPA – Fall 2012 This set of slides is revised from.
3 Control Statements:.
Computer programming Lecture 3.
Just Enough Java 17-May-19.
Using C++ Arithmetic Operators and Control Structures
Loops CGS3416 Spring 2019 Lecture 7.
Presentation transcript:

Lecture 4: Looping Tami Meredith

Back to Basics... Programming requires: 1. Identification of the problem. 2. Solving the problem: A. Selecting the data structures, and Data Management is the key here B. Identifying an algorithm Control Flow is the basis of algorithms 3. Coding the solution 4. Testing, debugging, verifying the solution

Control is Power! Control flow is actually very simple: 1. Everything is sequential, unless Something is optional (last class) Conditional Statements, i.e,. if 3. Something is repeated (this class) Looping Statements, i.e., do, for, while 4. Something complex is broken into simpler parts (last class, next class) i.e., methods, classes, objects

Control Flow Until now all programs have been sequential We do the instructions one after another without skipping or jumping over any This is the default flow of execution This is very limiting Need ways to say:  "lets only do... when... occurs"  "do this.... if.... happens and do.... otherwise"  "do this.... X times"

Exiting a program There are 3 ways to exit a program 1. Execution ends normally when the end of main is reached 2. Execution ends any time there is a return inside main 3. Execution ends any time, in any method, when System.exit( n ) occurs n is the integer exit code 0 if all is OK, other values for different errors OK for now to always use 0

Branching (Conditional Execution) We have the " if " statement in Java to make control flow choices if ( test ) true-actions else false-actions Example: int n1 = 3; int n2 = 4; if (n1 < n2) { // First block, true actions System.out.println("N1 is smaller"); } else { // Second (else) block, false actions System.out.println("N2 is equal or smaller"); }

Alternative Format if ( test ) true-actions No "else" part in this version Example: int n1 = 3; int n2 = 4; int result = 0; if (n1 != 0) { // Guard against division by 0 result = n2 / n1; } // println is always done System.out.println("Quotient is " + result);

Multiple Definitions We can combine definitions using a comma if they have the same type For example, int count = 0; int stop = 5; is the same as, int count = 0, stop = 5;

Blocks We can group a set of statements that we wish to perform Such a group is called a "Block" Blocks are identified with { and } We use blocks to put more than one statement in the "true-actions" and "false-actions" of if statements

Example int n1 = 3, n2 = 4, result = 0; if (n1 != 0) // No block, only assignment controlled by if result = n2 / n1; System.out.println("Quotient is " + result); if (n1 != 0) { // Block used, adds clarity result = n2 / n1; } System.out.println("Quotient is " + result);

Example Continued, Making println conditional int n1 = 3, n2 = 4, result = 0; // without a block if (n1 != 0) result = n2 / n1; if (n1 != 0) System.out.println("Quotient is " + result); if (n1 != 0) { // with a block result = n2 / n1; System.out.println("Quotient is " + result); }

Style Points Things inside a block should be indented Indenting indicates that something is in a block, it does not CAUSE it to be part of the block Blocks should be used liberally Blocks have no detrimental impacts on performance Like parentheses, blocks add clarity and make code more understandable Indentation can be 2, 4, or 8 spaces, but MUST be consistent for the entire program

Boolean Operators && (and) Both are true || (or) Either one or the other (or both) are true !(not)Negation, reverses a boolean value Operand 1Operand2Op1 && Op2Op1 || Op2 ! Op1 true false truefalse truefalse truefalsetrue false true

Example int min = 0, max = 10, val = 5; if (min <= val) { // Nested If statements, same as AND (&&) if (val <= max) { System.out.println("Value " + val + " is in range [min,max]"); } if ((min <= val) && (val <= max)) { // AND condition to combine tests System.out.println("Value " + val + " is in range [min,max]"); }

Example int min = 0, max = 10, val = 5; // Multiple if statements, same as OR (||) if (val < min) { System.out.println("Value " + val + " is not in range [min,max]"); } if (max < val) { System.out.println("Value " + val + " is not in range [min,max]"); } // OR condition to combine tests if ((val < min) || (max < val)) { System.out.println("Value " + val + " is not in range [min,max]"); }

Exercise Write a program with an integer variable named val1 If val1 is less than 0 print negative the screen If val1 is greater than 0 print positive to the screen If val1 equals zero, print zero to the screen

Solution // Integer variable tester, By Tami Meredith public class inttest { /* Define the method main for the program */ public static void main (String[] args) { int val1 = 77; if (val1 < 0) { System.out.println("negative"); } else if (val1 > 0) { System.out.println("positive"); } else { System.out.println("zero"); } } // end main() } // end class inttest

A Note My solutions tend to be a little cramped I am trying to fit things on the slide but keep the font large so you can read it I don't have a lot of space to work with as a result These examples are formatted OK, but could be a lot better! Format variation is allowed... main (String[] args) { main (String[] args) // stuff versus { } // stuff }

Placing the Curly Braces // compact, but { harder to see if (x != 0) { System.out.println("Not zero."); } // stand-alone, clearer but longer files if (x < 0) { System.out.println("Negative."); }

Choices are not enough if lets us chose whether to do something We create conditions (which are often quite complex) and based on these conditions (i.e., tests) code is either executed or ignored But, making choices is still only half the issue... What if we want to do something more than once?

Some Inefficient Code // Program, counts from 0 to the value "stop" int count = 0; int stop = 8 System.out.println(count); // print 0 count = count + 1; if (count <= stop) { System.out.println(count); // print 1 } count = count + 1; if (count <= stop) { System.out.println(count); // print 2 } // And so on, and so on... (need a better way if stop == 100!) // Must have enough tests to ensure we always reach stop

Our First Loop // Program, counts from 0 to the value stop int count = 0; int stop = 8; while (count <= stop) { System.out.println(count); count = count + 1; } // end of loop, go back to test

Loops Loops repeat an action (or set of actions) while a test is true 3 kinds of loops: while, do, for All just vary only in when the test is applied

While Loops Format: while (test) { // body: do while the test is true // May do this 0 times (never!) } Example: int x = 1; while (x < 10) { System.out.println(x); x = x + 1; }

Do Loops Format: do { // body: do until the test is true // Always does at least once } while (test); Example: int x = 1; do { System.out.println(x); x = x + 1; } while (x <= 10);

For Loops Format: for (init; test; step){ // body: do while the test is true } Init: Done exactly once before the loops begins, Initialisation Test: Done before each time the body is executed Step: Done after each time the body is executed and before the next test Example: int x; for (x = 0; x <= 10; x = x + 1) { System.out.println(x); }

Congratulations You are programmers now! Variables/Data + If + Loops = Programs! Just like driving a car = speeding up + slowing down + turning left or right All the rest is the equivalent of knowing when to turn, when to speed up, what the yellow lights mean (go faster)... Programming is knowing when to loop, what variables you need, when to branch You can do everything you need now From this point onwards we learn ways to improve our programs, not do more

Infinite Loops Many ways to create an infinite loop Most likely we will do it by accident, but its not hard... int x = 0; while (true) { // print 0 forever System.out.println(x); } for (;;) { // Same thing... System.out.println(x); }

Exiting a loop Loops end when we fail the test BUT, we can "jump out" of a loop anytime we want Use break to exit a loop while (true) { System.out.println(x); if (x == 20) { break; } x = x + 2; }

Nested Loops Loops can contain other loops! This is confusing at first, we'll come back to it more later on int i, j; for (i = 0; i < 11; i = i + 1) { for (j = 0; j < 11; j = j + 1) { System.out.println((i*10) + j); }

Incrementing We tend to increment variables a lot when using loops E.g., i = i + 1; To save typing (remember, programmers are lazy) the increment operators were created: i++ and ++i i++; // First use i, then add 1 to i ++i; // Add 1 before using i int i = 10, j, k; j = i++; // j = 10, i = 11 k = ++i; // k = 12, i = 12

Decrementing When we want to count down (instead of up) we decrement a variable E.g., i = i - 1; Thus, the decrement operators were created: i-- and --i i--; // First use i, then subtract 1 ++i; // Subtract 1 before using i int i = 10, j, k; j = i--; // j = 10, i = 9 k = --i; // k = 8, i = 8

Increment/Decrement ExpressionAlternative i++;i = i + i; ++i;i = i + 1; i--;i = i – 1; --i;i = i – 1; j = i++;j = i; i = i + 1; j = ++i;i = i + 1; j = i; j = i--;j = i; i = i - 1; j = --i;i = i – 1; j = i;

Exercise Write a program that prints the numbers from 100 down to 1 using a loop

Solution 1: For // Countdown, By Tami Meredith public class countdown { public static void main (String[] args) { int val; for (val = 100; val > 0; val--) { System.out.println(val); } // end for } // end main() } // end class countdown

Solution: While // Countdown, By Tami Meredith public class countdown { public static void main (String[] args) { int val = 100; while (val > 0) { System.out.println(val); val--; } // end while } // end main() } // end class countdown

Exercise Write a program that prints the letters of your name, one at a time, using a loop. Remember, charAt(i) gets the letters of a string at index i length() returns the length of a string Strings are indexed from 0 to length-1 Note: You are going to need to be very comfortable with the String class (Figure 2.5, pg 86)!

Solution // Letters One by One, By Tami Meredith public class onebyone { public static void main (String[] args) { String name = "Tami Meredith"; int index, len = name.length(); for (index = 0; index < len; index++) { System.out.println(name.charAt(index)); } // end for } // end main() } // end class onebyone

Now you understand...

STAY TUNED LOTS MORE TO COME!

To Do Go to the lab and complete today's assignment Read Chapter 5 (For next class), make notes, write down your questions and bring them next week If you want to work at home, install JDK 1.7 and JCreator LE Read Chapters (Material from previous classes) and Chapter 4 (Material from this class), if you have not already