Вы находитесь на странице: 1из 67

Loops

Loops are used to execute statements or blocks multiple times


based on a looping condition.
Java has three types of loops:
while loops
do while loops
for loops
Care should be taken whenever a loop is used to avoid an
endless loop.
while loops

The while loop is the most basic loop in Java.

while (boolean-expression)
{
statement1;
[...]
}

The loop body will continue to execute as long as the looping


condition is true. The looping condition is tested upon entry
and when the loop body is completed.
If the loop body consists of a single statement, the curly
braces are not necessary.
If the looping condition is false upon entry, the loop body will
not be executed.
Loop Components

Each loop has 4 main components

int x = 0; 1. Initialize loop variable

while ( x < 10) 2. Test loop variable


{
statement1; 3. Loop Body
[...]
x = x + 1; 4. Increment loop variable
}
while Loop Flow Chart
int count = 0;
while (loop-continuation-condition) {
while (count < 100) {
// loop-body;
System.out.println("Welcome to Java!");
Statement(s); count++;
} }
count = 0;

Loop
false false
Continuation (count < 100)?
Condition?

true true
Statement(s) System.out.println("Welcome to Java!");
(loop body) count++;

(A) (B)

5
animation

Trace while Loop


Initialize count
int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}

6
animation

Trace while Loop, cont.


(count < 2) is true
int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}

7
animation

Trace while Loop, cont.


Print Welcome to Java
int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}

8
animation

Trace while Loop, cont.


Increase count by 1
int count = 0; count is 1 now
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}

9
animation

Trace while Loop, cont.


(count < 2) is still true since count
int count = 0; is 1
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}

10
animation

Trace while Loop, cont.


Print Welcome to Java
int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}

11
animation

Trace while Loop, cont.


Increase count by 1
int count = 0; count is 2 now
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}

12
animation

Trace while Loop, cont.


(count < 2) is false since count is 2
int count = 0; now
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}

13
animation

Trace while Loop


The loop exits. Execute the next
int count = 0; statement after the loop.
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}

14
Trace while Loop

// Demonstrate the while loop.

class While {
public static void main(String args[]) {
int n = 10;
while(n > 0)
{
System.out.println("tick " + n);
n--;
}
}
}

15
Trace while Loop

// Demonstrate the while loop. tick 10


tick 9
class While { tick 8
public static void main(String args[]) { tick 7
int n = 10; tick 6
while(n > 0) tick 5
{ tick 4
System.out.println("tick " + n); tick 3
n--; tick 2
} tick 1
}
}

16
// The target of a loop can be empty.

class NoBody {
public static void main(String args[]) {
int i, j;
i = 100; Midpoint is 150
j = 200;
// find midpoint between i and j
while(++i < --j); // no body in this loop

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


}
}

17
Program to Reveres of a number
1.Program to Check Palindrome using while loop
public class Main {
public static void main(String[] args) {
int num = 1431, reversedInteger = 0, remainder; 2. Check Armstrong Number for 3 digit number
// reversed integer is stored in variable
while( num != 0 )
{ 3. Count Number of Digits in an Integer using while loop
remainder = num % 10;
reversedInteger = reversedInteger * 10 + remainder;
num /= 10; 4. Program to convert binary number to decimal
}
System.out.println("Reverse no is:"+reversedInteger);
} 5. Program to convert decimal number to binary
}

6. Find GCD of two numbers

Output:
Reverse no is:1341 7.Find LCM of two numbers
18
do while loops

The do-while loop is identical to the while loop except that the
test is evaluated at the end of the loop.
do
{
statement1;
[...]
} while (boolean-expression);

Because the looping condition is evaluated at the end of the


loop body, the loop body is guaranteed to execute at least
once.
1.do while loop starts with the execution of the statement(s). There is no checking of any condition
for the first time.

2.After the execution of the statements, and update of the variable value, the condition is checked
for true or false value. If it is evaluated to true, next iteration of loop starts.

3.When the condition becomes false, the loop terminates which marks the end of its life cycle.

4.It is important to note that the do-while loop will execute its statements atleast once before any
condition is checked, and therefore is an example of exit control loop.
// Demonstrate the do-while loop.
class DoWhile {
public static void main(String args[]) {
int n = 10;
do { do {
System.out.println("tick " + n); System.out.println("tick " + n);
n--; } while(--n > 0);
} while(n > 0);
}
}
class dowhileloopDemo
{
public static void main(String args[])
{
int x = 21;
do
{
// The line will be printed even
// if the condition is false
System.out.println("Value of x:" + x);
x++;
}
while (x < 20);
}
}
import java.util.Scanner;

class Sum {
public static void main(String[] args) {

Double number, sum = 0.0; 1.Write a program using do-while loop to print
Scanner input = new Scanner(System.in); Numbers and their cubes up to 10.
2.
do {
System.out.print("Enter a number: ");
number = input.nextDouble();
sum += number;
} while (number != 0.0);

System.out.println("Sum = " + sum);


}
}

Enter a number: 2.5


Enter a number: 23.3
Enter a number: -4.2
Enter a number: 3.4
Enter a number: 0
Sum = 25.0
class DoWhileBasics
{

public static void main(String args[])


{
int a=1;
do // 1st do while
{
System.out.print(1);
do// 2nd do while
{

System.out.print(2);

}
while(false);

}
while(false);

}
}
public class Main
{

public static void main(String args[])


{
int i=0,j;
do
{
j=1;
while(j<=3)
{
System.out.print(j);
j++;
}
System.out.println();

++i;
}
while(i<3);
}

}
// Using a do-while to process a menu selection
class Menu {
public static void main(String args[])
char choice;
do {
System.out.println("Help on: ");
System.out.println(" 1. if");
System.out.println(" 2. switch");
System.out.println(" 3. while");
System.out.println(" 4. do-while");
System.out.println(" 5. for\n");
System.out.println("Choose one:");
choice = (char) System.in.read();
} while( choice < '1' || choice > '5');
System.out.println("\n");
switch(choice) {
case '1':
System.out.println("The if:\n");
System.out.println("if(condition) statement;");
System.out.println("else statement;");
break;
case '2':
System.out.println("The switch:\n");
System.out.println("switch(expression) {");
System.out.println(" case constant:");
System.out.println(" statement sequence");
System.out.println(" break;");
System.out.println(" //...");
System.out.println("}"); Help on:
break; 1. if
case '3': 2. switch
System.out.println("The while:\n"); 3. while
System.out.println("while(condition) statement;"); 4. do-while
break; 5. for
case '4': Choose one:
System.out.println("The do-while:\n"); 4
System.out.println("do {"); The do-while:
System.out.println(" statement;"); do {
System.out.println("} while (condition);"); statement;
break; } while (condition);
case '5':
System.out.println("The for:\n");
System.out.print("for(init; condition; iteration)");
System.out.println(" statement;");
break;
}
Loops - Examples

What will these loops output?

int x = 0; int x = 0;
while(x<10) while(x<10)
{ {
System.out.println(x++); System.out.println(++x);
} }

int x = 0;
do
{
System.out.println(x);
x = x+1;
} while(x<10);
for loop
1.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.

2.Testing Condition: It is used for testing the exit condition for a loop. It must return a boolean value. It is
also an Entry Control Loop as the condition is checked prior to the execution of the loop statements.

3.Statement execution: Once the condition is evaluated to true, the statements in the loop body are
executed.

4.Increment/ Decrement: It is used for updating the variable for next iteration.

5.Loop termination:When the condition becomes false, the loop terminates marking the end of its life
cycle.
for loop

The syntax of the for loop makes the 4 parts of the loop
explicit.

int x = 0; 1. Initialize loop variable

while ( x < 10) 2. Test loop variable


{ for (i = 0; i < 10;
statement1; 3. Loop Body i++)
[...] {
x = x + 1; 4. Increment loop variable statement1;
} [...]
}
syntax:
for Loops
for (initial-action; loop- int i;
continuation-condition; for (i = 0; i < 100; i++) {
action-after-each-iteration) {
// loop body; System.out.println(
Statement(s); "Welcome to Java!");
} }

Initial-Action i=0

Loop
false false
Continuation (i < 100)?
Condition?
true true
Statement(s) System.out.println(
(loop body) "Welcome to Java");

Action-After-Each-Iteration i++

(A) (B)
32
animation

Trace for Loop


Declare i
int i;
for (i = 0; i < 2; i++) {
System.out.println(
"Welcome to Java!");
}

33
animation

Trace for Loop, cont.


Execute initializer
int i; i is now 0
for (i = 0; i < 2; i++) {
System.out.println(
"Welcome to Java!");
}

34
animation

Trace for Loop, cont.


(i < 2) is true
int i; since i is 0
for (i = 0; i < 2; i++) {
System.out.println( "Welcome to Java!");
}

35
animation

Trace for Loop, cont.


Print Welcome to Java
int i;
for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!");
}

36
animation

Trace for Loop, cont.


Execute adjustment statement
int i; i now is 1
for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!");
}

37
animation

Trace for Loop, cont.


(i < 2) is still true
int i; since i is 1
for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!");
}

38
animation

Trace for Loop, cont.


Print Welcome to Java
int i;
for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!");
}

39
animation

Trace for Loop, cont.


Execute adjustment statement
int i; i now is 2
for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!");
}

40
animation

Trace for Loop, cont.


(i < 2) is false
int i; since i is 2
for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!");
}

41
animation

Trace for Loop, cont.


Exit the loop. Execute the next
int i; statement after the loop
for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!");
}

42
class forLoopDemo
{
public static void main(String args[])
{
// for loop begins when x=2
// and runs till x <=4
for (int x = 2; x <= 4; x++)
System.out.println("Value of x:" + x);
}
}

Value of x:2
Value of x:3
Value of x:4
// Using the comma.

class Comma {
public static void main(String args[]) {
int a, b;
for(a=1, b=4; a<b; a++, b--)
{
System.out.println("a = " + a);
System.out.println("b = " + b);
}
}
}

Output
a=1
b=4
a=2
b=3
Here is another interesting for loop variation. Either the initialization or
the iteration expression or both may be absent, as in this next program:
// Parts of the for loop can be empty.

class ForVar {
public static void main(String args[]) {
int i;
boolean done = false;
i = 0;
for( ; !done; )
{
System.out.println("i is " + i);
if(i == 10)
done = true;
i++;
}
}
}
class ForLoopExample {
public static void main(String args[]){
for(int i=10; i>1; i--)
{
System.out.println("The value of i is: "+i);
}
}
}

The value of i is: 10


The value of i is: 9
The value of i is: 8
The value of i is: 7
The value of i is: 6
The value of i is: 5
The value of i is: 4
The value of i is: 3
The value of i is: 2
Program to calculate the sum of natural numbers using for loop
public class Demo {

public static void main(String[] args) {

int num = 10, count, total = 0;

for(count = 1; count <= num; count++){


total = total + count;
}

System.out.println("Sum of first 10 natural numbers is: "+total);


}
}

Output:
Sum of first 10 natural numbers is: 55
public class JavaExample {

public static void main(String[] args) {

//We will find the factorial of this number


int number = 5;
long fact = 1;
for(int i = 1; i <= number; i++)
{
fact = fact * i;
}
System.out.println("Factorial of "+number+" is: "+fact);
}
}

Output:
Factorial of 5 is: 120
public class JavaExample {

public static void main(String[] args) {

int count = 7, num1 = 0, num2 = 1;


System.out.print("Fibonacci Series of "+count+"
numbers:");

for (int i = 1; i <= count; ++i)


{
System.out.print(num1+" ");

/* On each iteration, we are assigning second number


* to the first number and assigning the sum of last two
* numbers to the second number
*/
int sumOfPrevTwo = num1 + num2;
num1 = num2;
num2 = sumOfPrevTwo;
}
}
}
Output:Fibonacci Series of 7 numbers:0 1 1 2 3 5 8
// Test for primes.
class FindPrime {
public static void main(String args[]) {
int num;
boolean isPrime;
num = 14;
if(num < 2)
isPrime = false;
else
isPrime = true;
for(int i=2; i <= num/i; i++)
{
if((num % i) == 0)
{
isPrime = false;
break;
}
}
if(isPrime)
System.out.println("Prime");
else
System.out.println("Not Prime");
}
}
for (initialization; test condition; increment/decrement operator) { //First For Loop
for (initialization; test condition; increment/decrement operator) { // Second For Loop
//Second For Loop Statements
Statement 1
Statement 2
………
Statement n
}
//First For Loop Statements
Statement 1
………
Statement n
}
Step 1: First, Compiler will check for the condition inside the first for loop.

If the condition is True then statements inside the For loop will be executed. It means, compiler will enter into
second For loop. Goto Step 2
If the condition is False then, compiler will exit from For Loop

Step 2: Compiler will check for the condition inside the second for loop.
If the condition is True then statements inside the second For loop will be executed. It means, it will execute
from Statement 1 to N.
If the condition is False then, compiler will exit from second For Loop

Step 3: Once it exit from second for loop, compiler will check for the condition inside the for loop (repeating
Step 1 )
Nested Loops
Java allows loops to be nested. That is, one loop may be inside another. For example,
here is a program that nests for loops:
// Loops may be nested.
class Nested {
public static void main(String args[]) {
int i, j;
for(i=0; i<10; i++)
{
for(j=i; j<10; j++)
System.out.print("."); The output produced by this program is shown here:
System.out.println(); ..........
} .........
} ........
} .......
......
.....
....
...
..
.
class NestedLoop {
public static void main(String[] args) {
Outer loop iteration 1
i = 1; j = 1
int i = 1;
i = 1; j = 2
Outer loop iteration 2
while (i <= 5) {
i = 2; j = 1
i = 2; j = 2
System.out.println("Outer loop iteration " + i);
Outer loop iteration 3
i = 3; j = 1
for (int j = 1; j <= 2; ++j) {
i = 3; j = 2
System.out.println("i = " + i + "; j = " + j);
Outer loop iteration 4
}
i = 4; j = 1
i = 4; j = 2
++i;
Outer loop iteration 5
}
i = 5; j = 1
}
i = 5; j = 2
}
class Pattern {
public static void main(String[] args) {

int rows = 5;

for(int i = 1; i <= rows; ++i)


{
for(int j = 1; j <= i; ++j)
{
System.out.print(j + " ");
}
System.out.println("");
}
}
}
class Pattern {
public static void main(String[] args) {

int rows = 5;

for(int i = 1; i <= rows; ++i) 1


{ 12
for(int j = 1; j <= i; ++j) 123
{ 1234
System.out.print(j + " "); 12345
}
System.out.println("");
}
}
}
public class Pattern1
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter number of rows: ");

int rows = sc.nextInt();

System.out.println("Here is your pattern....!!!");

for (int i = rows; i >= 1; i--)


{
for (int j = i; j >= 1; j--)
{
System.out.print(j+" "); Output
}

System.out.println(); 54321
} 4321
sc.close(); 321
} 21
} 1
import java.util.Scanner;
public class Pattern4
{
public static void main(String[] args) System.out.println();
{ }
Scanner sc = new Scanner(System.in);
System.out.print("Enter number of rows: "); }
}
int rows = sc.nextInt();

System.out.println("Here is your pattern....!!!");

for (int i = 1; i <= rows; i++)


{
for (int j = 1; j <= i; j++)
{
if(j%2 == 0)
{
System.out.print(0);
} 1
else 10
{ 101
System.out.print(1); 1010
} 10101
}
public class PrintPattern
{
public static void main(String args[])
{
int space=4;
for(int i=1; i<=5; i++)
{
//print spaces
for(int j=1; j<=space;j++)
*
System.out.print(" ");
**
***
//print stars
****
for(int j=1; j<=i; j++)
*****
System.out.print("* ");

//print new line


System.out.println();
space--;

}
}
}
class Test {
public static void main(String[] args) {
1
for (int i = 1; i <= 10; ++i) { 2
if (i == 5) { 3
break; 4
}
System.out.println(i);
}
}
}
import java.util.Scanner;

class UserInputSum {
public static void main(String[] args) {

Double number, sum = 0.0;


Scanner input = new Scanner(System.in);

while (true) { Enter a number: 3.2


System.out.print("Enter a number: "); Enter a number: 5
number = input.nextDouble(); Enter a number: 2.3
Enter a number: 0
if (number < 0.0) { Enter a number: -4.5
break; Sum = 10.5
}

sum += number;
}
System.out.println("Sum = " + sum);
}
}
class Test {
public static void main(String[] args) {

for (int i = 1; i <= 10; ++i) {


if (i > 4 && i < 9) {
continue;
}
System.out.println(i);
}
}
}

1
2
​ 3
4
9
10
import java.util.Scanner;

class AssignmentOperator {
public static void main(String[] args) {

Double number, sum = 0.0;


Scanner input = new Scanner(System.in);
Enter a number: 2.2
for (int i = 1; i < 6; ++i) {
Enter a number: 5.6
System.out.print("Enter a number: ");
Enter a number: 0
number = input.nextDouble();
Enter a number: -2.4
Enter a number: -3
if (number <= 0.0) {
Sum = 7.8
continue;
}

sum += number;
}
System.out.println("Sum = " + sum);
}
}
For nested loop

https://www.programiz.com/java-programming/continue-statement

https://www.programiz.com/java-programming/break-statement

http://www.beginwithjava.com/java/loops/break-continue-statement.html

Вам также может понравиться