Wednesday, December 5, 2018

What is for each loop in Java?

In this post you will learn about for each loop with example and differences between for loop and for each loop. This loops are commonly available in all programming languages. let’s start with the actual answer for this question:

Loops: as name said it will loop through through the data on a collection (or to a number value) until the condition gets satisfied.

example for loops: I wanted to print a static text for 5 times continuously. You can use any of the loop except foreach ( explain about foreach in a bit later) to do the operation.

for(int i = 0 ; i <  5; i++)
{
 System.out.println(“welcome to learn programming”);
}
The above code will execute 5 times with the static text given. The same can be written in while loop as well. example in while loop

int i = 1;
while ( i <= 5)
{
 System.out..println(“welcome to learn programming”); i++;
}


above code will also led to us the same output but the way we wrote code was just changed.

I hope you have understood the difference between for and while loop. Both are loop the condition until the condition gets satisfied. Syntax alone gets changed. You can replace any for loop with while loop and vice versa.

Foreach loop is used to run through the collection. consider you;re having an array collection of type integers and you wanted to print the sum of the entire elements in the array collection.but you don’t know the count of the elements in array. Because, the array is dynamic the value get vary based on your program input

in this situation you could use foreach to do so.

example:

int total = 0;
foreach(int n : numbers)
{
total += n;
}
System.out.println("total is: " + total);

No comments:

Post a Comment

High Paying Jobs after Learning Python

Everyone knows Python is one of the most demand Programming Language. It is a computer programming language to build web applications and sc...