- Get link
- X
- Other Apps
Enhanced for Loop
When Java 1.5 was released, it introduced a new feature know as enhanced for loop. The working of enhanced for loop is same as for loop.But it has very simple syntax.This loop is best suited to access the elements of array.But other operations like reading values or getting values require conventional for loop.
Syntax:
for(datatype variableName : collectionName)
{
//statement(s)
}
The dataype is used to specify the dataype of loop control variable e.g int in the for loop. It can be of any data typewith respect to dataype of collection or array The variableName is the name of variable like , i ,j,k etc. The colon(:) symbol is must to be used in syntax. Then the collectionName is the collection or group whom we want to traverse like arrayName.
Example:
for(int i : myArray)
System.out.println(i);
This will exactly work like for loop. In the example, we are printing the array element present at index i.
Note: When we have only one statement to execute in any control statement like if , else or loops, we can omit curly brackets {}.Check the example given above.
Lets create a program to understand the use of enhanced for loop.
Write a program to print a series containing multiples of 3 using enhanced for loop.
In the example above,- We created an array and got its value from user.If you want to know, how to get value of array from user, read Arrays .
- To get values from user, we used simple for loop.Because we have to add condition to get value till "num" number.When num=5 , only 5 numbers can be entered by user.If user enters more than 5 numbers then a runtime error "ArrayIndexOutOfBounds" will be thrown.
- To print array elements we can use enhanced for loop. The enhanced loop will iterate through the whole array entered by user. The "if" statement's test condition is dividing each element present at index "i" with 3 and compares remainder with 0. If remainder is 0 the element is multiple of 3 and gets printed on screen.
Output:
Happy Coding!
Comments
Post a Comment
If you have any doubt, ask here