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

9 JAVA For Loop in Java With Example TESDA NC III

The document discusses for loops in Java. It explains the syntax and flow of execution of a basic for loop. The initialization step runs once at the start, then the condition is evaluated on each iteration. If true, the body runs, otherwise it exits the loop. The increment/decrement step runs after each body execution to update the counter before re-evaluating the condition. Examples show using a for loop to iterate through arrays and print values. Enhanced for loops provide an easier way to iterate through arrays and collections.

Uploaded by

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

9 JAVA For Loop in Java With Example TESDA NC III

The document discusses for loops in Java. It explains the syntax and flow of execution of a basic for loop. The initialization step runs once at the start, then the condition is evaluated on each iteration. If true, the body runs, otherwise it exits the loop. The increment/decrement step runs after each body execution to update the counter before re-evaluating the condition. Examples show using a for loop to iterate through arrays and print values. Enhanced for loops provide an easier way to iterate through arrays and collections.

Uploaded by

Roiz
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 6

For loop in Java with example

Loops are used to execute a set of statements repeatedly until a particular


condition is satisfied. In Java we have three types of basic loops: for, while and
do-while. In this tutorial we will learn how to use “for loop” in Java.

Syntax of for loop:


for(initialization; condition ; increment/decrement)
{
statement(s);
}
Flow of Execution of the for Loop
As a program executes, the interpreter always keeps track of which statement is
about to be executed. We call this the control flow, or the flow of execution of the
program.

First step: In for loop, initialization happens first and only one time, which means
that the initialization part of for loop only executes once.

Second step: Condition in for loop is evaluated on each iteration, if the condition
is true then the statements inside for loop body gets executed. Once the
condition returns false, the statements in for loop does not execute and the
control gets transferred to the next statement in the program after for loop.
Third step: After every execution of for loop’s body, the increment/decrement
part of for loop executes that updates the loop counter.

Fourth step: After third step, the control jumps to second step and condition is
re-evaluated.

Example of Simple For loop


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 output of this program is:

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
In the above program:
int i=1 is initialization expression
i>1 is condition(Boolean expression)
i– Decrement operation

Infinite for loop


The importance of Boolean expression and increment/decrement operation co-
ordination:

class ForLoopExample2 {
public static void main(String args[]){
for(int i=1; i>=1; i++){
System.out.println("The value of i is: "+i);
}
}
}
This is an infinite loop as the condition would never return false. The initialization
step is setting up the value of variable i to 1, since we are incrementing the value
of i, it would always be greater than 1 (the Boolean expression: i>1) so it would
never return false. This would eventually lead to the infinite loop condition. Thus
it is important to see the co-ordination between Boolean expression and
increment/decrement operation to determine whether the loop would terminate at
some point of time or not.

Here is another example of infinite for loop:

// infinite loop
for ( ; ; ) {
// statement(s)
}
For loop example to iterate an array:
Here we are iterating and displaying array elements using the for loop.

class ForLoopExample3 {
public static void main(String args[]){
int arr[]={2,11,45,9};
//i starts with 0 as array index starts with 0 too
for(int i=0; i<arr.length; i++){
System.out.println(arr[i]);
}
}
}
Output:

2
11
45
9
Enhanced For loop
Enhanced for loop is useful when you want to iterate Array/Collections, it is easy
to write and understand.

Let’s take the same example that we have written above and rewrite it
using enhanced for loop.

class ForLoopExample3 {
public static void main(String args[]){
int arr[]={2,11,45,9};
for (int num : arr) {
System.out.println(num);
}
}
}
Output:

2
11
45
9
Note: In the above example, I have declared the num as int in the enhanced for
loop. This will change depending on the data type of array. For example, the
enhanced for loop for string type would look like this:

String arr[]={"hi","hello","bye"};
for (String str : arr) {
System.out.println(str);
}

public class Test {

public static void main(String args[]) {


int [] numbers = {10, 20, 30, 40, 50};

for(int x : numbers ) {
System.out.print( x );
System.out.print(",");
}
System.out.print("\n");
String [] names = {"James", "Larry", "Tom", "Lacy"};

for( String name : names ) {


System.out.print( name );
System.out.print(",");
}
}
}

This will produce the following result −


Output
10, 20, 30, 40, 50,
James, Larry, Tom, Lacy,

PART II
Display Sum of n Natural Numbers

// Program to find the sum of natural numbers from 1 to 1000.

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

Here, the value of sum is 0 initially. Then, the for loop is iterated from i = 1 to

1000 . In each iteration, i is added to sum and its value is increased by 1.


When i becomes 1001, the test condition is false and sum will be equal to 0 +

1 + 2 + .... + 1000 .

The above program to add the sum of natural numbers can also be written as

// Program to find the sum of natural numbers from 1 to 1000.


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

int sum = 0;
int n = 1000;

// for loop
for (int i = n; i >= 1; --i) {
// body inside for loop
sum += i; // sum = sum + i
}

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


}
}

You might also like