
what is for loop

Loops are used for iteration which means to execute a part of code repeatedly. Repetition of a part of code can be done for a number of times or infinitely. If repetition of code is done for a number of times it is finite loop and if repetition is done infinitely it is infinite loop. Java provides several loop structures for iteration. Those are for, while, do...while etc. Let us discuss "for" loop. "for" loop provides convenience to give declaration of a variable, initiation of a variable, increment the variable and check for condition for the program control to come out of the loop in one line. The syntax of "for" loop is as follows:-
for(initialization;condition;increment)
{
//statements
}
The "for" loop works as follows- when the program control enters the loop it first does the initialization part and then checks the condition part, if the condition returned true it executes the statements given inside the loop and then goes to increment part and increments the initialized variable. Then again it checks the condition and goes into the loop if the condition returned true. It continues this process until condition is returned false.
Note:- The initialization part is done only once and the program control will never return to the initialization part of the "for" loop when once it is done.
Let us take an example class Tick which implements for loop:-
class Tick
{ public static void main(String args[])
{
int i;
for(i=0;i<10;i++)
{
System.out.println("Tick" + i);
}
}
Here the loop is executed 10 times from 0 to 10. At first when control enters the loop the variable 'i' is initialized to 0 and checks for the condition whether 0 is less than 10 which returns true and it prints Tick 0 for the first time. Then the value of 'i' is incremented to 1 and again condition is checked whether 1 is less than 10 which returns true and it prints Tick 1. This continues till 'i' becomes 10. When 'i' becomes 10, it checks the condition whether 10 is less than 10 which returns false and then control comes out of the "for" loop and the above program ends.
The declaration of 'i' can also be done inside the "for" loop which is as follows:-
class Tick
{ public static void main(String args[])
{
for(int i=0;i<10;i++)
{
System.out.println("Tick" + i);
}
}
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.