Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

For Loop Program In Java

Last Updated on August 21, 2023 by Mayank Dham

Loops are used in computer programming to run a block of code repeatedly. Instead of typing the same code 100 times, you could use a loop to display the same message 100 times.

In Java, there are three types of loops.

  • for loop
  • while loop
  • do…while loop

We will discuss for loop in detail in this article.

for Loop in Java

To run a block of code a certain number of times, use a Java for loop. The for loop’s syntax is:

for (initialExpression; testExpression; updateExpression)
{
    // body of the loop
}

Here,

  • InitialExpression only ever executes once while initialising and/or declaring variables.
  • The condition is examined. The for loop’s body is executed if the condition is satisfied.
  • The initialExpression’s value is updated by the updateExpression.
  • The condition is once more evaluated. Until the condition is false, the process keeps going.

Example 1: Display a Text Five Times

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

    int n = 5;
    for (int i = 1; i <= n; ++i) {
      System.out.println("PrepBytes");
    }
  }
}
Output
PrepBytes
PrepBytes
PrepBytes
PrepBytes
PrepBytes

Here is how this program works.

Iteration Variable Condition: i <= n Action
1st i = 1, n = 5 true PrepBytes  is printed.
i is increased to 2.
2nd i = 2
n = 5 true PrepBytes is printed

i is increased to 3. |
| 3rd | i = 3

n = 5 | true | PrepBytes  is printed.

i is increased to 4. |
| 4th | i = 4

n = 5 | true | PrepBytes  is printed.

i is increased to 5. |
| 5th | i = 5

n = 5 | true | PrepBytes  is printed.

i is increased to 6. |
| 6th | i = 6

n = 5 | false | The loop is terminated. |

Example 2: Display numbers from 1 to 5

class Main {
  public static void main(String[] args) {
  
    int n = 5;
    for (int i = 1; i <= n; ++i) {
      System.out.println(i);
    }
  }
}
Output
1
2
3
4
5

Example 3: Display Sum of n Natural Numbers

class Main {
  public static void main(String[] args) {
      
    int sum = 0;
    int n = 1000;

    
    for (int i = 1; i <= n; ++i) {
      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, it is added to the sum and its value is increased by 1.

When i becomes 1001, the test condition is false and the sum will be equal to 0 + 1 + 2 + …. + 1000.

for-each Loop in Java

The Java for loop has an alternative syntax that makes it easy to iterate through arrays and collections. For example,

class Main {
  public static void main(String[] args) {      
    int[] numbers = {2, 4, 6, 8};
    for (int number: numbers) {
       System.out.println(number);
    }
  }
}
Output
2
4
6
8

Here, we have used the for-each loop to print each element of the numbers array one by one.

In the first iteration of the loop, number will be 3, number will be 7 in second iteration and so on.

Infinite for Loop in Java

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 an infinite for loop. For example,

class Infinite {
    public static void main(String[] args) {      
        int sum = 0;
        for (int i = 1; i <= 10; --i) {
            System.out.println("PrepBytes");
        }
    }
}

Here, the test expression ,i <= 10, is never false and PrepBytes is printed repeatedly until the memory runs out.

In this article, we tried to explain the implementation of for loop in java with the help of different examples. Loops are the basics of any language which must be a must to practice for becoming a master in any language.

Conclusion
The for loop program in Java stands as a versatile and fundamental construct that empowers programmers to efficiently execute repetitive tasks. Its concise syntax, consisting of initialization, condition, and increment sections, makes it well-suited for a wide range of iteration scenarios. By controlling the number of loop iterations and providing a structured approach to iterating through arrays, collections, or performing actions a specific number of times, the for loop greatly enhances code efficiency and readability.
The for loop’s simplicity, along with its ability to handle complex iteration patterns through nested constructs, underlines its significance in Java programming. Its utility extends from simple counting tasks to intricate data processing and manipulation, showcasing its adaptability across various domains. However, as with any programming construct, it’s essential to use for loops judiciously, considering the trade-offs between readability and complexity. By understanding the nuances of for loops, developers can harness their power to create more efficient and effective code in Java applications.

Frequently Asked Questions (FAQs)

Here are some frequently asked questions about Java for loop programs.

Q1: What is for loop in Java and how does it work?
The for loop in Java is a control structure used to execute a block of code repeatedly for a specified number of iterations. It consists of an initialization section, a condition section, and an increment section. The loop continues executing as long as the condition remains true, and the increment section is executed after each iteration.

Q2: What is the syntax of the for loop in Java?
The syntax of the for loop in Java is as follows:

for (initialization; condition; increment) {
    // Code to be executed in each iteration
}

The initialization initializes the loop control variable, the condition specifies the termination condition, and the increment updates the loop control variable after each iteration.

Q3: How to use a for loop to iterate through an array in Java?
The for loop is commonly used to iterate through arrays in Java. You can use the length property of the array to determine the number of iterations. For example:

int[] numbers = {1, 2, 3, 4, 5};
for (int i = 0; i < numbers.length; i++) {
    System.out.println(numbers[i]);
}

Q4: Can I have nested for loops in Java?
Yes, Java allows you to have nested for loops, where one for loop is inside another. Nested for loops are often used to handle multidimensional data structures like arrays or matrices. The inner loop executes completely for each iteration of the outer loop.

Q5: Are there alternatives to the for loop for iteration in Java?
Yes, Java provides other loop constructs for iteration, including the while loop and the do-while loop. The while loop executes a block of code as long as a specified condition remains true, while the do-while loop ensures that the code block is executed at least once before checking the condition.

Other Java Programs

Java Program to Add Two Numbers
Java Program to Check Prime Number
Java Program to Check Whether a Number is a Palindrome or Not
Java Program to Find the Factorial of a Number
Java Program to Reverse a Number
Java Program to search an element in a Linked List
Program to convert ArrayList to LinkedList in Java
Java Program to Reverse a linked list
Java Program to search an element in a Linked List
Anagram Program in Java
Inheritance Program in Java
Even Odd Program in Java
Hello World Program in Java
If else Program in Java
Binary Search Program in Java
Linear Search Program in Java
Menu Driven Program in Java
Package Program in Java
Leap Year Program in Java
Array Programs in Java
Linked List Program in Java
String Programs in Java
Star Program in Java
Number Pattern Program in Java

Leave a Reply

Your email address will not be published. Required fields are marked *