Repetition Statements

Slides:



Advertisements
Similar presentations
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.
Advertisements

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.
CS 106 Introduction to Computer Science I 02 / 12 / 2007 Instructor: Michael Eckmann.
Loops – While, Do, For Repetition Statements Introduction to Arrays
Loops Repeat after me …. Loops A loop is a control structure in which a statement or set of statements execute repeatedly How many times the statements.
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.
Loops Repetition Statements. Repetition statements allow us to execute a statement multiple times Often they are referred to as loops Like conditional.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
Lecture Review (If-else Statement) if-else statement has the following syntax: if ( condition ) { statement1; } else { statement2; } The condition.
ECE122 L9: While loops March 1, 2007 ECE 122 Engineering Problem Solving with Java Lecture 9 While Loops.
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 Coding 3 David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. Over & over again!
CSC 1051 M.A. Papalaskari, Villanova University Repetition CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing.
Chapter 6 Iteration.  Executes a block of code repeatedly  A condition controls how often the loop is executed while (condition) statement  Most commonly,
Chapter 5 Conditionals and Loops. © 2004 Pearson Addison-Wesley. All rights reserved5-2 Conditionals and Loops Now we will examine programming statements.
For Loops 1 Loops/Iteration Used to repeat an action Must have a STOP condition Three flavors - for, while, do/while Which loop to use? task with a specific.
© 2006 Pearson Education Chapter 3 Part 2 More about Strings and Conditional Statements Loops (for and while) 1.
Repetitive Structures BBS514 Structured Programming (Yapısal Programlama)1.
Flow Control in Java. Controlling which instruction to execute next Sequential  Similar to walking, one step after another Branching  Similar to a fork.
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.
Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
Flow Control in Java. Controlling which instruction to execute next Sequential  Similar to walking, one step after another Branching  Similar to a fork.
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
Repetition Statements while and do while loops
Chapter 5: 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.
Java iteration statements ● Iteration statements are statements which appear in the source code only once, but it execute many times. ● Such kind of statements.
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:
CONTROL STRUCTURE Chapter 3. CONTROL STRUCTURES ONE-WAY SELECTION Syntax: if (expression) statement Expression referred to as decision maker. Statement.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
CSE 501N Fall ’09 07: Iteration 17 September 2009 Nick Leidenfrost.
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.
Feedback  Lab2, Hw1  Groups  Group Project Requirements.
Structured Programming Structured Programming is writing a program in terms of only 3 basic control structures: sequence selection repetition We have already.
Lesson 7 Iteration Structures. Iteration is the third control structure we will explore. Iteration simply means to do something repeatedly. All iteration.
COS 312 DAY 5 Tony Gauvin. Ch 1 -2 Agenda Questions? Assignment 2 Posted – Due Feb 22 prior to class – Any issues? Assignment 3 will be posted soon Capstones.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
Java Fundamentals 4.
Chapter 4 Repetition Statements (loops)
Chapter 6 More Conditionals and Loops
Chapter 5: Control Structures II
Loop Structures.
Repetition-Counter control Loop
Repetition.
Chapter 5: Control Structures II
TK1114 Computer Programming
The switch Statement The switch statement provides another way to decide which statement to execute next The switch statement evaluates an expression,
While loops The while loop executes the statement over and over as long as the boolean expression is true. The expression is evaluated first, so the statement.
Flow Control in Java.
Chapter 6 More Conditionals and Loops
CSS161: Fundamentals of Computing
Outline Altering flow of control Boolean expressions
Control Statements Loops.
Module 4 Loops and Repetition 2/1/2019 CSE 1321 Module 4.
Control Statements Loops.
Outline Boolean Expressions The if Statement Comparing Data
Repetition CSC 1051 – Data Structures and Algorithms I Course website:
Presentation transcript:

Repetition Statements Repetition statements allow us to execute a statement multiple times Often they are referred to as loops Like conditional statements, they are controlled by boolean expressions Java has three kinds of repetition statements: while loop do loop for loop The programmer should choose the right kind of loop for the situation 4/29/2019 CS102 - Algorithms & Programming II

Java Repetition Statements while (condition) statement for ( init; condition; update) statement do statement while (condition); where statement is any Java statement condition is a boolean expression 4/29/2019 CS102 - Algorithms & Programming II

CS102 - Algorithms & Programming II while Statement The most general one of these loop statements is while. while ( boolean-expression ) statement where statement can be any statement including a compound statement, an if-statement, another loop statement, ... Statement is repeated as long as the condition (boolean-expression) is true. When the condition gets false, the statement is not executed anymore. If the condition never gets false  infinite loop If the condition gets immediately false  the loop will be repeated zero times. 4/29/2019 CS102 - Algorithms & Programming II

while Statement – Flow Diagram while ( condition ) statement true condition statement false 4/29/2019 CS102 - Algorithms & Programming II

while Statement – Counter Controlled Loop(1) Print 5 asterisk characters This loop will be repeated for 5 times (count: 0,1,...,4) count = 0; while ( count < 5 ) { System.out.println( “*”); count = count + 1; } System.out.println( “done”); * * * * * done 4/29/2019 CS102 - Algorithms & Programming II

while Statement – Counter Controlled Loop(2) Read & sum 5 values sum = 0; count = 0; while ( count < 5 ) { value = scan.nextInt(); sum = sum + value; count = count + 1; } System.out.println( “sum is ” + sum); 5 3 7 4 1 sum is 20 4/29/2019 CS102 - Algorithms & Programming II

Counter Controlled Loops Template of counter-controlled loops initialize counter while ( condition depending on counter) { other statements to be repeated update counter } 4/29/2019 CS102 - Algorithms & Programming II

CS102 - Algorithms & Programming II Infinite Loops The body of a while loop eventually must make the condition false If not, it is called an infinite loop, which will execute until the user interrupts the program in console applications use Ctrl-C to exit This is a common logical error You should always double check the logic of a program to ensure that your loops will terminate normally int count = 1; while (count <= 25){ System.out.println (count); count = count - 1; } 4/29/2019 CS102 - Algorithms & Programming II

CS102 - Algorithms & Programming II Infinite Loops (2) i = 1; while ( i != 50 ) { System.out.println( i); i = i + 2; } System.out.println( “done”); i = scan.nextInt(); while ( i != 1 ) { if ( i % 2 == 0) i = i / 2; else i = 3 * i + 1; Sometimes, it is difficult to check loop terminating condition. 4/29/2019 CS102 - Algorithms & Programming II

Sentinel-Controlled Loops What happens if we don’t know how many times a loop will run. Ex: a loop which reads the scores of the students in an exam and find the average of the scores; and we we don’t know the number of students. How are we going to stop the loops?  use a sentinel-value We choose a sentinel-value which can not be a score (e.g. –1) We read the scores until this sentinel-value has been entered. When this sentinel-value has been read, we stop the loop. 4/29/2019 CS102 - Algorithms & Programming II

Sentinel-Controlled Loops – Example(1) int sum = 0; int numOfStudents = 0; int ascore; double avg; System.out.print(“Enter a score (-1 to stop) >”); ascore = scan.nextInt(); while (ascore != -1) { sum = sum + ascore; numOfStudents = numOfStudents + 1; } avg = (double) sum / numOfStudents; System.out.println(“The number of students : “ + numOfStudents); System.out.println(“Average Score : “ + avg); 4/29/2019 CS102 - Algorithms & Programming II

CS102 - Algorithms & Programming II Example Program 1 // This program finds the factorial value of the given positive integer import java.util.Scanner; public class Factorial { public static void main(String[] args){ int num, factVal, counter; // Create a Scanner object Scanner scan = new Scanner(System.in); // Read the positive integer System.out.print("A Positive Integer: "); num = scan.nextInt(); // Find its factorial value counter = 2; factVal = 1; while (counter <= num) { factVal = factVal * counter; counter = counter + 1; } // Write the result System.out.println("Given Positive Integer: " + num); System.out.println("Its Factorial value : " + factVal); 4/29/2019 CS102 - Algorithms & Programming II

CS102 - Algorithms & Programming II for Statement Another loop statement in Java is for-statement. for-statement is more suitable for counter-controlled loops. for ( initialization ; condition ; increment ) statement which is equivalent to initialization ; while (condition ){ statement ; increment ; } 4/29/2019 CS102 - Algorithms & Programming II

for Statement – Flow Diagram initialization false condition true statement increment 4/29/2019 CS102 - Algorithms & Programming II

for statement -- Example int i; int i; int sum = 0; int sum = 0; for (i=1; i<=20; i++) i = 1; sum = sum + i; while (i<=20) { sum = sum + i; i++; } int i; int i; int sum = 0; int sum = 0; for (i=100; i>=1; i--) i = 100; sum = sum + i; while (i>=1) { 4/29/2019 CS102 - Algorithms & Programming II

for statement -- Example int i, j; int count=0; for (i=1, j=10; i<j; i++, j--)  count is 5 count++; i=1; j=10; for (; i<j; ) { i++; j--; } 4/29/2019 CS102 - Algorithms & Programming II

CS102 - Algorithms & Programming II do-while statement The third loop statement in Java is do-while statement. do statement while ( condition ) ; which is equivalent to while (condition ) 4/29/2019 CS102 - Algorithms & Programming II

do-while statement – Flow Diagram true condition false 4/29/2019 CS102 - Algorithms & Programming II

do-while statement -- Example int i=1; do { System.out.println(i); i++; } while (i<10); String s; System.out.print(“Enter a word > “); System.out.flush(); s = scan.nextLine(); System.out.println(s); } while (! s.equals(“quit”)); 4/29/2019 CS102 - Algorithms & Programming II

CS102 - Algorithms & Programming II Nested Loops If the body of a loop contains another loop, this is called as a nested loop. int sum=0; int i,j; for (i=1; i<=5; i++) for (j=1; j<=6; j++) sum=sum+1;  sum is 5*6=30 for (j=1; j<=i; j++) sum=sum+1;  sum is 1+2+3+4+5=15 4/29/2019 CS102 - Algorithms & Programming II

CS102 - Algorithms & Programming II Nested Loops – Example1 a right angled triangle (n lines, ith line contains i stars) * for (i=1; i<=n; i++) { // for each line ** for (j=1; j<=i; j++) *** System.out.print(“*”); . System.out.println(“”); . } *** .. * 4/29/2019 CS102 - Algorithms & Programming II

CS102 - Algorithms & Programming II Nested Loops – Example2 a triangle shape (1st line contains 1 star, 2nd line contains 3 star,..., nth line contains 2n-1 stars) * for (i=1; i<=n; i++) { // for each line *** for (j=1; j<=(n-i); j++) ***** System.out.print(“ ”); . for (j=1; j<=(2*i-1); j++) . System.out.print(“*”); ***.....*** System.out.println(“”); } 4/29/2019 CS102 - Algorithms & Programming II

CS102 - Algorithms & Programming II Nested Loops Nesting can be more than one level int sum=0; for (i=1; i<=5; i++) for (j=1; j<=5; j++) for (k=1; k<=5; k++) sum=sum+1;  sum is 125 4/29/2019 CS102 - Algorithms & Programming II