java iteration statements - bguipc172/wiki.files/class_java_3.pdf · java has three kinds of ....

47
1

Upload: others

Post on 31-May-2020

11 views

Category:

Documents


1 download

TRANSCRIPT

  • 1

  • 2

  • Java iteration statements● Iteration statements are statements which appear in the

    source code only once, but it execute many times. ● Such kind of statements are called loops.● Almost all the programming languages support looping

    instructions.

    3

    a = b5; if( a >= c9) while( a >= 5 ) b = a / 10; a = a + 4; { c = a + b; else b = 9 + a;

    a = a – 7; a --; } // while

  • Iteration statements - LoopsJava has three kinds of iteration statements ( לולאות/הוראות חזרה ) :

    WHILE loopFOR loopDO . . . WHILE loop

    Iteration (repetition) statements causes Java to execute one or more statements as long as a condition exist. Each repetition statement request :

    1. a control variable / loop counter ( משתנה הלולאה/מונה הלולאה )2. the initial value of control variable3. the increment (decrement) by which the control variable

    is modified each time through the loop4. the loop continuation condition that determines if looping

    should continue.

    4

  • Basic elements of iterations/* example with the while statement

    prints numbers from 1 through 10 */public class While_Test1{

    public static void main(String[ ] args){

    int counter = 1;while(counter

  • Java Loop structures

    ?

    ?

    While structureDo-while structure

    6

  • 7

    While loop statementwhile (loop-continuation-condition) {// loop-body;Statement(s);

    } //while

    int count = 0;while (count < 100) {

    System.out.println("Welcome to Java!");count++;} // while

    Loop Continuation Condition?

    true

    Statement(s) (loop body)

    false (count < 100)?

    true

    System.out.println("Welcome to Java!"); count++;

    false

    (A) (B)

    count = 0;

    Statement(s)

    (loop body)

    true

    System.out.println("Welcome to Java!");

    count++;

    (B)

    (A)

    true

    false

    false

    count = 0;

    (count < 100)?

    Loop

    Continuation

    Condition?

  • We designate zero to be a sentinel ( קיףז( value that indicates the end of the input.A sentinel must always be outside the normal range of values entered.

    int sum = 0,num,count = 0;// sum of series, input variable and loop counterdouble avg; // average of seriesSystem.out.println(“enter an integer ( 0 to quit) : “);num = reader.nextInt();while (num != 0){

    count++;sum+ = num;System.out.println(“enter an integer ( 0 to quit) : “);num = reader.nextInt( );

    } // whileavg = (double)sum/count;System.out.println(“The average is : “ + avg);

    Casting

    Sentinel value of 0 to terminate loop.Sentinel value is not counted.

    This program section reads a series of integers and computes their average.

    8

  • 9

    While loop – order of execution

  • While loop example 1• Input :

    – Two integers – num1 and num2

    • Output :– How many times num1 contains num2This is the result of the integer division num1/num2

    • Note :

    – Do not use the division operator ( / ) !10

  • Solution example 1public class Ex1While{static Scanner reader = new Scanner(System.in);

    public static void main(String[ ] args){

    int res = 0; // help variableSystem.out.println(“enter two integers : “);int num1 = reader.nextInt();int num2 = reader.nextInt();while ( (res+1) * num2

  • While loop example 2

    public class Ex2While{

    static Scanner reader = new Scanner(System.in);public static void main(String[ ] args){

    int res = 0; // ?System.out.println(“enter a positive number: “);int num = reader.nextInt();while ( num > 0 ) {

    res+ = num % 10;num/ = 10;

    } // whileSystem.out.println(“res= : “ + res);

    } // main} //class Ex2While

    This program reads an integer and …?

    12

  • Use of Logical operatorsAlong with relational operators (, >=,

  • Infinite loops● It is the programmer’s responsibility to ensure that the

    condition of a loop will eventually become false. If it doesn’t, the loop body will execute forever.

    ● This situation, called an infinite loop ( לולאה אין סופית ).

    Example 1: Example 2:int count = 1; double num = 2.0; while (count != 50) while ( num != 0.0)

    count+ = 2; num = num - 0.1;

    This loop will never terminate because count will never equal 50.

    This loop will never terminate because num will never have a value exactly equal to 0.0

    14

  • public static void main(String[ ] args){

    int var = 6;while (var >=5){

    System.out.println(“var = “+ var); var++;

    } // while} // main

    public static void main(String[ ] args){

    int var = 5;while (var =5 so the loop would never end.

    var value will keep decreasing because of – operator, hence it will always be

  • FOR loop statement• Equivalent to while… Any for loop can be converted

    to while loop and vice versa.

    • If we want to perform something for a predefined number of times, better use for.

    • If we just wait for something to happen (not after a certain number or iterations), better use while.

    • The for loop has three expressions that are contained within parentheses and separated with a semicolon.

    16

  • FOR loop - structureprogram statements before the for loop…

    for ( ; ; ; ; ; ){

    }program statements after for loop…

    Initialization Conditional Iteration

    for loop body

    for loop header

    17

  • FOR loop – order of execution

    initialization

    conditional

    iteration For loop body

    false

    true

    Three kinds of for loop header expressions

    ● Before the loop begins the first part of the header, called initialization, is executed.

    ● The second part of the header is the boolean condition, which is evaluatedbefore the loop body. If true ,the body is executed.

    ● The iteration part is executed after each iteration of the loop.

    Initialization is executed only once

    18

  • FOR loops execution

    For loops are controlled by a counter variable.

    for( num = init_value; num

  • 20

    Example 1:for (int num = 100; num > 0; num --)

    System.out.println(“num = “ + num);

    Example 2:for (int num = -3; num

  • 21

    FOR loop – order of execution

    The iteration part is executed after each iteration of the loop.

  • Infinite For loop Example● This Java Example shows how to create a for loop that runs infinite

    times in Java program.● It happens when the loop condition is always evaluated as true.● Its perfectly legal to skip any of the 3 parts of the for loop.

    Below given for loop will run infinite times.

    public class InfiniteForLoop{

    public static void main(String[ ] args){

    for( ; ; )System.out.println("Hello");

    } // main} // InfiniteForLoop

    22

    To terminate this program press ctrl + c in the console

  • FOR loops example 1This program section reads an integer and computes itsfactorial ( n!).

    int fact = 1; // factorialSystem.out.println("enter an integer : ");int n = reader.nextInt(); // input variablefor (int i = 1; i

  • Trace table (while)

    24

    public static void main(String[ ] args){

    int res = 0; // sum of digitsSystem.out.println(“enter a positive number: “);int num = reader.nextInt( ); // num = 123

    while ( num > 0) {res + =num % 10;num/ = 10;

    } // while

    System.out.println(“res= : “ + res);} // main

    num>0 num%10 res num output

    0 123

    T 3 3 12

    T 2 5 1

    T 1 6 0

    F 6

    input: 123

    Before loop execution

  • FOR loops example 2

    int prime = 1; / / help variableSystem.out.println( “ enter an integer : “ );int x = reader.nextInt(); / / input variableif (x > 3){

    for( int i = 2; i < x && prime == 1; i++ )if( x%i == 0)

    prime = 0;switch (prime){

    case 1:System.out.println(x + " is prime number “ );break;

    case 0:System.out.println(x + " is not prime number “ );break;

    } // switch} // if (x>3)else

    System.out.println(x + " is prime number ");

    This program section checks if the input integer is the prime number.

    25

  • Do …while loop statementdo{

    statement(s)} while (expression) ;

    • Similar to while loops– Except the condition is evaluated after the loop body.

    The condition is written at the end of the loop to indicate that it is not evaluated until the loop body is executed.

    – The loop body is always executed at least once, even if the expression is never true .

    Note that the loop begins with thereserved word do

    Note that the loop ends with semicolon

    26

  • Do …while loop execution

    Loop Continuation Condition?

    true

    Statement(s) (loop body)

    false

    27

    Statement(s)

    (loop body)

    false

    true

    Loop

    Continuation

    Condition?

  • Do …while loop example 1

    // program statement before the do…while loop

    System.out.print( "Please, enter a positive number: “ );do {

    int num = reader.nextInt(); if (num

  • Do …while loop example 2

    int reversNum = 0; // reversed numberSystem.out.println("enter an integer : ");int num = reader.nextInt( ); // input variabledo{

    int lastDigit = num % 10;reversNum = (reversNum*10 )+ lastDigit;num = num / 10;

    } while (num > 0);System.out.println(" That number reversed is “ + reversNum);

    This program section reads an integer and reverses its digit mathematically.

    29

  • Do …while loop example 3

    int x = 1; // ?System.out.println("enter an integer : ");int num = reader.nextInt( ); // input variabledo{

    x *= num;} while ( -- num >= 1);System.out.println(" x= “ + x );

    This program section reads an integer and …?

    30

  • 31

    Trace table (do - while)int x = 1; // ?System.out.println("enter an integer : ");int num = reader.nextInt( ); // input variabledo{

    x *= num;} while ( -- num >= 1);System.out.println(" x= “ + x );

    x num -- num >= 1 output

    1 3

    3 2 T

    6 1 T

    6 0 F 6

    Before loop execution

    input: 3

  • 32

    Java iteration statements

  • Fibonacci series

    • The Fibonacci sequence is named after Leonardo of Pisa,who was known as Fibonacci.

    • In mathematics, the Fibonacci numbers or Fibonacci seriesor Fibonacci sequence are the numbers in the following integer sequence:

    n: 0 1 2 3 4 5 6 . . .: 0 1 1 2 3 5 8 . . .

    0 n= 0

    = 1 n=1+ n >1

    33

    F n

    F nF n 1− F n 2−

    Number of element in the series

  • Fibonacci series – solutionpublic static void main(String[ ] args) {

    int n; // number of element in the seriesdo {

    System.out.print(" Enter an positive integer => ");n = reader.nextInt();

    } while (n < 0);int Fn2 = 0 ;int Fn1 = 1 ;int Fn = 0 ;if ( n == 1 )

    Fn = 1 ;for (int ind = 2 ; ind

  • Nested loops● The body of loop can contain another loop. This situation is

    called a nested loop ( לולאות מקוננות ).● Note, that for each iteration of outer loop, the inner loop

    executes completely.

    The next program section reads the integer number n,real number x and calculates the sum of the mathemaitcserias :

    !...

    !3!2!11

    321

    nxxxx n

    +++++

    35

  • Nested loops example 1double sum = 1.0; // sum of seriesint f; // n factorialdouble h; // x degreeint i = 1; // loop counterSystem.out.print( "enter an integer : “ );int n = reader.nextInt(); System.out.print( "enter real number : “ );double x = reader.nextDouble();while (i

  • Nested loops example 2Write a program that reads the grades of 100 students .Each student takes different number of courses.The program calculates and prints the average grade of each student. The program also calculates the number of excellent students ( average grade above 85 ).For example: for the next three students we have the following output :

    37

    Enter a grade -> 89Enter a grade -> 94Enter a grade -> 93Enter a grade -> 88Enter a grade -> -999The average of student number 1 is 91.0Enter a grade -> 78Enter a grade -> 76Enter a grade -> 68Enter a grade -> -999The average of student number 2 is 74.0Enter a grade -> 100Enter a grade -> 88Enter a grade -> 100Enter a grade -> 98Enter a grade -> -999The average of student number 3 is 96.5There are 2 excellent students

    sentinel

  • Nested loops example 2public static void main(String[] args){

    int grd; // student's gradeint sum; // sum of gradesint count; // number of coursesint best = 0; // number of excellent studentsdouble avg; // average gradefor(int i = 1; i 85)

    best++;} // forSystem.out.println("There are " + best + " excellent students");

    } // main38

    inner loop

    outer loop

  • ● The following program uses a nested for loop to find theprime numbers from 2 to 100:

    39

    Nested loops example 3

    public static void main(String[ ] args){

    int i, j; // loop countersfor( i = 2; i < 100; i++)

    {for( j = 2; j (i / j)) System.out.println(i + " is prime ");

    } // outer for} // main

    2 is prime 3 is prime 5 is prime 7 is prime 11 is prime 13 is prime .....73 is prime 79 is prime83 is prime 89 is prime 97 is prime

  • 40

    Jump statements ( הוראות קפיצה )

  • Jump statements ( הוראות קפיצה )

    • When break is encountered, the loop is exited regardless of whether the condition is still true.The break statement tells Java to exit a code block ( loop body) defined by opening and closing braces and used in a loop.The program then continues to run from the first line after the while/for/do…while body’s loop.If called within a nested loop, break breaks out of the inner loop only.

    • When continue is encountered, the rest of the loop is ignored.The program then continues to run from the beginning of the loop.

    A jump statement transfers control to another part of the program.There are two kinds of jump statements : break and continue.

    41

  • Using break statement program statement before theloop …

    loop(expression){

    .

    .break;..

    } //end loop

    program statement after theloop …

    program statement before thenested loops …

    loop1(expression1) {.

    loop2(expression2) {.break;.

    } // end loop2

    // continue with loop1} // end loop1program statement after the nested loops…

    42

  • Using break statement

    43

    ● Break statement is used to make looping statements more flexible andprovides more power to it.

  • Using continue statementprogram statement before the loop…

    loop ( expression ){

    .

    .continue;..

    } // loop

    program statements after the loop…// continue with the program

    Ignore executing rest of the loop’s body in this iteration

    44

  • 45

    Using continue statement● Continue Statement can be used only in Loop Control Statements such as

    For Loop | While Loop | do-While Loop.

    http://www.c4learn.com/java/java-for-loop/http://www.c4learn.com/java/java-while-loop/http://www.c4learn.com/java/java-do-while-loop/

  • break and continue examplesBrake out of loop at i = 5

    for (int i = 1; i

  • 47

    Caution !● Similarly, the following while loop is wrong:

    int i = 0; while (i < 10);{

    System.out.println("i is " + i);i++;

    }

    ● In the case of the do…while loop, the following semicolonis needed to end the loop.

    int i = 0; do {

    System.out.println("i is " + i);i++;

    } while (i < 10);

    Error !

    Correct !

    Slide Number 1Slide Number 2Java iteration statementsIteration statements - LoopsBasic elements of iterations Java Loop structuresWhile loop statementSlide Number 8 While loop – order of executionWhile loop example 1Solution example 1While loop example 2��Use of Logical operators��Infinite loopsInfinite loops (while)FOR loop statementFOR loop - structure FOR loop – order of executionFOR loops executionFOR loops examples FOR loop – order of execution�Infinite For loop Example�FOR loops example 1Trace table (while)FOR loops example 2Do …while loop statementDo …while loop executionDo …while loop example 1Do …while loop example 2Do …while loop example 3Trace table (do - while)Java iteration statementsFibonacci seriesFibonacci series – solutionNested loopsNested loops example 1Nested loops example 2Nested loops example 2Nested loops example 3Jump statements ( הוראות קפיצה )Jump statements ( הוראות קפיצה )Using break statement Using break statement Using continue statementUsing continue statementbreak and continue examplesCaution !