0% found this document useful (0 votes)
9 views

Loops

Uploaded by

Nishant Sinha
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Loops

Uploaded by

Nishant Sinha
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

case 3:

dayString = "Wednesday";
break;
case 4:
dayString = "Thursday";
break;
case 5:
dayString = "Friday";
break;
case 6:
dayString = "Saturday";
break;
case 7:
dayString = "Sunday";
break;
default:
dayString = "Invalid day";
}
System.out.println(dayString);
} }
When Java reaches a break keyword, it breaks out of the switch block.
This will stop the execution of more code and case testing inside the block.
When a match is found, and the job is done, it's time for a break. There is
no need for more testing

Loops in Java
In computer programming, loops are used to repeat a block of code. For example, if you want to
show a message 100 times, then rather than typing the same code 100 times, you can use a
loop.
In Java, there are three types of loops.
1. for loop
2. while loop
3. do...while loop

21
Java for Loop
Syntax:
for (initialization condition; testing condition; increment/decrement)
{
statement(s)
}
Initialization condition: Here, we initialize the variable in use. It marks the start of a for loop. An
already declared variable can be used or a variable can be declared, local to loop only.
Testing Condition: It is used for testing the exit condition for a loop.
Statement execution: Once the condition is evaluated to true, the statements in the loop body
are executed.
Increment/ Decrement: It is used for updating the variable for next iteration.
Loop termination:When the condition becomes false, the loop terminates marking the end of
its life cycle.

// Example 1: Program to print a text 5 times


class Main {
public static void main(String[] args) {
int n = 5;
// for loop
for (int i = 1; i <= n; ++i) {
System.out.println("Java is fun");
}
}
}
Output

Java is fun
Java is fun
Java is fun
Java is fun
Java is fun

22
Iteration Variable Condition: i <= n Action

i = 1 Java is fun is printed.


1st true
n = 5 i is increased to 2.

i = 2 Java is fun is printed.


2nd true
n = 5 i is increased to 3.

i = 3 Java is fun is printed.


3rd true
n = 5 i is increased to 4.

i = 4 Java is fun is printed.


4th true
n = 5 i is increased to 5.

i = 5 Java is fun is printed.


5th true
n = 5 i is increased to 6.

i = 6
6th false The loop is terminated.
n = 5

// Example 2: Program to print numbers from 1 to 5


class Main {
public static void main(String[] args) {
int n = 5;
// for loop
for (int i = 1; i <= n; ++i) {
System.out.println(i);
}
}
}
Here is how the program works.

Iteration Variable Condition: i <= n Action

i = 1 1 is printed.
1st true
n = 5 i is increased to 2.

i = 2 2 is printed.
2nd true
n = 5 i is increased to 3.

i = 3 3 is printed.
3rd true
n = 5 i is increased to 4.

23
i = 4 4 is printed.
4th true
n = 5 i is increased to 5.

i = 5 5 is printed.
5th true
n = 5 i is increased to 6.

i = 6
6th false The loop is terminated.
n = 5

Example 3: Display Sum of n Natural Numbers


class Main {
public static void main(String[] args) {
int sum = 0;
int n = 1000;
// for loop
for (int i = 1; i <= n; ++i) {
// body inside for loop
sum += i; // sum = sum + i
}
System.out.println("Sum = " + sum);
}
}

Output:
Sum = 500500
int a, b;
for (a = 6, b = 4; a <= 24; a = a + 6)
{
if (a % b == 0)
break;
}
System.out.println(a);
Output:
12

Example :Java Infinite for Loop


If we set the test expression in such a way that it never evaluates to false, the for loop will run
forever. This is called infinite for loop.

24
// Infinite for Loop
class Infinite {
public static void main(String[] args) {
int sum = 0;
for (int i = 1; i <= 10; --i) {
System.out.println("Hello");
}
} Here, the test expression, i <= 10, is
never false and Hello is printed
}
repeatedly until the memory runs out.

Java for-each Loop


The Java for loop has an alternative syntax that makes it easy to iterate through arrays and
collections. It is also known as the enhanced for loop.
// print array elements
Example 1:
class Main {
public static void main(String[] args) {

// create an array
int[] numbers = {3, 7, 5, -5};

// iterating through the array


for (int number: numbers) {
In the first iteration of the
System.out.println(number);
} loop, number will be 3, number will
} be 7 in second iteration and so on.
}
Output

3
7
5
-5

Example 2: Sum of Array Elements


25
class Main {
public static void main(String[] args) {
int[] numbers = {3, 4, 5, -5, 0, 12};
int sum = 0;
// iterating through each element of the array
for (int number: numbers) {
sum += number;
}
System.out.println("Sum = " + sum);
}
}
Output:
Sum = 19
In the above program, the execution of the for each loop looks as:

Iteration Variables

number = 3
1
sum = 0 + 3 = 3

number = 4
2
sum = 3 + 4 = 7

number = 5
3
sum = 7 + 5 = 12

number = -5
4
sum = 12 + (-5) = 7

number = 0
5
sum = 7 + 0 = 7

number = 12
6
sum = 7 + 12 = 19

for loop Vs for-each loop


Let's see how a for-each loop is different from a regular Java for loop.

Using for loop

26
class Main {
public static void main(String[] args) {
char[] vowels = {'a', 'e', 'i', 'o', 'u'};
for (int i = 0; i < vowels.length; ++ i) {
Output:
System.out.println(vowels[i]);
a
}}}
e
Using for-each Loop
i
class Main {
o
public static void main(String[] args) {
u
char[] vowels = {'a', 'e', 'i', 'o', 'u'};
for (char item: vowels) {
System.out.println(item);
}
}
}

Java while loop


Java while loop is used to run a specific code until a certain condition is met. The syntax of the
while loop is:
while (condition) {
// body of loop
}
Example 1: Display Numbers from 1 to 5
class Main {
Output
public static void main(String[] args) {
1
int i = 1, n = 5;
2
while(i <= n) {
System.out.println(i); 3
i++; 4
} 5
}
}

Here is how this program works.

27
Iteration Variable Condition: i <= n Action

i = 1 1 is printed.
1st true
n = 5 i is increased to 2.

i = 2 2 is printed.
2nd true
n = 5 i is increased to 3.

i = 3 3 is printed.
3rd true
n = 5 i is increased to 4.

i = 4 4 is printed.
4th true
n = 5 i is increased to 5.

i = 5 5 is printed.
5th true
n = 5 i is increased to 6.

i = 6
6th false The loop is terminated
n = 5

Java do...while loop


The do...while loop is similar to while loop. However, the body of do...while loop is executed
once before the test expression is checked. For example,
do {
// body of loop
} while(textExpression);
Display Numbers from 1 to 5
// Java Program to display numbers from 1 to 5
class Main {
public static void main(String[] args) {
int i = 1, n = 5;
// do...while loop from 1 to 5
do {
System.out.println(i);
i++;
} while(i <= n);
}
}
Here is how this program works.

28
Iteration Variable Condition: i <= n Action

i = 1 1 is printed.
not checked
n = 5 i is increased to 2.

i = 2 2 is printed.
1st true
n = 5 i is increased to 3.

i = 3 3 is printed.
2nd true
n = 5 i is increased to 4.

i = 4 4 is printed.
3rd true
n = 5 i is increased to 5.

i = 5 6 is printed.
4th true
n = 5 i is increased to 6.

i = 6
5th false The loop is terminated
n = 5

Infinite loop
If the condition of a loop is always true , the loop runs for infinite times (until the memory is
full). For example,
// infinite while loop
while(true){
// body of loop
}
Here is an example of an infinite do...while loop.
// infinite do...while loop
int count = 1;
do {
// body of loop
} while(count == 1)

29
Java break statement
class Test {
public static void main(String[] args) {
// for loop
for (int i = 1; i <= 10; ++i) {
// if the value of i is 5 the loop terminates
if (i == 5) {
break;
}
Output:
System.out.println(i);
1
}
2
}
} 3
4
Java break and Nested Loop
In the case of nested loops, the break statement terminates the innermost loop.

Here, the break statement terminates the innermost while loop, and control jumps to the outer loop.
Labeled break Statement
We can use the labeled break statement to terminate the outermost loop as well.

As you can see in the above image, we have used the label identifier to specify the outer loop.
Now, notice how the break statement is used ( break label; ).
30
Here, the break statement is terminating the labeled statement (i.e. outer loop).
Example : labeled break Statement
class LabeledBreak {
public static void main(String[] args) {
// the for loop is labeled as first
first:
for( int i = 1; i < 5; i++) {
// the for loop is labeled as second
second:
for(int j = 1; j < 3; j ++ ) {
System.out.println("i = " + i + "; j = " +j);
// the break statement breaks the first for loop
if ( i == 2)
break first; Output:
} i = 1; j = 1
} i = 1; j = 2
} i = 2; j = 1
}

Java continue Statement


The continue statement skips the current iteration of a loop.
Note: The continue statement is almost always used in decision-making statements (if...else
Statement).
Example : Java continue statement
class Main {
public static void main(String[] args) {
for (int i = 1; i <= 10; ++i) {
if (i > 4 && i < 9) { Output:
continue; 1
} 2
System.out.println(i); 3
} 4
} 9
} 10

31

You might also like