Sunteți pe pagina 1din 2

Java use of for loop

A for loop is a programming language statement which allows code to be repeatedly executed. A for loop is classified as an iteration statement. A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times. The for loop syntax in Java is for (initialization; condition; iteration) { // statement; } Here is the flow of control in a for loop: The initialization step is executed first, and only once. This step allows you to declare and initialize any loop control variables. You are not required to put a statement here, as long as a semicolon appears. Next, the loop condition is checked. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and flow of control jumps to the next statement past the for loop. Loop condition includes Boolean expression. After the body of the for loop executes, the flow of control jumps back up to the iteration statement. This statement allows you to update any loop control variables. The Boolean expression is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then update step,then Boolean expression). After the Boolean expression is false, the for loop terminates. Lets take an example of for loop Class UseForLoop{ Public static void main(String ars[]){ int i; for (i=1;i<=5;i++){ System.out.println(I am in for loop); } } } Output: I am in for loop I am in for loop Declaration of variable Start of for loop where variable i is used as loop control variable Statements within {} after for statement will be repeatedly executed End of for loop End of main End of class

I am in for loop I am in for loop I am in for loop Loop condition determines how many times the statements in the for loop will be executed. In the above programe the statement in the for loop is executed five times. Loop starts For i=1 For i=2 For i=3 For i=4 For i=5 For i=6 check condition: i<=5 True check condition: i<=5 True check condition: i<=5 True check condition: i<=5 True check condition: i<=5 True check condition: i<=5 False print I am in for loop print I am in for loop print I am in for loop print I am in for loop print I am in for loop loop terminates increase i by 1 i.e. i = i+1 increase i by 1 i.e. i = i+1 increase i by 1 i.e. i = i+1 increase i by 1 i.e. i = i+1 increase i by 1 i.e. i = i+1 No action Now i=2 Now i=3 Now i=4 Now i=5 Now i=6 No action

S-ar putea să vă placă și