[Go to site: main page, start]

0% found this document useful (0 votes)
153 views7 pages

Java Looping Statements and Examples

The document discusses various looping statements in Java including for, while, do-while loops and nested loops. It provides examples of using these loops to print numbers, patterns and traverse arrays. Key points covered include using a for loop to print numbers from 1 to 10, nested for loops to print multiple values, and using a do-while loop where the condition is checked at the end of each iteration. Labeled loops and infinite loops are also demonstrated.

Uploaded by

Rajesh Kumar
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
153 views7 pages

Java Looping Statements and Examples

The document discusses various looping statements in Java including for, while, do-while loops and nested loops. It provides examples of using these loops to print numbers, patterns and traverse arrays. Key points covered include using a for loop to print numbers from 1 to 10, nested for loops to print multiple values, and using a do-while loop where the condition is checked at the end of each iteration. Labeled loops and infinite loops are also demonstrated.

Uploaded by

Rajesh Kumar
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Looping or iterative Statements

Exercise:- Write a program to print number from 1 to 10 for


loop.(Use of simple for loop).

[Link]

//Java Program to demonstrate the example of for loop


//which prints table of 1
public class ForExample {
public static void main(String[] args) {
//Code of Java for loop
for(int i=1;i<=10;i++){
[Link](i);
}
}
}

Output:

1
2
3
4
5
6
7
8
9
10

Exercise:- Write a Java program to show working of nested for


loop.

[Link]

public class NestedForExample {


public static void main(String[] args) {
//loop of i
for(int i=1;i<=3;i++){
//loop of j
for(int j=1;j<=3;j++){
[Link](i+" "+j);
}//end of i
}//end of j
}
}

Output:

1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3

Exercise:- Write a Java program to print a pyramid pattern of stars


using nested for loop.

[Link]

public class PyramidExample2 {


public static void main(String[] args) {
int term=6;
for(int i=1;i<=term;i++){
for(int j=term;j>=i;j--){ // use (int j=term;j<=term;j++) for ascending pattern
[Link]("* ");
}
[Link]();//new line
}
}
}

Output:

* * * * * *
* * * * *
* * * *
* * *
* *
*
Exercise:- Program to access array elements using for each
loop.

It is easier to use for-each loop to traverse array or collection in Java

Syntax:

for(data_type variable : array_name){


//code to be executed
}

[Link]

//Java For-each loop example which prints the


//elements of the array
public class ForEachExample {
public static void main(String[] args) {
//Declaring an array
int arr[]={12,23,44,56,78};
//Printing array using for-each loop
for(int i:arr){
[Link](i);
}
}
}

Output:

12
23
44
56
78

Java Labeled For Loop


We can have a name of each Java for loop. To do so, we use label before the for loop.
It is useful while using the nested for loop as we can break/continue specific for loop.

Note: The break and continue keywords breaks or continues the innermost for loop
respectively.

Syntax:
1. labelname:
2. for(initialization; condition; increment/decrement){
3. //code to be executed
4. }

[Link]

public class LabeledForExample2 {


public static void main(String[] args) {
aa:
for(int i=1;i<=3;i++){
bb:
for(int j=1;j<=3;j++){
if(i==2&&j==2){
break bb;
}
[Link](i+" "+j);
}
}
}
}

Output:

1 1
1 2
1 3
2 1
3 1
3 2
3 3

Exercise:- Program in java to show use of Java Infinitive for Loop.


[Link]

//Java program to demonstrate the use of infinite for loop


//which prints an statement
public class ForExampleInfinite {
public static void main(String[] args) {
//Using no condition in for loop
for(;;){
[Link]("infinitive loop");
}
}
}

Output:

infinitive loop
infinitive loop
infinitive loop
infinitive loop
infinitive loop
ctrl+c

Now, you need to press ctrl+c to exit from the program.

While and Do …while loops


Exercise:- Write Java program to show use of while loop.
[Link]

public class WhileExample {


public static void main(String[] args) {
int i=1;
while(i<=10){
[Link](i);
i++;
}
}
}

Output:

1
2
3
4
5
6
7
8
9
10
Exercise:- Write Java program to show use of Infinitive While
Loop.

If you pass true in the while loop, it will be infinitive while loop.

Syntax:

while(true){
//code to be executed
}

[Link]

1. public class WhileExample2 {


2. public static void main(String[] args) {
3. // setting the infinite while loop by passing true to the condition
4. while(true){
5. [Link]("infinitive while loop");
6. }
7. }
8. }

Output:

infinitive while loop


infinitive while loop
infinitive while loop
infinitive while loop
infinitive while loop
ctrl+c

In the above code, we need to enter Ctrl + C command to terminate the infinite loop.

Exercise:- Write program in java to show use of do …. while loop.


[Link]

public class DoWhileExample {


public static void main(String[] args) {
int i=1; // if we use 11 then loop will execute once as condition tested in end.
do{
[Link](i);
i++;
}while(i<=10);
}
}

Output:

1
2
3
4
5
6
7
8
9
10

Common questions

Powered by AI

Understanding infinite loops educates programmers about control flow and resource management, as infinite loops that lack proper exit conditions can exhaust CPU resources, leading to software crashes or freezes . This comprehension aids in developing robust applications where loops are guarded with appropriate exit strategies and conditions. Recognizing potential pitfalls of infinite loops fosters skills in defensive programming, ensuring explicit conditions and safer execution.

Both infinite 'for' and 'while' loops run indefinitely, but their syntax varies. An infinite 'for' loop lacks specific initialization, condition, and increment sections, using 'for(;;)' to indicate indefinite execution . An infinite 'while' loop simply continues with 'while(true)' . Practically, infinite loops might be used for server listening or waiting for user input until a condition explicitly breaks the loop. However, the clearer and more typical structure for testing or integration into event-driven scenarios makes 'while(true)' simpler to align with expected conditions.

The 'break' statement immediately terminates the closest enclosing loop, bypassing any remaining iterations, which is useful for exiting early when a specific condition is met . Misusing 'break', such as using it excessively or inappropriately in non-critical logic, can prematurely terminate loops, causing logic errors that might skip necessary iterations or leave the program in an unexpected state, reducing the program's correctness and maintainability.

Manipulating loop variables in Java for loops allows generating algorithmic patterns by dynamically altering iteration step sizes, directions, or conditions. For instance, varying increment/decrement values can create asymmetrical patterns or simulate algorithm states, while adjusting loop ranges to specific problem needs leads to complex yet optimized solutions like producing diamond shapes or conforming loops to non-linear sequences for pattern construction .

In a 'while' loop, the condition is evaluated before the loop body is executed. This means that if the condition is false at the start, the loop body might never execute . Conversely, in a 'do-while' loop, the loop body is executed at least once before the condition is evaluated, since the condition is checked after execution . These differences affect program execution by ensuring at least one execution in 'do-while' loops, whereas 'while' loops might not execute even once if their condition is not met initially.

Nested for loops excel in scenarios requiring structured, multi-dimensional iteration such as matrix operations, pattern printing, or grid-based calculations, where tasks are iterative and predictable . Compared to recursion, which is used for problems solvable by breaking them into similar sub-problems such as tree traversals or factorial calculations, nested loops consume less stack space because they avoid the overhead of multiple function calls. However, recursion can offer more elegant solutions for problems with recursive natural structure, though at the risk of stack overflows with deep recursion levels .

Printing patterns using nested loops, such as pyramids of stars, demonstrate computational thinking by breaking down complex visual structures into repeatable sub-problems—each loop level typically represents a pattern component . Efficient pattern printing requires understanding iteration limits and control of outputs, teaching programmers to minimize computations through logical decreases or increases in iteration counts, ensuring reduced execution time and improved readability of code .

Accessing array elements efficiently requires understanding how different loops handle iteration and traversal. Using a for-each loop abstracts element access, focusing on element values without index management, providing cleaner and less error-prone code for sequential access . Traditional for loops, by allowing index manipulation, offer control over access patterns and modifications. Efficiency gains emerge from matching loop choice to task complexity, ensuring optimal performance without compromising on maintainability .

A labeled for loop in Java allows programmers to specify a loop's label name, making it easier to control the flow, especially in nested loops . When breaking or continuing loops, you can use the label to specify exactly which loop to affect, thus adding a layer of control over which particular loop iteration should break or continue, improving readability and manageability of complex nested iterations .

The for-each loop simplifies array traversal by abstracting index management, iterating directly over elements, which reduces the chance of errors related to indices . However, its main limitation is inflexibility; it doesn't allow modifying the underlying array or accessing index numbers directly, which can be necessary for certain algorithms that require index manipulation or multi-dimensional array processing, unlike the traditional for loop .

You might also like