Docsity

Java Iteration Statements: While, For, and Do-While Loops, Study notes of Java Programming

Partial preview of the text

Download Java Iteration Statements: While, For, and Do-While Loops and more Study notes Java Programming in PDF only on Docsity!

JAVA

ITERATION

STATEMENTS 1.While Loop

2.For Loop

3.Do-While Loop

Iteration Statement/Looping Statements

❖ Looping in programming languages is a feature which facilitates the execution of a set of instructions/functions repeatedly while some condition evaluates to true.

❖ Java provides three ways for executing the loops.

❖ While all the ways provide similar basic functionality , they differ in their syntax and condition checking time.

1.While Loop

❖ while loop: A while loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition.

❖ The while loop can be thought of as a repeating if statement.

Syntax : while (Boolean condition) { loop statements... }

1.While Loop

Program to demonstrate the while loop

class whileLoopDemo { public static void main(String args[]) { int x = 1; while (x <= 4) { System.out.println("Value of x: " + x); x++; } } } Output: Value of x: 1 Value of x: 2 Value of x: 3 Value of x: 4

2.For Loop

❖ for loop: for loop provides a concise way of writing the loop structure.

❖ Unlike a while loop, a for statement consumes the initialization, condition and increment/decrement in one line thereby providing a shorter , easy to debug structure of looping.

Syntax:

for (initialization condition; testing condition;

increment/decrement)

{ statement(s) }

2.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.

2.For Loop

❖ 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.

3.Do-While Loop

❖ do while: do while loop is similar to while loop with only difference that it checks for condition after executing the statements , and therefore is an example of Exit Control Loop****.

Syntax: do { statements.. } while (condition);

3.Do-While Loop

Program to demonstrate the do-while loop

class dowhileloopDemo { public static void main(String args[]) { int x = 21; do { System.out.println("Value of x: " + x); x++; } while (x < 20); } }

Output: Value of x: 21