For Loop In JAVA With Examples – Complete Tutorial

Table of Contents

What Is For Loop:

In JAVA For statement is the most commonly used lopping statement which iterate over a range of numbers. It is different from if then else in a way that it forces the program to go back up again repeatedly until termination expression evaluate to false. For loop is another way to control flow of program.


For Loop Syntax:

The most basic syntax of For loop is:

for (initialization-expression; termination-expression;increment-or-decrement-expression) {
    statements-or-code-to-be-executed-here;
}

initialization-expression – The initialization expression is executed once before the loop begins. It initializes the loop.

termination-expression – This is executed each time to check whether looping should terminate or continue. The looping continues to execute the code until it evaluates to true and terminate when evaluate to false.

increment-or-decrement-expression – It is executed after each iteration which increment or decrement the value of initialized variable.

statements-or-code-to-be-executed-here – Here we put the code or statement which we want to be iterated until for looping termination expression evaluate to false.


Example of For Loop:

Lets create a program to find the sum of 1 to 100 number using for Loop:

public class ForExample {

	public static void main(String[] args) {
		
		int i;
		int total = 0;
		for(i=1;i<=100;i++){
		total = total + i;
		}
		System.out.println("Sum of Value from 1 to 100 number is: " + total);

	}

}

Output is:

Sum of Value from 1 to 100 number is: 5050

Importance of For Loop:

As we know in JAVA, code is executed from top to bottom executing every line of code unless we use control flow statement. In our previous section, we already learned one way is to use if then else which tells the compiler to skip executing code if if condition is evaluated to false.

Another way to tell JAVA not to execute the code is using Loopings. It is different from if then else in a way that it forces the program to go back up again repeatedly until termination expression evaluate to false.

For example we need to create a program to find factorial of 10. You can do something like:

int x = 10*9*8*7*6*5*4*3*2*1;

You can do it easily in this case but what if we need to find factorial of 1000 or What if we need to add 1 to 1000 number or even more. Here we need for loop to iterate a particular code for a range of values.

Leave a Reply

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