Loops in java -While/for/do While

Loops:

  • In programming, Loops are used to repeat a block of code.
  • It allows a set of instructions to be executed repeatedly until a certain condition is fulfilled.
  • Loops are handy because they save time, reduce errors, and they make code more readable.

There are three types of for loops in Java.

  • for loop
  • while loop
  • do…..while loop

Elements in a Java Loop(tbd)

Every loop has its elements or variables that govern its execution. Generally, a loop has four elements that have different purposes which are:

  • Initialization Expression(s)
  • Test Expression(Condition)
  • Update Expression(s)
  • Body of the loop

While loop:

  • The while loop executes a block of code as long as a specified condition is true.
  • Java while loop is used to run a specific code until a certain condition is met.
while (testExpression) {
    // body of loop
}

Here,

  1. A while loop evaluates the textExpression inside the parenthesis ().
  2. If the textExpression evaluates to true, the code inside the while loop is executed.
  3. The textExpression is evaluated again.
  4. This process continues until the textExpression is false.
  5. When the textExpression evaluates to false, the loop stops.

Flow chart for while loop

While loop program 1:

package tamilnadu.chennai;

public class ProgrammingDemo {
	public static void main(String[]args)
	{
		ProgrammingDemo pd = new ProgrammingDemo();
		pd.loop_learning();
  }

private void loop_learning()
	{
		int purse = 0;
		int day = 1;
		while(day<=5)
		{
			purse = purse+day;
			System.out.println(purse);
			day=day+1;
		}
	}
}
}
package tamilnadu.chennai;

public class ProgrammingDemo {
	public static void main(String[]args)
	{
		ProgrammingDemo pd = new ProgrammingDemo();
		
		pd.worship();
}
private void worship()
	{
		int flower=1024;
		int temple=0;
		while(flower>0)
		{
			flower=flower/2;
		     temple=temple+1;
		}
		     System.out.println(temple);
		
	}
}
}
package tamilnadu.chennai;

public class ProgrammingDemo {
	public static void main(String[]args)
	{
		ProgrammingDemo pd = new ProgrammingDemo();
		pd.goldProgram();
		
	}
	private void goldProgram()
	{
		int day=1;
		int gold=1;
		int total=0;
		
		 while(day<=7)
		 {
			gold=gold*2;
			day=day+1;
		System.out.println(gold);
		}
		 
	}

For Loop

Java for loop is used to run a block of code for a certain number of times. The syntax of for loop is:

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

Here,

  1. The initialExpression initializes and/or declares variables and executes only once.
  2. The condition is evaluated. If the condition is true, the body of the for loop is executed.
  3. The updateExpression updates the value of initialExpression.
  4. The condition is evaluated again. The process continues until the condition is false.

Rules of using FOR loop in java

  • Variables declared in the initialization block should be of the same datatype. we cannot write like: for(int x = 0, long y = 1; y < 5; y++)
  • Variables declared inside the initialization block are accessible only within the loop.
  • When we declare any variable inside the for loop, we can not access it after the loop statement is over.

Program:

package tamilnadu.chennai;

import java.util.Scanner;

public class ForLoop_Practice1 {
	public static void main(String[] args) {
		ForLoop_Practice1 flp = new ForLoop_Practice1();
		flp.fibo();
		flp.neon();
}
private void neon() {
		// TODO Auto-generated method stub
		Scanner sc = new Scanner(System.in);
		System.out.println("Enter the number you want to check:");
		int num = sc.nextInt();
		int numFirst = num;
		num = num * num;
		System.out.println("Square of the given number" + " " + num);
		int sum;
		for (sum = 0; num > 0;) {
			int rem = num % 10;
			sum = rem + sum;
			System.out.print(rem + " ");
			num = num / 10;
		}
		System.out.println();
		System.out.println("sum of the digits of square value" + " " + sum);
		if (sum == numFirst) {
			System.out.println(numFirst + " " + "is a neon number");
		} else {
			System.out.println(num + " " + "is not a neon number");
		}
	}

	private void fibo() {
		// TODO Auto-generated method stub
		int no1 = 0;
		int no2 = 1;
		int temp;
		for (temp = 0; temp < 13;) {
			temp = no1 + no2;
			System.out.println(temp);
			no1 = no2;
			no2 = temp;
		}
	}

}

Do while loop:

The Java do-while loop is used to iterate a part of the program repeatedly, until the specified condition is true. If the number of iteration is not fixed and you must have to execute the loop at least once, it is recommended to use a do-while loop.

Java do-while loop is called an exit control loop. Therefore, unlike while loop and for loop, the do-while check the condition at the end of loop body. The Java do-while loop is executed at least once because condition is checked after loop body.    

Nested For loop:

If a loop exists inside the body of another loop, it’s called a nested loop. Here’s an example of the nested for loop.

package tamilnadu.chennai;

import java.util.Scanner;

public class ForLoop_Practice1 {
	public static void main(String[] args) {
		ForLoop_Practice1 flp = new ForLoop_Practice1();
		flp.nestedloop1();
		flp.nestedloop2();
}
private void nestedloop2() {
		// TODO Auto-generated method stub
		for (int row = 1; row <= 3; row++) {
			for (int col = 1; col <= 5; col++) {
				System.out.print(col + " ");
			}
			System.out.println();
		}
	}

	private void nestedloop1() {
		// TODO Auto-generated method stub
		for (int no = 1; no <= 3; no++) {
			for (int count = 1; count <= 4; count++) {
				System.out.print(no);
			}
			System.out.println();
		}

	}
}

References: https://www.geeksforgeeks.org/loops-in-java/ https://www.programiz.com/java-programming/for-loop https://www.javatpoint.com/java-for-loop https://www.tutorialspoint.com/java/java_for_loop.htm https://techvidvan.com/tutorials/java-for-loop/ https://www.w3schools.com/java/java_while_loop.asp https://beginnersbook.com/2015/03/while-loop-in-java-with-examples/ https://www.programiz.com/java-programming/do-while-loop

Leave a comment

Design a site like this with WordPress.com
Get started