CSC 1051 – Data Structures and Algorithms I

Slides:



Advertisements
Similar presentations
Copyright © 2012 Pearson Education, Inc. Chapter 6 More Conditionals and Loops Java Software Solutions Foundations of Program Design Seventh Edition John.
Advertisements

INF 523Q Chapter 3: Program Statements (Examples).
Loops – While, Do, For Repetition Statements Introduction to Arrays
Java Program Statements Selim Aksoy Bilkent University Department of Computer Engineering
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
CSC 1051 M.A. Papalaskari, Villanova University Repetition CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing.
Chapter 5 Conditionals and Loops. © 2004 Pearson Addison-Wesley. All rights reserved5-2 Conditionals and Loops Now we will examine programming statements.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
© 2006 Pearson Education Chapter 3 Part 2 More about Strings and Conditional Statements Loops (for and while) 1.
Copyright © 2014 Pearson Education, Inc. Chapter 6 More Conditionals and Loops Java Software Solutions Foundations of Program Design 8 th Edition John.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
Chapter 5 Loops.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
Copyright © 2012 Pearson Education, Inc. Chapter 6 More Conditionals and Loops Java Software Solutions Foundations of Program Design Seventh Edition John.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
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 6. else-if & switch Copyright © 2012 Pearson Education, Inc.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
Chapter 5 – Part 3 Conditionals and Loops. © 2004 Pearson Addison-Wesley. All rights reserved5-2 Outline The if Statement and Conditions Other Conditional.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
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.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
CSC 1051 M.A. Papalaskari, Villanova University Algorithms Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
CSC 1051 – Algorithms and Data Structures I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
CSC 1051 M.A. Papalaskari, Villanova University Repetition CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing.
Loops Copyright © 2012 Pearson Education, Inc.. Conditionals and Loops (Chapter 5) So far, we’ve looked at: –making decisions with if –how to compare.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
1 More about Flow of Control. Topics Debugging Logical Operators (Chapter 5) Comparing Data (Chapter 5) The conditional operator The switch Statement.
Feedback  Lab2, Hw1  Groups  Group Project Requirements.
Programming in Java (COP 2250) Lecture 12 & 13 Chengyong Yang Fall, 2005.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
Chapter 5 – Part 3 Conditionals and Loops. © 2004 Pearson Addison-Wesley. All rights reserved2/19 Outline The if Statement and Conditions Other Conditional.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
© 2006 Pearson Education Chapter 3 Part 2 More about Strings and Conditional Statements Loops (for and while) 1.
CSC 1051 – Data Structures and Algorithms I
CSC 1051 – Data Structures and Algorithms I
Chapter 6 More Conditionals and Loops
CSC 1051 – Data Structures and Algorithms I
Chapter 6 More Conditionals and Loops
More Conditionals and Loops
The switch Statement The switch statement provides another way to decide which statement to execute next The switch statement evaluates an expression,
Outline The switch Statement The Conditional Operator The do Statement
Chapter 6 More Conditionals and Loops
Debugging October 3, 2007 ComS 207: Programming I (in Java)
Outline Altering flow of control Boolean expressions
Chapter 6 More Conditionals and Loops
Chapter 6 More Conditionals and Loops
Module 4 Loops and Repetition 2/1/2019 CSE 1321 Module 4.
Debugging October 4, 2006 ComS 207: Programming I (in Java)
Repetition Statements
CSC 1051 – Data Structures and Algorithms I
Outline Boolean Expressions The if Statement Comparing Data
CSCI 1100/1202 February 6, 2002.
‘do’ and ‘for’ loops October 1, 2007 ComS 207: Programming I (in Java)
‘do’ and ‘for’ loops October 2, 2006 ComS 207: Programming I (in Java)
Repetition CSC 1051 – Data Structures and Algorithms I Course website:
Module 4 Loops and Repetition 9/19/2019 CSE 1321 Module 4.
Presentation transcript:

CSC 1051 – Data Structures and Algorithms I Repetition Statements CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website: www.csc.villanova.edu/~map/1051/ Some slides in this presentation are adapted from the slides accompanying Java Software Solutions by Lewis & Loftus CSC 1051 M.A. Papalaskari, Villanova University

Repetition structures in Java while loop: int count = 0; while (count < 5) { count++; System.out.println (count); } Other repetition structures (Chapter 6 in text) the do loop the for loop CSC 1051 M.A. Papalaskari, Villanova University

The while and do loops are similar. statement true false condition evaluated while Loop true condition evaluated statement false do Loop CSC 1051 M.A. Papalaskari, Villanova University

for: a loop with built in “counter” initialization condition evaluated false statement true increment CSC 1051 M.A. Papalaskari, Villanova University

An example of a do loop: int count = 0; do { count++; System.out.println (count); } while (count < 5); The body of a do loop executes at least once CSC 1051 M.A. Papalaskari, Villanova University

The do Statement A do statement has the following syntax: { statement-list; } while (condition); //end do The statement-list is executed once initially, and then the condition is evaluated The statement is executed repeatedly until the condition becomes false See example GradeReportLoopy.java CSC 1051 M.A. Papalaskari, Villanova University

Another example of a do loop: //******************************************************************** // GradeReportLoopy.java Author: Papalaskari //******************************************************************** import java.util.Scanner; public class GradeReportLoopy { //----------------------------------------------------------------- // Reads a grades from the user and prints comments accordingly. //----------------------------------------------------------------- public static void main (String[] args) { int grade; String ans; Scanner scan = new Scanner (System.in); do { System.out.print ("Enter a numeric grade (0 to 100): "); grade = scan.nextInt(); printReport(grade); System.out.print ("Would you like to do another grade report? "); ans = scan.next(); } while (ans.charAt(0) == 'y' || ans.charAt(0) == 'Y') ; } continue CSC 1051 M.A. Papalaskari, Villanova University

public static void printReport (int grade) { int category = grade / 10; System.out.print ("That grade is "); switch (category) { case 10: System.out.println ("a perfect score. Well done."); break; case 9: System.out.println ("great!"); case 8: System.out.println ("well above average. Excellent."); break; case 7: System.out.println ("above average. Nice job."); break; case 6 System.out.println ("below average."); break; default: System.out.println ("not passing."); } } } CSC 1051 M.A. Papalaskari, Villanova University

Another example of a do loop: //******************************************************************** // GradeReportLoopy.java Author: Papalaskari //******************************************************************** import java.util.Scanner; public class GradeReportLoopy { //----------------------------------------------------------------- // Reads a grades from the user and prints comments accordingly. //----------------------------------------------------------------- public static void main (String[] args) { int grade; String ans; Scanner scan = new Scanner (System.in); do { System.out.print ("Enter a numeric grade (0 to 100): "); grade = scan.nextInt(); printReport(grade); System.out.print ("Would you like to do another grade report? "); ans = scan.next(); } while (ans.charAt(0) == 'y' || ans.charAt(0) == 'Y') ; } Output Enter a numeric grade (0 to 100): 84 That grade is well above average. Excellent. Would you like to do another grade report? yes Enter a numeric grade (0 to 100): 99 That grade is great! well above average. Excellent. Would you like to do another grade report? Y Enter a numeric grade (0 to 100): 100 That grade is a perfect score. Well done. Would you like to do another grade report? no CSC 1051 M.A. Papalaskari, Villanova University

Try this: Write a do loop to print the even numbers from 2 to 100. Write a loop to input a grade, ensuring that it is in the range 1-100 (ask them to try again and again until they input a number in that range)   CSC 1051 M.A. Papalaskari, Villanova University

The for Statement A for loop is functionally equivalent to the following while loop structure: initialization; while ( condition ) { statement; increment; } CSC 1051 M.A. Papalaskari, Villanova University

The for Statement - Example A while loop: int count=1; while (count <= 5) { System.out.println (count); count++; } Equivalent for loop: for (int count=1; count <= 5; count++) System.out.println (count); CSC 1051 M.A. Papalaskari, Villanova University

The for Statement 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 CSC 1051 M.A. Papalaskari, Villanova University

The for Statement 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 (int count=1; count <= 5; count++) System.out.println (count); The increment portion is executed at the end of each iteration CSC 1051 M.A. Papalaskari, Villanova University

Try this: Write a for loop to print the even numbers from 2 to 100. Write a method that uses a for loop to print n stars, where n is an integer parameter Write a method that uses a for loop to print a square of n by n stars, where n is an integer parameter. Here is an example of the 3 by 3: * * * * * * * * *   CSC 1051 M.A. Papalaskari, Villanova University

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 that can be calculated or determined in advance See Stars.java CSC 1051 M.A. Papalaskari, Villanova University

//******************************************************************** // Stars.java Author: Lewis/Loftus // // Demonstrates the use of nested for loops. public class Stars { //----------------------------------------------------------------- // Prints a triangle shape using asterisk (star) characters. public static void main (String[] args) final int MAX_ROWS = 10; for (int row = 1; row <= MAX_ROWS; row++) for (int star = 1; star <= row; star++) System.out.print ("*"); System.out.println(); } CSC 1051 M.A. Papalaskari, Villanova University

Output * ** *** **** ***** ****** ******* ******** ********* ********** //******************************************************************** // Stars.java Author: Lewis/Loftus // // Demonstrates the use of nested for loops. public class Stars { //----------------------------------------------------------------- // Prints a triangle shape using asterisk (star) characters. public static void main (String[] args) final int MAX_ROWS = 10; for (int row = 1; row <= MAX_ROWS; row++) for (int star = 1; star <= row; star++) System.out.print ("*"); System.out.println(); } CSC 1051 M.A. Papalaskari, Villanova University

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 CSC 1051 M.A. Papalaskari, Villanova University

More examples using for loops Conditionals and loops enhance our ability to generate interesting graphics See Bullseye.java See BullseyePanel.java See Boxes.java See BoxesPanel.java CSC 1051 M.A. Papalaskari, Villanova University

//******************************************************************** // Bullseye.java Author: Lewis/Loftus // // Demonstrates the use of loops to draw. import javax.swing.JFrame; public class Bullseye { //----------------------------------------------------------------- // Creates the main frame of the program. public static void main (String[] args) JFrame frame = new JFrame ("Bullseye"); frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); BullseyePanel panel = new BullseyePanel(); frame.getContentPane().add(panel); frame.pack(); frame.setVisible(true); } CSC 1051 M.A. Papalaskari, Villanova University

//******************************************************************** // Bullseye.java Author: Lewis/Loftus // // Demonstrates the use of loops to draw. import javax.swing.JFrame; public class Bullseye { //----------------------------------------------------------------- // Creates the main frame of the program. public static void main (String[] args) JFrame frame = new JFrame ("Bullseye"); frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); BullseyePanel panel = new BullseyePanel(); frame.getContentPane().add(panel); frame.pack(); frame.setVisible(true); } CSC 1051 M.A. Papalaskari, Villanova University

//******************************************************************** // BullseyePanel.java Author: Lewis/Loftus // // Demonstrates the use of conditionals and loops to guide drawing. import javax.swing.JPanel; import java.awt.*; public class BullseyePanel extends JPanel { private final int MAX_WIDTH = 300, NUM_RINGS = 5, RING_WIDTH = 25; //----------------------------------------------------------------- // Sets up the bullseye panel. public BullseyePanel () setBackground (Color.cyan); setPreferredSize (new Dimension(300,300)); } continue CSC 1051 M.A. Papalaskari, Villanova University

//----------------------------------------------------------------- continue //----------------------------------------------------------------- // Paints a bullseye target. public void paintComponent (Graphics page) { super.paintComponent (page); int x = 0, y = 0, diameter = MAX_WIDTH; page.setColor (Color.white); for (int count = 0; count < NUM_RINGS; count++) if (page.getColor() == Color.black) // alternate colors else page.setColor (Color.black); page.fillOval (x, y, diameter, diameter); diameter -= (2 * RING_WIDTH); x += RING_WIDTH; y += RING_WIDTH; } // Draw the red bullseye in the center page.setColor (Color.red); CSC 1051 M.A. Papalaskari, Villanova University

//******************************************************************** // Boxes.java Author: Lewis/Loftus // // Demonstrates the use of loops to draw. import javax.swing.JFrame; public class Boxes { //----------------------------------------------------------------- // Creates the main frame of the program. public static void main (String[] args) JFrame frame = new JFrame ("Boxes"); frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); BoxesPanel panel = new BoxesPanel(); frame.getContentPane().add(panel); frame.pack(); frame.setVisible(true); } CSC 1051 M.A. Papalaskari, Villanova University

//******************************************************************** // Boxes.java Author: Lewis/Loftus // // Demonstrates the use of loops to draw. import javax.swing.JFrame; public class Boxes { //----------------------------------------------------------------- // Creates the main frame of the program. public static void main (String[] args) JFrame frame = new JFrame ("Boxes"); frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); BoxesPanel panel = new BoxesPanel(); frame.getContentPane().add(panel); frame.pack(); frame.setVisible(true); } CSC 1051 M.A. Papalaskari, Villanova University

//******************************************************************** // BoxesPanel.java Author: Lewis/Loftus // // Demonstrates the use of conditionals and loops to guide drawing. import javax.swing.JPanel; import java.awt.*; import java.util.Random; public class BoxesPanel extends JPanel { private final int NUM_BOXES = 50, THICKNESS = 5, MAX_SIDE = 50; private final int MAX_X = 350, MAX_Y = 250; private Random generator; //----------------------------------------------------------------- // Sets up the drawing panel. public BoxesPanel () generator = new Random(); setBackground (Color.black); setPreferredSize (new Dimension(400, 300)); } continue CSC 1051 M.A. Papalaskari, Villanova University

//----------------------------------------------------------------- continue //----------------------------------------------------------------- // Paints boxes of random width and height in a random location. // Narrow or short boxes are highlighted with a fill color. public void paintComponent(Graphics page) { super.paintComponent (page); int x, y, width, height; for (int count = 0; count < NUM_BOXES; count++) x = generator.nextInt(MAX_X) + 1; y = generator.nextInt(MAX_Y) + 1; width = generator.nextInt(MAX_SIDE) + 1; height = generator.nextInt(MAX_SIDE) + 1; CSC 1051 M.A. Papalaskari, Villanova University

if (width <= THICKNESS) // check for narrow box { continue if (width <= THICKNESS) // check for narrow box { page.setColor (Color.yellow); page.fillRect (x, y, width, height); } else if (height <= THICKNESS) // check for short box page.setColor (Color.green); page.setColor (Color.white); page.drawRect (x, y, width, height); CSC 1051 M.A. Papalaskari, Villanova University

Homework Review Sections 6.3, 6.4, and 6.5 Always do all self-review exercises when you review Exercises EX6.1 - 6.17 (important to get lots of practice with writing loops!) Think about the following exercise from Lab 4 and determine which is the best kind of loop for each of the cases: We need to write a program that finds the largest of some numbers input through the keyboard. Here are some questions: a) Do we know in advance how many numbers there will be? b) Do we want to prompt for each number? c) If we do not prompt for each number, how do we signal the end of input? Look at some additional examples of programs from the text: ReverseNumber.java Multiples.java Some slides in this presentation are adapted from the slides accompanying Java Software Solutions by Lewis & Loftus CSC 1051 M.A. Papalaskari, Villanova University

Another example of do loop: Sample Run Enter a positive integer: 2896 That number reversed is 6982 Reverse a number See ReverseNumber.java This can be done numerically or by viewing the number as a String – the example in the textbook does it numerically. Using strings it is a bit easier (EX 6.17). Try it! CSC 1051 M.A. Papalaskari, Villanova University

//******************************************************************** // ReverseNumber.java Author: Lewis/Loftus // // Demonstrates the use of a do loop. import java.util.Scanner; public class ReverseNumber { //----------------------------------------------------------------- // Reverses the digits of an integer mathematically. public static void main (String[] args) int number, lastDigit, reverse = 0; Scanner scan = new Scanner (System.in); continue CSC 1051 M.A. Papalaskari, Villanova University

System.out.print ("Enter a positive integer: "); continue System.out.print ("Enter a positive integer: "); number = scan.nextInt(); do { lastDigit = number % 10; reverse = (reverse * 10) + lastDigit; number = number / 10; } while (number > 0); System.out.println ("That number reversed is " + reverse); CSC 1051 M.A. Papalaskari, Villanova University

Sample Run Enter a positive integer: 2896 That number reversed is 6982 continue System.out.print ("Enter a positive integer: "); number = scan.nextInt(); do { lastDigit = number % 10; reverse = (reverse * 10) + lastDigit; number = number / 10; } while (number > 0); System.out.println ("That number reversed is " + reverse); CSC 1051 M.A. Papalaskari, Villanova University

Another example of for loop: Print multiples of a number up to a limit. See Multiples.java Can you make it print 10 per line? Can you change it so that it prints them backwards? Sample Run Enter a positive value: 7 Enter an upper limit: 400 The multiples of 7 between 7 and 400 (inclusive) are: 7 14 21 28 35 42 49 56 63 70 77 84 91 98 105 112 119 126 133 140 147 154 161 168 175 182 189 196 203 210 217 224 231 238 245 252 259 266 273 280 287 294 301 308 315 322 329 336 343 350 357 364 371 378 385 392 399 CSC 1051 M.A. Papalaskari, Villanova University

//******************************************************************** // Multiples.java Author: Lewis/Loftus // // Demonstrates the use of a for loop. import java.util.Scanner; public class Multiples { //----------------------------------------------------------------- // Prints multiples of a user-specified number up to a user- // specified limit. public static void main (String[] args) final int PER_LINE = 5; int value, limit, mult, count = 0; Scanner scan = new Scanner (System.in); System.out.print ("Enter a positive value: "); value = scan.nextInt(); continue CSC 1051 M.A. Papalaskari, Villanova University

System.out.print ("Enter an upper limit: "); limit = scan.nextInt(); continue System.out.print ("Enter an upper limit: "); limit = scan.nextInt(); System.out.println (); System.out.println ("The multiples of " + value + " between " + value + " and " + limit + " (inclusive) are:"); for (mult = value; mult <= limit; mult += value) { System.out.print (mult + "\t"); // Print a specific number of values per line of output count++; if (count % PER_LINE == 0) System.out.println(); } CSC 1051 M.A. Papalaskari, Villanova University