for loop examples

Hope you had already gone through loops in java to get basic understanding of loop in Java.

Below are few examples which will make you hands on, and make you aware real use of loops. First let us consider solving below problem.

For loop example problem: Take two different arrays each of size 10. Concatinate each number of first array with each number of second array, and display each combination. Hint:Output generates 100 different numbers.
Solution: First declare & initialize two array a and b. Now each number of first array need to be concatinated with each number of second array. We need two different for loops, one to iterate thru first array, another to iterate thru second array. However, these two loops need to be nested, i..e outer for loop iterates thru first array, inner for loop iterates thru second array.

public class LoopExample{
public static void main(String args[])
{
int a[] = { 23,54,89,14,83,5,29,3,93,32};
int b[] = { 21,43,26,19,3,8,25,2,8,24};

for(int i=0;i < a.length;i++)
{
for(int j=0;j < b.length;j++)
{
String tmp = a[i]+""+b[j];
System.out.println(tmp);
}
}
}
}

Also this problem can be solved using while loop or do while loops.

Another Problem: Repeat above problem, but print only the numbers which are multiples of 3.
Solution: As shown above, after the number gets created, it is in String format, to convert it to int, use Integer.parseInt() method, Further check if it is multiple of 3, using modulo operator.

public class LoopExample{
public static void main(String args[])
{
int a[] = { 23,54,89,14,83,5,29,3,93,32};
int b[] = { 21,43,26,19,3,8,25,2,8,24};

for(int i=0;i < a.length;i++)
{
for(int j=0;j < b.length;j++)
{
String tmp = a[i]+""+b[j];
int val = Integer.parseInt(tmp);
if(val%3==0)
{
System.out.println(tmp);
}
}
}
}
}

Note that each iteration does not create any entry on the Stack, but a method call creates an entry in Stack. For more details, refer what is stack memory and when an entry is added to stack memory
You may also like to read:
Core Java Interview Questions
List of Operators in java
Java Interview Questions
What are Wrapper classes
More for loop examples