GroTechMinds

java loop program examples

A Comprehensive Guide on the Basic For Loop in Java

Control structures are statements that allow us to manage the flow of execution of a block of code within a program. They determine how and when specific segments of code are executed, enabling you to implement complex logic and decision-making. For example, sequential execution (line by line), is the default natural order of execution in Java, whereas we have decision-making statements (if, if else, if else if, nested if), loop statements (for, while, do-while) and branching statements (break, continue) as well.

Introduction:

In Java, loops allow us to execute a block of statements in repetition. The for loop is one of the concise ways of writing the loop structure. It combines the initialization of variables, and conditions to specify the number of iterations, and either incrementing or decrementing in a single line, making it easy to read and understand.

Syntax of the for loop:

The Syntax of the for loop is given as follows.

				
					for (initialization; condition; increment/decrement)
{
‘loop body’
}

				
			
Initialization:

This is used to declare and initialize the loop control variable or variables. The loop control variable can also be declared globally and initialized inside the loop control statement.

Condition:

Before each iteration of the loop, this condition is checked. If the condition is true, the loop continues. If it is false, the loop terminates.

Increment/Decrement:

After each iteration of the loop, this determines whether incrementing or decrementing should happen to the value of the loop variable (i.e.,) updating of the variable’s value.

Loop Body:

The loop body is the executable code that is controlled by the control statement, in this case, it is the for loop.

Different variations of a basic for loop:

For loop are of different types like nested for loop, enhanced for loop (or for each loop), and the basic for loop. The basic for loop and its variations will be discussed as the scope of this blog, and they are as follows.

For loop using increment operator:

The different variations of using the increment operator in a for loop are given as follows.

1. Using the increment operator ‘(the variable) ++’, we can increase the value of the variable by one unit on each iteration (e.g., i++).

Code Snippet:
				
					public static void main(String[] args)
{
        	for (int i = 0; i < 5; i++)
        	{
                    	System.out.println("This is iteration number " + i);
        	}
}

				
			
Output Screenshot:
Java 1
  1. Using the increment operator ‘(the variable) ++’ two times adjacent to each other separated by a comma, we can increase the value of the variable by two units on each iteration (e.g., i++,i++).
Code Snippet:
				
					public static void main(String[] args)
{
        	for (int i = 0, j=0; i < 7; i++,i++)
        	{
                    	System.out.println("The value of 'i' in this iteration is " + i+", and the iteration number is "+(j));
                    	j++;
        	}
}

				
			
Output Screenshot:
java 2
  1. Using one of the compound assignment operators ‘(the variable) += (count of increment)’, we can increase the value of the variable by desired units on each iteration (e.g., i+=10, increases the value of i by 10 on each iteration).
Code Snippet:
				
					public static void main(String[] args)
{
        	for (int i = 0, j=0; i < 51; i+=10)
        	{
                    	System.out.println("The value of 'i' in this iteration is " + i+", and the iteration number is "+(j));
                    	j++;
        	}
}

				
			
Output Screenshot:
java3
For loop using decrement operator:
  1. Using the decrement operator ‘(the variable) –’, we can decrease the value of the variable by one unit on each iteration (e.g., i–).
Code Snippet:
				
					public static void main(String[] args)
{
        	for (int i = 5, j=5; i > -1; i--)
        	{
                    	System.out.println("The value of 'i' in this iteration is " + i+", and the iteration number is "+(j-i));
        	}
}

				
			
Output Screenshot:
  1. Using the decrement operator ‘(the variable) –’ two times adjacent to each other separated by a comma, we can decrease the value of the variable by two units on each iteration (e.g., i–,i–).
Code Snippet:
				
					public static void main(String[] args)
{
        	for (int i = 6, j=0; i > -1; i--,i--)
        	{
                    	System.out.println("The value of 'i' in this iteration is " + i+", and the iteration number is "+(j));
                    	j++;
        	}
}

				
			
Output Screenshot:
java 5
  1. Using one of the compound assignment operators ‘(the variable) -= (count of decrement)’, we can decrease the value of the variable by desired units on each iteration (e.g., i-=10, decreases the value of ‘i’ by 10 on each iteration).
Code Snippet:
				
					public static void main(String[] args)
{
        	for (int i = 50, j=0; i > -1; i-=10)
        	{
                    	System.out.println("The value of 'i' in this iteration is " + i+", and the iteration number is "+(j));
                    	j++;
        	}
}

				
			
Output Screenshot:
java 6
Infinite for loop:

If the condition in the for loop is given in such a way that the loop condition will never get met (will never become false), the loop will run until its value runs out of the range of the data type of the variable given in the control statement.

  1. The infinite for loop with increment operator is as follows.
Code Snippet:
				
					public static void main(String[] args) throws InterruptedException
{
        	for (byte i = 0, j=0; i > -1; i++)
        	{
                    	System.out.println("The value of 'i' in this iteration is " + i+", and the iteration number is "+(j));
                    	j++;
                    	Thread.sleep(100);
        	}
}

				
			
Output Screenshot:
gif java
  1. The infinite for loop with decrement operator is as follows.
Code Snippet:
				
					public static void main(String[] args) throws InterruptedException
{
        	for (byte i = 0, j=0; i < 1; i--)
        	{
                    	System.out.println("The value of 'i' in this iteration is " + i+", and the iteration number is "+(j));
                    	j++;
                    	Thread.sleep(100);
        	}
}

				
			
Output Screenshot:
gif java 2
The real Infinite for loop:

If the condition in the for loop is given in such a way that the loop condition is empty, it will never get met (will never become false), the loop will never end until the human intervention, system shuts down or the memory runs out . The infinite for loop without initialization, condition, increment/decrement is as follows.

Code Snippet:
				
					public static void main(String[] args) throws InterruptedException
{
        	for(  	;       	;       	)
        	{
        	System.out.println("This will never End");
        	Thread.sleep(50);
        	}
}

				
			
Output gif:
gif java 3
Practical Examples:

Problem Statement 1: Find out, the sum of the first 100 natural numbers using for loop.

Solution: To calculate the sum of the first 100 natural numbers using for loop, we iterate from 1 to 100 and add the value of the current iteration to the int variable ‘sum’ on every iteration.

Code Snippet:
				
					public static void main(String[] args) 
{
        	int sum=0;
        	int i;
        	for ( i=1; i<=100; i++)
        	{
                    	sum=sum+i;
        	}
        	System.out.println("The sum of first "+(i-1)+" numbers is "+ sum);
}

				
			
Output Screenshot:
gif Java 4

Problem Statement 2: Find out, the sum of all the even numbers from the first 100 natural numbers using for loop.

Solution: To calculate the sum of all the even numbers present in the first 100 natural numbers using a for loop, we iterate from 1 to 100 and increment every iteration by two units. We add the value of the variable ‘i’ of the current iteration to the int variable ‘sum’ on every iteration to get the sum of all the even numbers in the first 100 natural numbers.

Code Snippet:
				
					public static void main(String[] args) 
{
int sum=0;
        	for(int i=0;i<=100;i+=2)
        	{
        	sum=sum+i;
        	}
System.out.println("The sum of all the even numbers in the first 100 natural numbers is "+sum);
}

				
			
Output Screenshot:
java 7

Problem Statement 3: Reverse the given String ‘Grotechminds’ using a for loop.

Solution: To reverse the index positions of the given String using a for loop, we iterate the char value of the String in the index position 0 to index position 11 (length of the string – 1). On the first iteration, we add the char value present in the last index position to the zeroth index position of the empty String. On the second iteration we add the char value present in the last but one’s index position to the first index position of the empty String, thereby reversing the string upon the completion of all the iterations.

Code Snippet:
				
					public static void main(String[] args) 
{
        	String gtm="Grotechminds";
        	String gtm_rev="";
        	for (int i=0; i<gtm.length(); i++)
        	{
                    	char c=gtm.charAt(i);
                    	gtm_rev=c+gtm_rev;        	
        	}
System.out.println("The reversed String of "+gtm+" is "+gtm_rev);
}
}

				
			
Output Screenshot:
java 8
Conclusion:

For loop is a reliable and very effective tool in Java for automating tasks like iterating through data, generating sequences, or performing complex calculations that involve iterations. Remember to practice, stay updated with the latest trends in Automation Software Testing Course,and maintain a positive attitude throughout your interview process. As we progress through the journey of application of our knowledge on loops, we get to know the possibilities loops offer. 

Also read:

Upskill Yourself
Consult Us