JAVA FOR LOOP

A for loop in java is a way to write a looping structure which can iterate over a specified block multiple times until the condition becomes false.

Table of Contents

[hide]
  • What are loops in Java
  • Types of loops in Java
  • Java For Loop
  • Example :A Simple for Loop
  • Example :Factorial using For Loop

What are loops in Java

Loops in Java Programming Language is a way to efficiently write a code that will iterate over a part of block multiple times if the condition is true.

Just take an example that you want to print your name on the screen 200 times, for printing something we use System.out.print, in this case, we have to use this 200 times to print the name which is not recommended. For this purpose, we use loops in which we write the print statement only once and it can run multiple times until certain condition is satisfied.

Loops are the fundamental concept of Java Programming Language, every beginner must know how to use loops. It saves times and makes our code efficient. There are three ways of executing loops in Java, which we will discuss in next module.

Types of loops in Java

There are basically three types of loops in Java :

  • Java for loop

  • Java while loop

  • Java do-while loop

Java for loop

Definition of Key Terms

For Loop in Java

It is a way to iterate over a set of Java operations multiple times as per the given condition. If we know the number of iterations then it is always recommended to use for loop.

While Loop in Java

It is also a way to iterate over a set of Java operations multiple times based on some boolean condition. If we do not know the number of iterations then it is always recommended to use While loop.

Do-While Loop in Java

Do-While loop iterate over a specified block multiple times based on some boolean condition. If we do not know the number of iterations and we must have to execute the loop at least once then we should go for Do-While loop

Now let us learn about these Java loops in detail.

Java For Loop

As we have learnt that Java loops iterate over a set of specified block based on some condition, here we will learn about the syntax and example of for loops in Java.

Java for loop Syntax

for(statement; condition check; increment/decrement) {// Code to be executed }

Java for loop consists of four main parts :

For Loop Key Terms

Initialization

When the loop starts this condition automatically gets executed. We can initialize variables here or can use the existing initialized variable.

Condition check

This is the second condition that returns boolean value i.e (true or false). It checks for the condition to be true for the execution of for loop. It jumps out of for loop once the condition becomes false.

Code execution(loop body)

Once the condition is true,the code gets executed performing the operations inside the loop body.

Increment/Decrement

It increases or decreases the variable value or we can say it increments/decrements the value of a variable.

NOTE : initialization, condition check and increment/decrement is optional in Java for loop. If you leave this empty no error would be there but it will cause infinite loop
for ( ; ; ) // infinite for loop

Flow Diagram :

Java for loop

As we can see from flow diagram as soon as the initialization is done, condition is checked, if its true then it enters the for loop if not then it simply gets terminated.

Example 1 : A Simple for Loop

copyimage
// Java program to illustrate for loop example
import java.util.*;
public class ForLoopExample{
    public static void main(String args[]){  
         Scanner sc= new Scanner(System.in); 
         System.out.print("Enter the iteration value : ");
         int num= sc.nextInt();
 
         for(int i=0 ; i<num ; i++ ) {
         System.out.println(i + " " +"iteration");
         }
     }
}
Enter the iteration value : 10

OUTPUT :

  • 0 iteration
  • 1 iteration
  • 2 iteration
  • 3 iteration
  • 4 iteration
  • 5 iteration
  • 6 iteration
  • 7 iteration
  • 8 iteration
  • 9 iteration

Dry Run

Lets dry run the above program with entered input value as 10. Kindly understand the flow carefully, how for loops works. This will help you to check whether you are getting the expected output or not.
InitializationCondition checkLoop bodyIncr ++ /Decr --
i = 00 < = 10;// Condition true0 iterationi++ // i values becomes 1
i = 11 < = 10;// Condition true1 iterationi++ // i values becomes 2
i = 22 < = 10;// Condition true2 iterationi++ // i values becomes 3
i = 33 < = 10;// Condition true3 iterationi++ // i values becomes 4
i = 44 < = 10;// Condition true4 iterationi++ // i values becomes 5
i = 55 < = 10;// Condition true5 iterationi++ // i values becomes 6
i = 66 < = 10;// Condition true6 iterationi++ // i values becomes 7
i = 77 < = 10;// Condition true7 iterationi++ // i values becomes 8
i = 88 < = 10;// Condition true8 iterationi++ // i values becomes 9
i = 99 < = 10;// Condition true9 iterationi++ // i values becomes 10
i = 1010 < = 10; // Condition false,out of for loop

Hope you have understood how to dry run your program in paper. If facing any difficulty with operations i.e (assignment operator, incr/decr operator) Kindly go through our Java Operators tutorials.

Example 2 : Factorial using For Loop

Factorial is a mathematical term that is used to calculate the product of an integer. Factorial of a number n can be calculated as n! (here value of n! is 1*2*3*4 ... (n-1)*n)

Assume you have to calculate the factorial of a number say 6, its factorial can be calculated as
6!= 6 * 5 *4 * 3 * 2 * 1 which is equal to 720. Lets see the implementation with Java program.

copyimage
// Java program to calculate factorial of any number
import java.util.*;
public class FactorialExample{
    public static void main(String args[]){  
        Scanner sc= new Scanner(System.in); 
        System.out.print("Enter the any number : ");
        int num = sc.nextInt(); 
        int fact = 1;

        for(int i=num ; i>0 ; i-- ) {
           fact= fact*i;
        }
        System.out.println( "Factorial is : " + fact);
    }
}

OUTPUT :

Enter any number : 6Factorial is : 720

Dry Run

InitializationCondition checkLoop bodyIncr ++ /Decr --
i = 66 > 0;// Condition truefact=1 * 6 = 6i-- // i values becomes 5
i = 55 > 0;// Condition truefact=6 * 5 = 30i-- // i values becomes 4
i = 44 > 0;// Condition truefact=30 *4 = 120i-- // i values becomes 3
i = 33 > 0;// Condition truefact=120 * 3 = 360i-- // i values becomes 2
i = 22 > 0;// Condition truefact=360 * 2 = 720i-- // i values becomes 1
i = 11 >0;// Condition truefact=720 * 1 = 720i-- // i values becomes 0
i = 00 > 0;// Condition false

Dry Run of the program with pen and paper is the most important thing for beginners, once you get the habit of calculating the output with pen and paper, later you would be good at solving complex problems. Now lets learn how to implement nested for loops.