03.Java for Loop
03.Java for Loop
In this tutorial, we will learn how to use for loop in Java with the help of
examples and we will also learn about the working of Loop in computer
programming.
• for loop
• while loop
• do...while loop
This tutorial focuses on the for loop. You will learn about the other type of
loops in the upcoming tutorials.
Here,
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");
}
}
}
Run Code
Output
Java is fun
Java is fun
Java is fun
Java is fun
Java is fun
i = 6
6th false The loop is terminated.
n = 5
Example 2: Display numbers from 1 to 5
// 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);
}
}
}
Run Code
Output
1
2
3
4
5
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
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
}
Output:
Sum = 500500
Here, the value of sum is 0 initially. Then, the for loop is iterated from i = 1 to
1 + 2 + .... + 1000 .
The above program to add the sum of natural numbers can also be written as
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
}
class Main {
public static void main(String[] args) {
// create an array
int[] numbers = {3, 7, 5, -5};
Output
3
7
5
-5
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. For example,
// Infinite for Loop
class Infinite {
public static void main(String[] args) {
int sum = 0;
Here, the test expression , i <= 10 , is never false and Hello is printed
repeatedly until the memory runs out.