SlideShare a Scribd company logo
1 of 26
The syntax of the iterative statements of Java




                                                 1
Objective

On completion of this lecture you would be able to
 know

•   The various iteration statements in Java




                                                     2
Recap

In the previous class we have discussed

• Various selection statements available in Java




                                                   3
Iterative statements in Java

• Java language provides three loop or iterative
  statements

• They are
   •   while statement
   •   do statement
   •   for statement




                                                   4
The while Statement

int sum = 0, number = 1;


while ( number <= 100 ) {


    sum = sum + number;
                             These statements are
                              These statements are
                             executed as long as number
                              executed as long as number
                             is less than or equal to 100.
                              is less than or equal to 100.
    number = number + 1;


}


                                                              5
Syntax for the while Statement
                 while ( <boolean expression> ) {
                        <statement>
                 }
                                                    Boolean Expression
                                                    Boolean Expression



                  while ( number <= 100       ){

 Statement
  Statement           sum = sum + number;
(loop body)
 (loop body)           number = number + 1;
                  }


                                                                 6
Control Flow of while


int sum = 0, number = 11
 int sum = 0, number =




                           true
 number <= 100 ??
  number <= 100



false
                             sum = sum + number;
                              sum = sum + number;

                             number = number + 1;
                              number = number + 1;




                                                     7
while Loop Pitfall - 1

1
1   int product = 0;


    while ( product < 500000 ) {
        product = product * 5;
    }                                       Infinite Loops
                                             Infinite Loops
                                         Both loops will not
                                          Both loops will not
                                         terminate because the
                                          terminate because the
                                         boolean expressions will
                                          boolean expressions will
2
2   int count = 1;                       never become false.
                                          never become false.



    while ( count != 10 ) {
        count = count + 2;
    }


                                                             8
while Loop Pitfall - 2

1
1   float count = 0.0f;


    while ( count != 1.0f ) {
        count = count + 0.3333333f;
    }                                     Using Real Numbers
                                          Using Real Numbers
                                         Loop 22terminates, but Loop 11
                                          Loop terminates, but Loop
                                         does not because only an
                                          does not because only an
                                         approximation of aareal
                                          approximation of real
                                         number can be stored in aa
2
2   float count = 0.0f;                   number can be stored in
                                         computer memory.
                                          computer memory.


    while ( count <= 1.0f ) {
        count = count + 0.3333333f;
    }


                                                                 9
while Loop Pitfall - 3
 • Goal: Execute the loop body 10 times.

1 count = 1;
1                                2 count = 1;
                                 2
   while (count < 10) {              while (count <= 10) {
       ...                                 ...
       count++;                            count++;
   }                                 }
3 count = 0;
3                                4 count = 0;
                                 4
   while (count <= 10) {             while (count < 10) {
       ...                                 ...
       count++;                            count++;
   }                                 }
    1 and 3 exhibit off-by-one error.
    1     3

                                                             10
The do-while Statement

int sum = 0, number = 1;


do {

                                 These statements are
                                  These statements are
       sum += number;            executed as long as sum is
                                  executed as long as sum is
                                 less than or equal to
                                  less than or equal to
       number++;                 1,000,000.
                                  1,000,000.


} while ( sum <= 1000000 );




                                                           11
Syntax for the do-while Statement
                do {
                          <statement>

                } while (<boolean expression>);


               do {


                     sum += number;                Statement
                                                    Statement
                     number++;                    (loop body)
                                                   (loop body)


               } while (sum <= 1000000);


Boolean Expression
Boolean Expression


                                                        12
Control Flow of do-while


 int sum = 0, number = 11
  int sum = 0, number =




sum += number;
 sum += number;

number++;
 number++;




                            true
sum <= 1000000 ??
 sum <= 1000000


 false


                                   13
Pre-test vs. Post-test loops

•   Use a pre-test loop for something that may be
    done zero times

•   Use a post-test for something that is always done
    at least once




                                                        14
Checklist for Repetition Control

1. Watch out for the off-by-one error (OBOE).

2. Make sure the loop body contains a statement that
   will eventually cause the loop to terminate.

3. Make sure the loop repeats exactly the correct
   number of times.




                                                    15
Syntax of the for Statement
for ( <initialization>; <boolean expression>; <update> )


                               <statement>

                                       Boolean
                                       Boolean
Initialization
 Initialization                                          Update
                                                         Update
                                      Expression
                                      Expression


  for (     i=0 ;                     i < 20   ;   i++     ){


          number = inputBox.getInteger();                        Statement
                                                                  Statement
          sum += number;                                        (loop body)
                                                                 (loop body)
  }




                                                                               16
Control Flow of for

                      ii= 0;
                        = 0;



                     ii< 20 ??
                       < 20
false
                               true
        number = inputBox.getInteger( );
         number = inputBox.getInteger( );
        sum += number;
         sum += number;




                       ii++;
                         ++;




                                            17
The for Statement

int i, sum = 0, number;


for (i = 0; i < 20; i++) {


    number = inputBox.getInteger();

    sum += number;


}                                     These statements are
                                       These statements are
                                      executed for 20 times
                                       executed for 20 times
                                       ((i i= 0, 1, 2, … , ,19).
                                             = 0, 1, 2, … 19).




                                                                   18
Indefinite vs. Definite loops

•   For loops and while loops are exchangeable

•   But use a for loop when the number of iterations
    are definite

•   Use a while or do-while when the number of
    iterations depends on statements in the loop body




                                                   19
Summary

In this class we have discussed

•   Various iterative statements available in Java




                                                     20
Quiz

1.Which of the following loop is deterministic

a)   while

b)   do

c)   for

d)   all of the Above




                                                 21
Quiz
2.If altering statement is missed in a loop, then it
    becomes

a)   fast loop

b)   deterministic loop

c)   non deterministic loop

d)   infinite loop




                                                       22
Quiz

3.Minimum iteration for _______ loop is one.

a)   for

b)   while

c)   do

d)   all of these




                                               23
Assignment
• Write a Java program to find factorial of a given
  no.

• Write a Java program to find Fibonacci series.

• Write a Java program to find whether the given no
  is prime or not.




                                                      24
Frequently asked questions

• List the various iterative statements available in
  Java

• Explain the working of various iterative
  statements

• Compare while with do statement

• Compare while, do with for loop




                                                       25
 
                swings
              Struts
                  jdbc
               hibernate
                 home
   java previous question papers
 OCT/NOV-2012 QUESTION PAPER
       April / May 2012 c-09
   October/ November-2011 c-09
        April/ May 2011 c-09
        April/ May 2011 c-05




                                   26

More Related Content

What's hot

Python programing
Python programingPython programing
Python programinghamzagame
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to pythonMarian Marinov
 
Lucio Floretta - TensorFlow and Deep Learning without a PhD - Codemotion Mila...
Lucio Floretta - TensorFlow and Deep Learning without a PhD - Codemotion Mila...Lucio Floretta - TensorFlow and Deep Learning without a PhD - Codemotion Mila...
Lucio Floretta - TensorFlow and Deep Learning without a PhD - Codemotion Mila...Codemotion
 
.NET 2015: Будущее рядом
.NET 2015: Будущее рядом.NET 2015: Будущее рядом
.NET 2015: Будущее рядомAndrey Akinshin
 
Parsers Combinators in Scala, Ilya @lambdamix Kliuchnikov
Parsers Combinators in Scala, Ilya @lambdamix KliuchnikovParsers Combinators in Scala, Ilya @lambdamix Kliuchnikov
Parsers Combinators in Scala, Ilya @lambdamix KliuchnikovVasil Remeniuk
 
Mesics lecture 7 iteration and repetitive executions
Mesics lecture 7   iteration and repetitive executionsMesics lecture 7   iteration and repetitive executions
Mesics lecture 7 iteration and repetitive executionseShikshak
 
Davide Cerbo - Kotlin: forse è la volta buona - Codemotion Milan 2017
Davide Cerbo - Kotlin: forse è la volta buona - Codemotion Milan 2017 Davide Cerbo - Kotlin: forse è la volta buona - Codemotion Milan 2017
Davide Cerbo - Kotlin: forse è la volta buona - Codemotion Milan 2017 Codemotion
 
Beyond javascript using the features of tomorrow
Beyond javascript   using the features of tomorrowBeyond javascript   using the features of tomorrow
Beyond javascript using the features of tomorrowAlexander Varwijk
 
Very interesting C programming Technical Questions
Very interesting C programming Technical Questions Very interesting C programming Technical Questions
Very interesting C programming Technical Questions Vanathi24
 

What's hot (20)

Computer Programming- Lecture 6
Computer Programming- Lecture 6Computer Programming- Lecture 6
Computer Programming- Lecture 6
 
Python programing
Python programingPython programing
Python programing
 
Computer Programming- Lecture 9
Computer Programming- Lecture 9Computer Programming- Lecture 9
Computer Programming- Lecture 9
 
Computer Programming- Lecture 5
Computer Programming- Lecture 5 Computer Programming- Lecture 5
Computer Programming- Lecture 5
 
Computer Programming- Lecture 7
Computer Programming- Lecture 7Computer Programming- Lecture 7
Computer Programming- Lecture 7
 
Algorithm
AlgorithmAlgorithm
Algorithm
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
 
C# - What's next
C# - What's nextC# - What's next
C# - What's next
 
Lucio Floretta - TensorFlow and Deep Learning without a PhD - Codemotion Mila...
Lucio Floretta - TensorFlow and Deep Learning without a PhD - Codemotion Mila...Lucio Floretta - TensorFlow and Deep Learning without a PhD - Codemotion Mila...
Lucio Floretta - TensorFlow and Deep Learning without a PhD - Codemotion Mila...
 
Chapter 00 revision
Chapter 00 revisionChapter 00 revision
Chapter 00 revision
 
.NET 2015: Будущее рядом
.NET 2015: Будущее рядом.NET 2015: Будущее рядом
.NET 2015: Будущее рядом
 
Chapter7
Chapter7Chapter7
Chapter7
 
Parsers Combinators in Scala, Ilya @lambdamix Kliuchnikov
Parsers Combinators in Scala, Ilya @lambdamix KliuchnikovParsers Combinators in Scala, Ilya @lambdamix Kliuchnikov
Parsers Combinators in Scala, Ilya @lambdamix Kliuchnikov
 
Go &lt;-> Ruby
Go &lt;-> RubyGo &lt;-> Ruby
Go &lt;-> Ruby
 
Mesics lecture 7 iteration and repetitive executions
Mesics lecture 7   iteration and repetitive executionsMesics lecture 7   iteration and repetitive executions
Mesics lecture 7 iteration and repetitive executions
 
Davide Cerbo - Kotlin: forse è la volta buona - Codemotion Milan 2017
Davide Cerbo - Kotlin: forse è la volta buona - Codemotion Milan 2017 Davide Cerbo - Kotlin: forse è la volta buona - Codemotion Milan 2017
Davide Cerbo - Kotlin: forse è la volta buona - Codemotion Milan 2017
 
Beyond javascript using the features of tomorrow
Beyond javascript   using the features of tomorrowBeyond javascript   using the features of tomorrow
Beyond javascript using the features of tomorrow
 
Lezione03
Lezione03Lezione03
Lezione03
 
Very interesting C programming Technical Questions
Very interesting C programming Technical Questions Very interesting C programming Technical Questions
Very interesting C programming Technical Questions
 
Clean code ch15
Clean code ch15Clean code ch15
Clean code ch15
 

Viewers also liked

Math1003 1.8 - Converting from Binary and Hex to Decimal
Math1003 1.8 - Converting from Binary and Hex to DecimalMath1003 1.8 - Converting from Binary and Hex to Decimal
Math1003 1.8 - Converting from Binary and Hex to Decimalgcmath1003
 
Storage devices used in cmp13to14
Storage devices used in cmp13to14Storage devices used in cmp13to14
Storage devices used in cmp13to14myrajendra
 
Bin to hexa.22to23
Bin to hexa.22to23Bin to hexa.22to23
Bin to hexa.22to23myrajendra
 
Fundamentals.1
Fundamentals.1Fundamentals.1
Fundamentals.1myrajendra
 
Hexa to binary
Hexa to binaryHexa to binary
Hexa to binarymyrajendra
 

Viewers also liked (7)

Math1003 1.8 - Converting from Binary and Hex to Decimal
Math1003 1.8 - Converting from Binary and Hex to DecimalMath1003 1.8 - Converting from Binary and Hex to Decimal
Math1003 1.8 - Converting from Binary and Hex to Decimal
 
Autoexec32(2)
Autoexec32(2)Autoexec32(2)
Autoexec32(2)
 
Storage devices used in cmp13to14
Storage devices used in cmp13to14Storage devices used in cmp13to14
Storage devices used in cmp13to14
 
Bin to hexa.22to23
Bin to hexa.22to23Bin to hexa.22to23
Bin to hexa.22to23
 
Fundamentals.1
Fundamentals.1Fundamentals.1
Fundamentals.1
 
Hexa to binary
Hexa to binaryHexa to binary
Hexa to binary
 
Number Systems
Number SystemsNumber Systems
Number Systems
 

Similar to 9 cm604.12

Similar to 9 cm604.12 (19)

06 Loops
06 Loops06 Loops
06 Loops
 
Java căn bản - Chapter6
Java căn bản - Chapter6Java căn bản - Chapter6
Java căn bản - Chapter6
 
Iteration
IterationIteration
Iteration
 
Embedded systems
Embedded systemsEmbedded systems
Embedded systems
 
130707833146508191
130707833146508191130707833146508191
130707833146508191
 
Lecture 3
Lecture 3Lecture 3
Lecture 3
 
MzTEK Programming - Part 3
MzTEK Programming - Part 3MzTEK Programming - Part 3
MzTEK Programming - Part 3
 
Lab 6
Lab 6Lab 6
Lab 6
 
Matlab Script - Loop Control
Matlab Script - Loop ControlMatlab Script - Loop Control
Matlab Script - Loop Control
 
4. loop
4. loop4. loop
4. loop
 
Control structures
Control structuresControl structures
Control structures
 
Lec7 - Loops updated.pptx
Lec7 - Loops updated.pptxLec7 - Loops updated.pptx
Lec7 - Loops updated.pptx
 
While loop
While loopWhile loop
While loop
 
Loops in c language
Loops in c languageLoops in c language
Loops in c language
 
Loops in c language
Loops in c languageLoops in c language
Loops in c language
 
C++ control structure
C++ control structureC++ control structure
C++ control structure
 
4th_Ed_Ch03.pdf
4th_Ed_Ch03.pdf4th_Ed_Ch03.pdf
4th_Ed_Ch03.pdf
 
Cs1123 6 loops
Cs1123 6 loopsCs1123 6 loops
Cs1123 6 loops
 
Programming in Java: Recursion
Programming in Java: RecursionProgramming in Java: Recursion
Programming in Java: Recursion
 

More from myrajendra (20)

Fundamentals
FundamentalsFundamentals
Fundamentals
 
Data type
Data typeData type
Data type
 
Hibernate example1
Hibernate example1Hibernate example1
Hibernate example1
 
Jdbc workflow
Jdbc workflowJdbc workflow
Jdbc workflow
 
2 jdbc drivers
2 jdbc drivers2 jdbc drivers
2 jdbc drivers
 
3 jdbc api
3 jdbc api3 jdbc api
3 jdbc api
 
4 jdbc step1
4 jdbc step14 jdbc step1
4 jdbc step1
 
Dao example
Dao exampleDao example
Dao example
 
Sessionex1
Sessionex1Sessionex1
Sessionex1
 
Internal
InternalInternal
Internal
 
3. elements
3. elements3. elements
3. elements
 
2. attributes
2. attributes2. attributes
2. attributes
 
1 introduction to html
1 introduction to html1 introduction to html
1 introduction to html
 
Headings
HeadingsHeadings
Headings
 
Forms
FormsForms
Forms
 
Css
CssCss
Css
 
Views
ViewsViews
Views
 
Views
ViewsViews
Views
 
Views
ViewsViews
Views
 
Starting jdbc
Starting jdbcStarting jdbc
Starting jdbc
 

9 cm604.12

  • 1. The syntax of the iterative statements of Java 1
  • 2. Objective On completion of this lecture you would be able to know • The various iteration statements in Java 2
  • 3. Recap In the previous class we have discussed • Various selection statements available in Java 3
  • 4. Iterative statements in Java • Java language provides three loop or iterative statements • They are • while statement • do statement • for statement 4
  • 5. The while Statement int sum = 0, number = 1; while ( number <= 100 ) { sum = sum + number; These statements are These statements are executed as long as number executed as long as number is less than or equal to 100. is less than or equal to 100. number = number + 1; } 5
  • 6. Syntax for the while Statement while ( <boolean expression> ) { <statement> } Boolean Expression Boolean Expression while ( number <= 100 ){ Statement Statement sum = sum + number; (loop body) (loop body) number = number + 1; } 6
  • 7. Control Flow of while int sum = 0, number = 11 int sum = 0, number = true number <= 100 ?? number <= 100 false sum = sum + number; sum = sum + number; number = number + 1; number = number + 1; 7
  • 8. while Loop Pitfall - 1 1 1 int product = 0; while ( product < 500000 ) { product = product * 5; } Infinite Loops Infinite Loops Both loops will not Both loops will not terminate because the terminate because the boolean expressions will boolean expressions will 2 2 int count = 1; never become false. never become false. while ( count != 10 ) { count = count + 2; } 8
  • 9. while Loop Pitfall - 2 1 1 float count = 0.0f; while ( count != 1.0f ) { count = count + 0.3333333f; } Using Real Numbers Using Real Numbers Loop 22terminates, but Loop 11 Loop terminates, but Loop does not because only an does not because only an approximation of aareal approximation of real number can be stored in aa 2 2 float count = 0.0f; number can be stored in computer memory. computer memory. while ( count <= 1.0f ) { count = count + 0.3333333f; } 9
  • 10. while Loop Pitfall - 3 • Goal: Execute the loop body 10 times. 1 count = 1; 1 2 count = 1; 2 while (count < 10) { while (count <= 10) { ... ... count++; count++; } } 3 count = 0; 3 4 count = 0; 4 while (count <= 10) { while (count < 10) { ... ... count++; count++; } } 1 and 3 exhibit off-by-one error. 1 3 10
  • 11. The do-while Statement int sum = 0, number = 1; do { These statements are These statements are sum += number; executed as long as sum is executed as long as sum is less than or equal to less than or equal to number++; 1,000,000. 1,000,000. } while ( sum <= 1000000 ); 11
  • 12. Syntax for the do-while Statement do { <statement> } while (<boolean expression>); do { sum += number; Statement Statement number++; (loop body) (loop body) } while (sum <= 1000000); Boolean Expression Boolean Expression 12
  • 13. Control Flow of do-while int sum = 0, number = 11 int sum = 0, number = sum += number; sum += number; number++; number++; true sum <= 1000000 ?? sum <= 1000000 false 13
  • 14. Pre-test vs. Post-test loops • Use a pre-test loop for something that may be done zero times • Use a post-test for something that is always done at least once 14
  • 15. Checklist for Repetition Control 1. Watch out for the off-by-one error (OBOE). 2. Make sure the loop body contains a statement that will eventually cause the loop to terminate. 3. Make sure the loop repeats exactly the correct number of times. 15
  • 16. Syntax of the for Statement for ( <initialization>; <boolean expression>; <update> ) <statement> Boolean Boolean Initialization Initialization Update Update Expression Expression for ( i=0 ; i < 20 ; i++ ){ number = inputBox.getInteger(); Statement Statement sum += number; (loop body) (loop body) } 16
  • 17. Control Flow of for ii= 0; = 0; ii< 20 ?? < 20 false true number = inputBox.getInteger( ); number = inputBox.getInteger( ); sum += number; sum += number; ii++; ++; 17
  • 18. The for Statement int i, sum = 0, number; for (i = 0; i < 20; i++) { number = inputBox.getInteger(); sum += number; } These statements are These statements are executed for 20 times executed for 20 times ((i i= 0, 1, 2, … , ,19). = 0, 1, 2, … 19). 18
  • 19. Indefinite vs. Definite loops • For loops and while loops are exchangeable • But use a for loop when the number of iterations are definite • Use a while or do-while when the number of iterations depends on statements in the loop body 19
  • 20. Summary In this class we have discussed • Various iterative statements available in Java 20
  • 21. Quiz 1.Which of the following loop is deterministic a) while b) do c) for d) all of the Above 21
  • 22. Quiz 2.If altering statement is missed in a loop, then it becomes a) fast loop b) deterministic loop c) non deterministic loop d) infinite loop 22
  • 23. Quiz 3.Minimum iteration for _______ loop is one. a) for b) while c) do d) all of these 23
  • 24. Assignment • Write a Java program to find factorial of a given no. • Write a Java program to find Fibonacci series. • Write a Java program to find whether the given no is prime or not. 24
  • 25. Frequently asked questions • List the various iterative statements available in Java • Explain the working of various iterative statements • Compare while with do statement • Compare while, do with for loop 25
  • 26.   swings   Struts jdbc hibernate home java previous question papers  OCT/NOV-2012 QUESTION PAPER April / May 2012 c-09 October/ November-2011 c-09 April/ May 2011 c-09 April/ May 2011 c-05 26

Editor's Notes

  1. Chapter 7 - There are basically two types of terminating the loop: 1. count-controlled and 2. sentinel-controlled. Count-controlled loops terminate the execution of the loop after the loop body is executed for a fixed number of times. Sentinel-controlled loops terminate the execution of the loop after one of the designated values called a sentinel is encountered.
  2. Chapter 7 -
  3. Chapter 7 -
  4. Chapter 7 - Note: In theory, this while statement is an infinite loop, but in programming languages other than Java, this loop will eventually terminate because of an overflow error. An overflow error will occur if you attempt to assign a value larger than the maximum value the variable can hold. When an overflow error occurs, the execution of the program is terminated in almost all programming languages. With Java, however, an overflow will not cause the program termination. When an overflow occurs in Java, a value that represents infinity (IEEE 754 infinity, to be precise) is assigned to a variable and no abnormal termination of a program will happen. Also, in Java an overflow occurs only with float and double variables; no overflow will happen with int variables. When you try to assign a value larger than the maximum possible integer an int variable can hold, the value “wraps around” and becomes a negative value. Whether the loop terminates or not because of an overflow error, the logic of the loop is still an infinite loop, and we must watch out for it. When you write a loop, you must make sure that the boolean expression of the loop will eventually become false.
  5. Chapter 7 - Although 1/3 + 1/3 + 1/3 == 1 is mathematically true, the expression 1.0/3.0 + 1.0/3.0 + 1.0/3.0 in computer language may or may not get evaluated to 1.0 depending on how precise the approximation is. In general, avoid using real numbers as counter variables because of this imprecision.
  6. Chapter 7 - Yes, you can write the desired loop as count = 1; while (count != 10 ) { ... count++; } but this condition for stopping the count-controlled loop is dangerous. We already mentioned about the potential trap of an infinite loop.
  7. Chapter 7 - The following is the routine presented earlier that inputs a person’s age using the do–while statement. do { age = inputBox.getInteger(&quot;Your Age (between 0 and 130):&quot;); if (age &lt; 0 || age &gt; 130) { messageBox.show(&quot;An invalid age was entered. &quot; + &quot;Please try again.&quot;); } } while (age &lt; 0 || age &gt; 130); This code is not as good as the version using the while statement it includes an if statement inside its loop body and the if test is repeating the same boolean expression of the do–while. Since the loop body is executed repeatedly, it is important not to include any extraneous statements. Moreover, duplicating the testing conditions tends to make the loop statement harder to understand. For this example, we can avoid the extra test inside the loop body and implement the control flow a little more clearly by using a while statement. In general, the while statement is more frequently used than the do–while statement.
  8. Chapter 7 -
  9. Chapter 7 -
  10. Chapter 7 -
  11. Chapter 7 -
  12. Chapter 7 - The &lt;initialization&gt; component also can include a declaration of the control variable. We can do something like this: for (int i = 0; i &lt; 10; i++) instead of int i; for (i = 0; i &lt; 10; i++)
  13. Chapter 7 -
  14. Chapter 7 -
  15. Chapter 7 -