Download as pdf or txt
Download as pdf or txt
You are on page 1of 33

Chapter 4: Iteration and loops

Iteration and loops


2

 Computers are often used to automate repetitive tasks.


This process is called loop. The code that is repeated in a
loop is called the body of the loop. Each repetition of the
loop body is called an iteration of the loop.

 An if statement will execute once if a condition is true but


loop will run as many times as it needs to while a
condition is true.

 The three Java loop statements are:


 while statement.
 do-while statement.
 for statement.
while Statement
3

 In while statement, the Boolean expression is


checked before the loop body is executed.

int number=1;
while (number <10)
{
System.out.println(”number=”+number);
number=number+1;
}
Output
4
do-while statement
5

 In do-while statement, the Boolean expression is


checked after the loop body is executed.

int number=1;
do
{
System.out.println("number="+number);
number=number+1;
}
while (number <10);
Output
6
Difference between while & do while
7
 When Boolean expression is  Even with same while condition
False while loop statements used in do-while, do-while loop
are not executed even once. statements are at least
executed once.

int n= 3; int n= 3;
   while(n < 3) {  do  {
System.out.println(“n= “+ n); System.out.println(“n= " + n);
                 n=n+1;                  n=n+1;
          }           }
while(n < 3);
for loops
8

 for loops is so common in programming.


 It start by initializing a variable; a condition, that
depends on that variable; and inside the loop they do
something to that variable, like increment it.
 Syntax:
for (INITIALIZER; CONDITION; INCREMENTOR) {
BODY
}
Semantics of the for Statement
9
Example
10

for (int i = 0; i < 4; i++) {


System.out.println(i);
}
Nested Loops
11

 Loops can be nested, just like other Java structures


 When nested, the inner loop iterates from beginning to end for each
single iteration of the outer loop

int rowNum, columnNum;


for (rowNum = 1; rowNum <=3; rowNum++)
{
for (columnNum = 1; columnNum <=2;
columnNum++)
System.out.print(" row " + rowNum +
" column " + columnNum);
System.out.println();
}
Increment and decrement operators
12

 Incrementing and decrementing are such common


operations that Java provides special operators for them.
 The ++ operator adds one to the current value of an int or
char.
 -- subtracts one.
 So both below expressions are same:
number=number+1 OR number++
 Neither operator works on doubles, booleans or Strings.
Difference between i++ and ++i
13

 Both of them increase the variable i by one.


 for (int i = 0; i < 100; i++)
 for (int i = 0; i < 100; ++i)

 i++ and ++i are very similar but not exactly the same.


 
14

 ++i increments the number before the current


expression is evaluted,
 i++ increments the number after the expression is
evaluated.
int a = 0;
int b = a++; // b = 0; a = 1
a = 0;
b = ++a: // b = 1; a = 1
Exercises
15

 Write a Java Program to print numbers from 10 to 1


using while statement.
 Do the same using for loop.
Infinite Loops
16

 A while, do-while, or for loop should be designed so that


the value tested in the Boolean expression is changed in a
way that eventually makes it false, and terminates the loop
 If the Boolean expression remains true, then the loop will
run forever, resulting in an infinite loop
 Loops that check for equality or inequality (== or !=) are
especially prone to this error and should be avoided if
possible
Example
17

int x=3;
for (int i = 0; x == 3; i++) {
System.out.println(i);
}
//the condition x==3 is always true.
Jump Statements
18

 In Java jump statements are mainly used to transfer


control to another part of our program depending on the
conditions. 
 These statements can be used to jump directly to other
statements, skip a specific statement to prevent program
from running forever.
if (x%2==0)
x=x+2; // it will be increment x when condition is true forever.
 In Java we have the following three jump statements:
1. break
2. continue
3. return
The break statement
19

 If we want to go out of a loop then we use a break


statement.
 If we use a break statement in a loop then execution
will continue with the immediate next statement
outside the loop.
 After a break, all the remaining statements in the
loop are skipped (terminated). The break statement
can be used in a while loop, for loop, and do-while
loop.
Example
20

class Myclass1
{ Output:
   public static void main(String args[])
   { 1
      int n = 1; 2
      while (n<=15)
      {
3
         System.out.println(n); 4
         n++; 5
         if (n==7)
         { 6
            break;
         }
      }
   }
}
The continue statement
21

 continue does not terminate the loop, it just skips


some part of the loop.
 When we do not want to execute some statements
then we use a continue statement to skip those
statements from execution.
 If the continue statement is confronted in the
program then it will start the next iteration.
Example
22

public static void main(String[] args) {  
    //for loop   Output:
    for(int i=1;i<=10;i++){   1
        if(i==5){   2
            //using continue statement   3
4
            continue;//it will skip the rest statement  
6
        }   7
        System.out.println(i);   8
    }   9
}   10
}  
The return statement
23

 The return statement is used to end the execution of


a specific method and then return a value.
 It is used to exit from a method, with or without a
value.
 The data type of the returned value should always
be equal to the data type of the method's declared
return value. (Methods will be covered in chapter#6)
Example
24

for(int i=1;i<=10;i++){  
        if(i==5){    
     return;
// it will terminate the loop  
        }  
Output:
        System.out.println(i);   1
    }   2
3
}   4
}  
The exit Statement
25

 A break statement will end a loop or switch


statement, but will not end the program
 The exit statement will immediately end the
program as soon as it is invoked:
System.exit(0);
 The exit statement takes one integer argument
 By tradition, a zero argument is used to indicate a normal
ending of the program
Exercises
26

 Write a program to print only numbers from 1 to 100


excluding numbers are divisible by 7.
 Write a program to print numbers from 1 to 100 and
stop printing when the number is divisible by 7.
Glossary Review
27

1. Loop
2. Infinite loop
3. Body
Knowledge Check
28

 Describe the output the following for loop

public static void main(String []args){

for (char ch = 'a' ; ch <= 'z' ; ch++)


System.out.println(ch);
}
The output:
abcdefghijklmnopqrstuvwxyz
29

 Write a for loop to print the multiplication table of 3.


Answer
30

public static void main(String []args){


int a=3;

for (int n = 0 ; n <= 10 ; n++)


System.out.println(a*n);

}
31

 Do the same using while loop.


Answer
32

public static void main(String []args){

int a=3;
int b=0;

while (b<=10)
{
System.out.println(a*b);
b++;
}
}
33

Questions?!

You might also like