The For loop is a kind of loop in Java which is used to repeat a set of instructions of code for a known number of times until the condition given to it becomes false. Its syntax is given below :
for(i=1;i<=10;i++)
{
-----code-----
-----------------
}
The first part within the first semicolon is the initialization of the variable (here "i") used as the counter in the loop. The second part between the two semicolons is the condition which when becomes false results in the termination of the loop. Here the condition given is "i<=10" which means that the value of the variable i must be less then or equal to 10, but not greater than 10. The third and the last part after the second semicolon is the increment or decrement operation (here i is incremented). After every completion of the execution of the whole set of the code, the value of the variable used in the loop is incremented or decremented as according to the instructions given, by a fixed amount as given by the user. For example, to increment the value of i by 5, we can write "i=i+5" or "i+5" instead of "i++", and it would definitely do our job.
Note : The three parameters of the for loop i.e. initialization, condition, and increment/decrement operation are totally optional. The for loop can work without any or all parts of it missing, though the the two semicolons are necessary to be given. below is an example of such a loop with all its parts missing, which would then result in an infinite loop i.e. the loop that will run forever.
for(;;)
{
-----code-----
-----------------
}
for(i=1;i<=10;i++)
{
-----code-----
-----------------
}
The first part within the first semicolon is the initialization of the variable (here "i") used as the counter in the loop. The second part between the two semicolons is the condition which when becomes false results in the termination of the loop. Here the condition given is "i<=10" which means that the value of the variable i must be less then or equal to 10, but not greater than 10. The third and the last part after the second semicolon is the increment or decrement operation (here i is incremented). After every completion of the execution of the whole set of the code, the value of the variable used in the loop is incremented or decremented as according to the instructions given, by a fixed amount as given by the user. For example, to increment the value of i by 5, we can write "i=i+5" or "i+5" instead of "i++", and it would definitely do our job.
Note : The three parameters of the for loop i.e. initialization, condition, and increment/decrement operation are totally optional. The for loop can work without any or all parts of it missing, though the the two semicolons are necessary to be given. below is an example of such a loop with all its parts missing, which would then result in an infinite loop i.e. the loop that will run forever.
for(;;)
{
-----code-----
-----------------
}
No comments:
Post a Comment