Week 4 Iteration and While Loop.pdf
Document Details
Uploaded by SimplifiedLaplace
Tags
Full Transcript
Iterative Control Statements Repetition / Loops while, do-while, for Control Structures • Control Structures determine the order in which statements or instructions are carried out in a Java program. • The three main control structures in any programming language are – Sequence – Selection – Repet...
Iterative Control Statements Repetition / Loops while, do-while, for Control Structures • Control Structures determine the order in which statements or instructions are carried out in a Java program. • The three main control structures in any programming language are – Sequence – Selection – Repetition/Iteration 2 Sequence & Selection • Sequence: Instructions in a program are executed in the order they appear line after line • Selection: Sections of code are selected within the program. Allows for alternative course of actions Iteration • Suppose you need to display a string e.g. Welcome to Java 100 times • It would be tedious to write the following statement 100 times System.out.println(“Welcome to Java”); System.out.println(“Welcome to Java”); …… System.out.println(“Welcome to Java”); 100 times Iteration • Java provides a powerful construct called a loop that controls how many times an operation or sequence of operations is performed in succession • Using a loop you simply tell the program how many times you want an operation repeated Iteration • Java provides three such types of loop structures: – while – do – while – for • We will start by studying the while loop Two types of repetition • Number of repetitions is known – for loop • Number of repetitions is unknown – while and do-while loop (Note: while and do-while loops can also be used when number of repetitions is known but generally it is always for loop that is used) Iterative Control Structures • A repetition structure allows the programmer to specify that an action is to be repeated while some condition remains true. • Psuedocode While there are more items on my shopping list Put item in my trolley Cross it off my list while statement Syntax or General form while(control condition) { statement(s); } • Causes one or more statements to repeat as long as a specified condition remains true • Repetition terminates when the condition becomes false • The control condition in a while loop is tested before the statements in the loop are executed • It is possible that the loop statements will never be executed while statement • while is keyword or reserved word • The control condition is a Boolean expression (True or False) that controls execution of the loop while(control expression) { statement1; statement2; . . statementn; } • If condition is True the loop body is executed; if it’s evaluation is False the entire loop is terminated while statement • Part of the loop that contains statements to be repeated is known as loop body. Contained within { } while(control condition) { //loop body statement(s); } Write “Welcome to Java” 100 times • Pseudocode Set counter to 1 WHILE counter is less than or equal 100 Print “Welcome to Java” Add 1 to counter Write “Welcome to Java” 100 times • If a loop is going to repeat a statement a number of times then we need a counter that counts how many repetitions have been made • The counter must be set at an initial value • The counter must be able to move from the initial value to the number of repetitions by either adding to it or subtracting from it Write “Welcome to Java” 100 times • In this example we want counter to start printing from line 1 • We want it to stop after line 100 • By adding 1 to the counter after each repetition the program will know how many repetitions were made Sample Program 1 //program to display text on screen 100 times public class Iteration1 { public static void main(String args[]) { //declare variables int counter = 1; //declare variable and initialize with 1 while(counter <= 100) //while condition is true { //display text System.out.println(“Welcome to Java"); counter++; //add 1 to counter using increment operator } //end while }//end main method }//end class while Flowchart counter =1 counter<=100 true System.out.print(“Welcome to Java”) counter++; false Terminates when counter is 101 Increment & Decrement Operators • In Sample Program 1 we encountered the line of code counter++ • ++ is known as increment operator and it is a shorthand way of adding the value of 1 to a variable • Has same effect as writing counter = counter + 1 Increment & Decrement Operators • Likwise -- is know as decrement operator and it is the shorthand way of subtracting 1 from a variable • counter -- has same effect as writing counter = counter - 1 Increment & Decrement Operators • Both of these operators can only be applied to variables and can only change the value of the variable by a value of 1 • To change the value of a variable by 2 in shorthand we would write counter+=2 Display digits 0 to 9 on screen • Pseudocode Set counter to 0 WHILE counter is less than or equal to 9 Display counter Add 1 to counter Sample Program 2 //program to display digits 0,1,2,3,…9 public class Iteration2 { public static void main(String args[]) { //declare variables int counter = 0; //declare variable and initialize with 0 while(counter <= 9) //while condition is true { System.out.println(counter); //display value of counter counter++; //increment counter – add 1 to counter } //end while }//end main method }//end class while Flowchart counter = 0 counter<=9 true System.out.print(counter); counter++; false Terminates when counter is 10 Display sum of numbers 1 to 10 • Pseudocode Set total to 0 Set counter to 1 WHILE counter is less than or equal to 10 ADD counter to total ADD 1 to counter DISPLAY total Sample Program 3 //total numbers from 1 to 10 public class Iteration3 { public static void main(String args []) { int counter =1, total = 0; while(counter <= 10) { total = total + counter; //add counter to total each time round counter++; //increment counter } //end while //Print total outside the loop System.out.println("Total of numbers from 1 to 10 is " +total); }//end main method }//end class Infinite loop • A loop that runs forever • Can be stopped by killing the program Consider the code…. : int years = 0; while(years < 20) { balance = balance + interest; } Problem years will always be 0 – loop cannot terminate : int years = 0; while(years < 20) years is not incremented in { loop body interest = balance * rate /100; } Consider the code… //display numbers 10 to 1 int digit = 10; while(digit > 0) { System.out.print(digit); digit++; } System.out.print("Blast off!"); Problem //display numbers 10 to 1 int digit = 10; while(digit >= 0) { System.out.print(digit); digit++; digit should be decremented, not } incremented – digit will always be greater than 0 System.out.print("Blast off!");