Presentation is loading. Please wait.

Presentation is loading. Please wait.

Lecture 4b Repeating With Loops

Similar presentations


Presentation on theme: "Lecture 4b Repeating With Loops"— Presentation transcript:

1 Lecture 4b Repeating With Loops

2 Loops

3 A loop is structure that allows repeated execution of a block of statements
The loop structure is controlled by a Boolean expression When the Boolean expression evaluates to true the block of statements that forms the loop body executes. The Boolean expression is repeatedly evaluated as long as it remains true When the Boolean expression becomes false the loop is terminated.

4 Flowchart of a loop structure
Boolean Expression true Loop Body false

5 There are three types of loops in Java:
for loops while loops Do-while loops

6 The for Loop The for loop is used when a definite number of repetitive task is to be performed The for loop has three main expressions for creating the loop The three expressions are contained in one place (the parentheses) and include A starting value for the loop control variable The test condition that controls the loop entry An expression that alters the loop control variable Within the parentheses the three expressions are separated by two semicolons The parentheses are followed by an optional pair of braces

7 Parts of The for Loop The for loop begins with the for keyword followed by a pair parentheses There are three sections within the pair of parentheses separated by two semicolons The three sections are used for Initialising the loop control variable Testing the loop control variable Updating the loop control variable The pair of parentheses of are followed by the body of the for loop Like the if statement, the for loop body can be a single statement or a block statement in braces

8 Structure of the for Loop
for (initialization expression; loop condition; increment expression){ //statement } The control of the for loop appear in parentheses and is made up of three parts. The first part, the initialization expression, sets the initial conditions for the loop and is executed before the loop starts. Loop executes so long as the loop condition is true and exits otherwise The third part of the control information, the increment expression, is usually used to increment the loop counter. This is executed at the end of each loop iteration.

9 For example: int limit = 5; int sum = 0;
for(int i = 1; i<=limit; i++){ /* initialization expression loop condition increment expression */ sum += 2; } What is the value of sum ? 10

10 for(int div = 0; div<1000; div++){ if(div % 12 == 0){
Another example: for(int div = 0; div<1000; div++){ if(div % 12 == 0){ System.out.println(div+"is divisible by 12"); } } This loop will display every number from 0 to 999 that is evenly divisible by 12.

11 for(int i = 0; i < 100; ){ sum += i;
If there is more than one variable to set up or increment they are separated by a comma. for( i = 0, j = 0; i * j < 1000; i++, j+=2){ System.out.println(i+"*"+j+"="+i*j); } You do not have to fill every part of the control of the for loop but you must still have two semi-colons. for(int i = 0; i < 100; ){ sum += i; i++; }

12 The while loop The while loop has a loop controlling Boolean expression The Boolean expression is the first statement in the while loop The while loop can be used to execute a set of statements for as long as the Boolean expression remains true In Java, the while loop consists of the keyword while followed by a Boolean expression within a set of parentheses followed by the loop body The loop body can be a single statement or a block of statements within a set of curly braces

13 The while Loop Structure
while (expression){ statement } This while loop executes as long as the given logical expression between parentheses is true. When the expression is false, execution continues with the statement following the loop block. The expression is tested at the beginning of the loop, so if it is initially false, the loop will not be executed at all.

14 For example: int limit = 7; int sum = 0; int i = 1;
while (i < limit){ sum += i; i++; } What is the value of sum? 21

15 The for loop The while loop Initialize count Test condition is true?
Execute loop statement(s) Increment count New statement The for loop y n Test condition is true? Execute loop statement(?) Next statement The while loop y n

16 Definite and Infinite loop
The while loop can be used to perform a specific task for a predetermined number of times A loop that executes for a specific number of times is known as a definite loop In a definite loop a loop control variable is initialised whose value is used to determine the loop’s execution continuation As long as the loop control variable does not exceed a limiting value the loop body execution continues A statement to alter the loop control variable must be included within the loop body to avoid an infinite loop An infinite loop is a loop that never ends and that is a common mistake committed by most programmers

17 How to prevent infinite loops
It is not a good idea to write infinite loop for any reason In order to prevent a loop from running infinitely we would adopt the following three action steps A loop control variable must be declared and initialised with a starting value The loop control variable must be tested in the while statement If the test expression evaluates to true, the body of the while statement must include a statement that will alter the value of the loop control variable so it can eventually evaluate to false in order to terminate the loop

18 Creating Indefinite loop
Often the a program may be executed for unlimited number of times Such programs contain loops without loop control variables and are known as indefinite loops Indefinite loops have loops that are controlled by user input Such loops will continue to run as long as the user indicates a desire to continue running the program Indefinite loops are used mainly in data input validation Data validation is a process of ensuring that some value falls within a specific range

19 User control Sample String response; int age, years; int birthYear, currentYear; while( response == “Yes” ) { age = currentYear – birthYear; years = years + 1; }

20 The continue Statement
The continue statement causes the loop to exit its current “trip” through the loop and start over at the first statement of the loop. Here are two examples: Example 1: int index = 0; while(index<=5){ index+=1; if(index==4){ continue; } System.out.println("The index is "+index); The index is 1 The index is 2 The index is 3 The index is 5 The index is 6

21 12 int sum = 0; for(int i=1; i<=6; i++){ if(i%3==0){ continue; }
Example 2: int sum = 0; for(int i=1; i<=6; i++){ if(i%3==0){ continue; } sum += i; What is the value of sum? 12

22 Using the break Statement in Loops
We have seen the use of the break statement in the switch statement. In loops, you can use the break statement to exit the current loop you are in. Here is an example: int index = 0; while (index <= 10){ index++; if(index==3) break; System.out.println("The index is"+index); } The index is 1 The index is 2

23 Nested Loops You can nest loops of any kind one inside another to any depth. Here is an example: int totalCount = 0; while(totalCount<20){ for(int i = 0; i < 2; i++){ totalCount += i; } System.out.println(totalCount); 20

24 Final example: for (int i = 1; i <= 10; i++) { if (i % 2 == 0 ) System.out.println("The number " + i + " is even.") } else System.out.println("The number " + i + " is odd.")

25 The do-while loop The do-while loop is a variation of the while loop
Its syntax is given as do{ // loop body Statement(s); } while( loop-continuation-condition); The do-while loop executes the loop body first It then checks the loop continuation condition to determine whether to continue or to terminate the loop If the condition is true the loop body is executed again. If it is false the loop is terminated

26 The while-loop and the do-while-loop are equal in power
Sometimes one is a better choice than the other A while-loop can be re-written in a do-while-loop and a do-while-loop can be re-written in a while-loop It is often a good idea to choose the do-while-loop if there are statements inside the loop that must be executed at least once before the test condition is performed

27 TestDoWhile public class TestDoWhile { public static void main( String args[] ) int myData = 1, sumMyData = 0; do sumMyData += myData; System.out.println(“myData is ” + myData); }while( sumMyData < 10); System.out.println(“\nsumMyData is ” + sumMyData + “\n”); }

28 SHORT TEST In the switch statement expression must produce a result of what type? What must be used to separate each section of a for statement. Which statement causes a program to go back to the statement that began a loop and then keep going from there. Write a for loop that outputs 1001 in reverse sequence. Write a for loop that outputs all numbers that are divisible by 3 between 0-50. char, byte, short, int ;(semi colon) ( continue ;) Answers: From slide “Switch Statements”: char, byte, short or int From slide “The for loop”: a semi-colon From slide “The continue Statement”: continue for(int i=100; i>0; i--) System.out.println(i); for(int i=0; i<=50; i++) { if (i%3 == 0) } for( int k = 100; k >= 1; --k ) {SOP( k ) ; } for( int p = 0; p <= 50; p++ ) { if( p % 3 == 0 ) { System.out.print( p ); } }

29 SHORT EXERCISE In the switch statement expression must produce a result of what type? What must be used to separate each section of a for statement. Which statement causes a program to go back to the statement that began a loop and then keep going from there. Write a for loop that outputs 1001 in reverse sequence. Write a for loop that outputs all numbers that are divisible by 3 between 0-50. char, byte, short, int ; (semi-colon)

30 SHORT EXERCISE In the switch statement expression must produce a result of what type? What must be used to separate each section of a for statement. Which statement causes a program to go back to the statement that began a loop and then keep going from there. Write a for loop that outputs 1001 in reverse sequence. Write a for loop that outputs all numbers that are divisible by 3 between 0-50. char, byte, short, int ; (semi-colon) continue

31 SHORT EXERCISE In the switch statement expression must produce a result of what type? What must be used to separate each section of a for statement. Which statement causes a program to go back to the statement that began a loop and then keep going from there. Write a for loop that outputs 1001 in reverse sequence. Write a for loop that outputs all numbers that are divisible by 3 between 0-50. char, byte, short, int ; (semi-colon) continue for(int i=100; i>=0;i--) { System.out.println(i);}

32 SHORT EXERCISE In the switch statement expression must produce a result of what type? What must be used to separate each section of a for statement. Which statement causes a program to go back to the statement that began a loop and then keep going from there. Write a for loop that outputs 1001 in reverse sequence. Write a for loop that outputs all numbers that are divisible by 3 between 0-50. char, byte, short, int ; (semi-colon) continue for(int i=100; i>=0;i--) { System.out.println(i);} for(int i=0;i<=50;i++) { if(i%3 == 0) { System.out.println(i); } }


Download ppt "Lecture 4b Repeating With Loops"

Similar presentations


Ads by Google