Nesting Loops (That’s loops inside of loops. Why not?)

Slides:



Advertisements
Similar presentations
Loops –Do while Do While Reading for this Lecture, L&L, 5.7.
Advertisements

Standard Algorithms Find the highest number. ! Your name and today’s date ! Find the maximum Dim numbers(20) As Integer.
Craps. /* * file : Craps.java * file : Craps.java * author: george j. grevera, ph.d. * author: george j. grevera, ph.d. * desc. : program to simulate.
Fundamental Programming Structures in Java: Control Flow, Arrays and Vectors.
An introduction to arrays
Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. It is common to use two nested loops when filling or searching: for.
Today’s topics: I/O (Input/Output). Scribbler Inputs & Outputs  What are the Scribbler’s inputs and outputs?  reset button  motors/wheel  light sensor.
Mock test review Revision of Activity Diagrams for 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.
Introduction to Computers and Programming for Loops  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course. Introduction to.
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.
Copyright 2006 by Pearson Education 1 reading: 4.1 Cumulative sum.
FIT Objectives By the end of this lecture, students should: understand iteration statements understand the differences of for and while understand.
COMP 14 Introduction to Programming Miguel A. Otaduy May 20, 2004.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Repetition Statements.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 6 Repetition Statements.
COMP 110 Introduction to Programming Mr. Joshua Stough September 24, 2007.
Control Structures II. Why is Repetition Needed? There are many situations in which the same statements need to be executed several times. Example: Formulas.
Chapter 4: Control Structures II
JAVA Control Structures: Repetition. Objectives Be able to use a loop to implement a repetitive algorithm Practice, Practice, Practice... Reinforce the.
Lecture 10 Instructor: Craig Duckett. Assignment 2 Revision TONIGHT DUE TONIGHT Wednesday, August 5 th Assignment 3 NEXT DUE NEXT Monday, August 10 th.
CSC 1051 M.A. Papalaskari, Villanova University Repetition CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing.
Java Programming: From the Ground Up
Week 2 - Wednesday.  What did we talk about last time?  Data representation  Binary numbers  Types  int  boolean  double  char  String.
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
Chapter 5 Loops.
October 28, 2015ICS102: For Loop1 The for-loop and Nested loops.
Copyright © 2012 Pearson Education, Inc. Chapter 6 More Conditionals and Loops Java Software Solutions Foundations of Program Design Seventh Edition John.
Control Structures II Repetition (Loops). Why Is Repetition Needed? How can you solve the following problem: What is the sum of all the numbers from 1.
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 4: Control Structures II
Loops (cont.). Loop Statements  while statement  do statement  for statement while ( condition ) statement; do { statement list; } while ( condition.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
Chapter 5 Conditionals and Loops. © 2004 Pearson Addison-Wesley. All rights reserved5-2 The switch Statement The switch statement provides another way.
Topics Logical Operators (Chapter 5) Comparing Data (Chapter 5) The conditional operator The switch Statement The for loop Nested Loops.
More loops while and do-while. Recall the for loop in general for (initialization; boolean_expression; update) { }
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
CONTROL STATEMENTS LOOPS. WHY IS REPETITION NEEDED?  There are many situations in which the same statements need to be executed several times.  Example:
CSCI 1226 FALL 2015 MIDTERM #1 REVIEWS.  Types of computers:  Personal computers  Embedded systems  Servers  Hardware:  I/O devices: mice, keyboards,
Programming Fundamentals I Java Programming Spring 2009 Instructor: Xuan Tung Hoang TA: Tran Minh Trung Lab 03.
Application development with Java Lecture 6 Rina Zviel-Girshin.
CONTROL STRUCTURE Chapter 3. CONTROL STRUCTURES ONE-WAY SELECTION Syntax: if (expression) statement Expression referred to as decision maker. Statement.
REPETITION MTS3033 OBJECT ORIENTED PROGRAMMING 1.
UFCFY5-30-1Multimedia Studio Scripting for Interactive Media Further Structures for Branching and Looping.
When constructing a two-dimensional array, specify how many rows and columns are needed: final int ROWS = 3; final int COLUMNS = 3; String[][] board =
Feedback  Lab2, Hw1  Groups  Group Project Requirements.
Lecture 7 – Repetition (Loop) FTMK, UTeM – Sem /2014.
JAVA PROGRAMMING Control Flow. Jeroo: Finish Activities 1-7 Finish InputTest program w/changes.
Lesson 7 Iteration Structures. Iteration is the third control structure we will explore. Iteration simply means to do something repeatedly. All iteration.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
A 2-D Array is a structure that storage space both vertically and horizontally. Thus, the array has both rows and columns. 2-D Arrays are used to create.
Switch statement.
CSC111 Quick Revision.
TemperatureConversion
Chapter 6 More Conditionals and Loops
Boolean expressions Conditional statements and expressions
CiS 260: App Dev I Chapter 4: Control Structures II.
Repetition-Sentinel,Flag Loop/Do_While
Chapter 5: Control Structures II
Control Statement Examples
Control Structure Senior Lecturer
CSS161: Fundamentals of Computing
Topic 1: Problem Solving
Module 4 Loops and Repetition 2/1/2019 CSE 1321 Module 4.
The keyboard is the standard input device.
Outline Boolean Expressions The if Statement Comparing Data
Repetition CSC 1051 – Data Structures and Algorithms I Course website:
Control Statements:.
Presentation transcript:

Nesting Loops (That’s loops inside of loops. Why not?)

Consider a line of asterisks: *********************... How can I do this in a program? row column

Consider a line of asterisks: *************… final int numberCols = 20; for (int col=1; col<=numberCols; col++) { System.out.print( "*" ); }System.out.println();

Say I want rows and rows of this line. **************…**************…**************…... final int numberRows = 5; final int numberCols = 20;

//output all of the lines for (int row=1; row<=numberRows; row++) { //output one line //output one line for (int col=1; col<=numberCols; col++) { for (int col=1; col<=numberCols; col++) { System.out.print( "*" ); System.out.print( "*" ); } System.out.println(); System.out.println();}

Say instead we want: * * * * …... Note space between asterisks.

for (int row=1; row<=numberRows; row++) { for (int col=1; col<=numberCols; col++) { for (int col=1; col<=numberCols; col++) { System.out.print( "* " ); System.out.print( "* " ); } System.out.println(); System.out.println();} space

Say we want a checkerboard: for (int row=1; row<=numberRows; row++) { for (int col=1; col<=numberCols; col++) { for (int col=1; col<=numberCols; col++) { System.out.print( "* " ); System.out.print( "* " ); } System.out.println(); System.out.println();}

for (int row=1; row<=numberRows; row++) { for (int col=1; col<=numberCols; col++) { for (int col=1; col<=numberCols; col++) { System.out.print( "* " ); System.out.print( "* " ); } System.out.println(); System.out.println();} Can mod (%) help us somehow? Say we want a checkerboard:

final int width = 8; //output all of the rows for (int r=1; r<=width; r++) { //output all of the columns within the row //output all of the columns within the row for (int c=1; c<=width/2; c++) { for (int c=1; c<=width/2; c++) { if ( (r%2) == 0 ) { System.out.print( " *" ); System.out.print( " *" ); } else { System.out.print( "* " ); System.out.print( "* " );} } System.out.println(); System.out.println();}

final int width = 8; //output all of the rows for (int r=1; r<=width; r++) { //output all of the columns within the row //output all of the columns within the row for (int c=1; c<=width/2; c++) { for (int c=1; c<=width/2; c++) { if ( (r%2) == 0 )System.out.print( " *" ); elseSystem.out.print( "* " ); } System.out.println(); System.out.println();}

final int width = 8; //output all of the rows for (int r=1; r<=width; r++) { //output all of the columns within the row //output all of the columns within the row for (int c=1; c<=width/2; c++) { for (int c=1; c<=width/2; c++) { if ( (r%2) == 0 ) System.out.print( " *" ); System.out.print( " *" );else } System.out.println(); System.out.println();} What are the possible values of r % 2? How many values are possible with r % 2? What data type has exactly this many values?

final int width = 8; boolean bumpOver = false; //output all of the rows for (int r=1; r<=width; r++) { //output all of the columns within the row //output all of the columns within the row for (int c=1; c<=width/2; c++) { for (int c=1; c<=width/2; c++) { if (bumpOver) System.out.print( " *" ); System.out.print( " *" );else } System.out.println(); System.out.println(); bumpOver = !bumpOver; bumpOver = !bumpOver;} Use a boolean instead of mod.

final int width = 8; boolean bumpOver = false; //output all of the rows for (int r=1; r<=width; r++) { //output all of the columns within the row //output all of the columns within the row for (int c=1; c<=width/2; c++) { for (int c=1; c<=width/2; c++) { if (bumpOver) System.out.print( " *" ); System.out.print( " *" );else } System.out.println(); System.out.println(); bumpOver = !bumpOver; bumpOver = !bumpOver;} Why width/2?

/* * file : CheckerBoard.java * file : CheckerBoard.java * author: george j. grevera, ph.d. * author: george j. grevera, ph.d. * desc. : program to output a checkerboard (problem 4.1, p. 74. * desc. : program to output a checkerboard (problem 4.1, p. 74. */ */ public class CheckerBoard { public static void main ( String[] s ) { public static void main ( String[] s ) { //declare variables & initialize i/o //ouput startup message System.out.println( "here's the checkerboard:\n" ); final int width = 8; boolean bumpOver = false; //output all of the rows for (int r=1; r<=width; r++) { //output all of the columns within the row //output all of the columns within the row for (int c=1; c<=width/2; c++) { for (int c=1; c<=width/2; c++) { if (bumpOver) System.out.print( " *" ); System.out.print( " *" );else } System.out.println(); System.out.println(); bumpOver = !bumpOver; bumpOver = !bumpOver;} //finish up System.out.println( "\n\nadios" ); }} The complete program.

Let’s “draw” a rectangle/box.

Generate a rectangle. ********** * * * *<- rows * * ********** ^ cols

Generate a rectangle. ********** * * * *<- rows * * ********** ^ cols Note that the first and last lines are the same; also note that all of the middle lines are the same.

Generate a rectangle. ********** * * * *<-rows * * ********** ^ cols So our algorithm is: 1. Output the first line. 2. Output the intervening lines. 3. Output the last line (just like the first).

Generate a rectangle. ********** * * * *<-rows * * ********** ^ cols //Output the first line. for (int c=0; c<cols; c++) { System.out.print( "*" ); }System.out.println();

Generate a rectangle. ********** * * * *<-rows * * ********** ^ cols //Output the intervening lines. for (int r=0; r<rows-2; r++) { System.out.print( "*" ); for (int c=0; c<cols-2; c++) { System.out.print( " " ); } System.out.println( "*" ); }

Generate a rectangle. ********** * * * *<-rows * * ********** ^ cols //Output the last line (just like the first). for (int c=0; c<cols; c++) { System.out.print( "*" ); }System.out.println();

final int rows = 10;//define number of rows final int cols = 20;//define number of columns //Output the first line (just like the last). for (int c=0; c<cols; c++) { System.out.print( "*" ); }System.out.println(); //Output the intervening lines. for (int r=0; r<rows-2; r++) { System.out.print( "*" ); for (int c=0; c<cols-2; c++) { System.out.print( " " ); } System.out.println( "*" ); } //Output the last line (just like the first). for (int c=0; c<cols; c++) { System.out.print( "*" ); }System.out.println();

Repeatedly prompt until user enters something valid. final intminimum = 0; intinputValue = minimum-1; while (inputValue < minimum) { inputValue = in.nextInt(); }

Repeatedly prompt until user enters something valid. final intminimum = 0; intinputValue = minimum-1; booleaninvalid = true; while (invalid) { inputValue = in.nextInt(); if (inputValue >= minimum) { invalid = false; }}

Repeatedly prompt until user enters something valid. final intminimum = 0; intinputValue = minimum-1; booleanvalid = false; while (!valid) { inputValue = in.nextInt(); if (inputValue >= minimum) { valid = true; }}

Shakespearean insults p. 75 of Per Brinch Hansen’s Java book (if time permits). p. 75 of Per Brinch Hansen’s Java book (if time permits). Thou goatish, hasty-witted ratsbane! Thou goatish, hasty-witted ratsbane! Thou loggerheaded, doghearted dewberry! Thou loggerheaded, doghearted dewberry! Thou churlish, tickle-brained pigeon-egg! Thou churlish, tickle-brained pigeon-egg! Our task is to prompt the user for the number of these to output, and then output that number of insults. Our task is to prompt the user for the number of these to output, and then output that number of insults.

Shakespearean insults Thougoatish,hasty-wittedratsbane! Thougoatish,hasty-wittedratsbane! Thouloggerheaded,doghearteddewberry! Thouloggerheaded,doghearteddewberry! Thouchurlish,tickle-brainedpigeon-egg! Thouchurlish,tickle-brainedpigeon-egg! always pick one

Shakespearean insults Column 1 Column 2 Column 3 artlessbeetle-headedbarnacle bootlessclay-brainedcoxcomb churlishdoghearteddewberry dissemblingfly-bittenfoot-licker erranthasty-wittedgudgeon fobbingidle-headedjolthead goatishrough-hewnlout impertinentswag-belliedminnow jarringtickle-brainedpigeon-egg loggerheadedweather-bittenratsbane

Shakespearean insults algorithm 1. Prompt user for number of insults. 2. Read in the number of insults. 3. Output that number of insults. 1. Output “Thou ”. 2. Pick and output a word from column Output “,”. 4. Pick and output a word from column Output “ ”. 6. Pick and output a word from column Output “!” w/ newline.

Shakespearean insults algorithm //Prompt user for number of insults. //Read in the number of insults. //Output that number of insults. //Output “Thou ”. //Pick and output a word from column 1. //Output “,”. //Pick and output a word from column 2. //Output “ ”. //Pick and output a word from column 3. //Output “!” w/ newline.

Shakespearean insults algorithm Scanner in = new Scanner( System.in ); //Prompt user for number of insults. System.out.print( "Enter the number of insults: " ); //Read in the number of insults. final int count = in.nextInt();

Shakespearean insults algorithm //Output that number of insults. for (int i=0; i<count; i++) { //Output “Thou ”. //Pick and output a word from column 1. //Output “, ”. //Pick and output a word from column 2. //Output “ ”. //Pick and output a word from column 3. //Output “!” w/ newline. }

//Output that number of insults. for (int i=0; i<count; i++) { //Output “Thou ”. System.out.print( “Thou ” ); //Pick and output a word from column 1. ? //Output “, ”. System.out.print( “, ” ); //Pick and output a word from column 2. ? //Output “ ”. //Pick and output a word from column 3. ? //Output “!” w/ newline. System.out.println( “!” ); }

//Output that number of insults. Random rnd = new Random(); for (int i=0; i<count; i++) { System.out.print( “Thou ” ); //Pick and output a word from column 1. ? System.out.print( “, ” ); //Pick and output a word from column 2. ? System.out.print( “ ” ); //Pick and output a word from column 3. ? System.out.print ln ( “!” ); }

//Output that number of insults. Random rnd = new Random(); for (int i=0; i<count; i++) { System.out.print( “Thou ” ); //Pick and output a word from column 1. switch (rnd.nextInt(10)+1) { case 1:System.out.print( “artless”) break; case 2:System.out.print( “bootless”); break;… default:System.out.print( “loggerheaded”); break; } //end switch

//Output that number of insults. Random rnd = new Random(); for (int i=0; i<count; i++) { System.out.print( “Thou ” ); //Pick and output a word from column 1. switch (rnd.nextInt(10)+1) { case 1:System.out.print( “artless”)break; case 2:System.out.print( “bootless”);break; … default:System.out.print( “loggerheaded”);break; } //end switch System.out.print( “, ” ); //Pick and output a word from column 2. ? System.out.print( “ ” ); //Pick and output a word from column 3. ? System.out.println( “!” ); }

//Pick and output a word from column 1. switch (rnd.nextInt(10)+1) { case 1:System.out.print( “artless”)break; case 2:System.out.print( “bootless”);break; … default:System.out.print( “loggerheaded”);break; } //end switch System.out.print( “, ” ); //Pick and output a word from column 2. switch (rnd.nextInt(10)+1) { case 1:System.out.print( “beetle-headed”)break; case 2:System.out.print( “clay-brained”);break; … default:System.out.print( “weather-bitten”);break; } //end switch System.out.print( “ ” ); //Pick and output a word from column 3. …

//Output that number of insults. Random rnd = new Random(); for (int i=0; i<count; i++) { System.out.print( “Thou ” ); //Pick and output a word from column 1. switch (rnd.nextInt(10)+1) { case 1:System.out.print( “artless”)break; case 2:System.out.print( “bootless”);break; … default:System.out.print( “loggerheaded”);break; } //end switch System.out.print( “, ” ); //Pick and output a word from column 2. switch (rnd.nextInt(10)+1) { case 1:System.out.print( “beetle-headed”)break; case 2:System.out.print( “clay-brained”);break; … default:System.out.print( “weather-bitten”);break; } //end switch System.out.print( “ ” ); //Pick and output a word from column 3. ? System.out.println( “!” ); } And similarly here.