For loop in Java

For loop in Java

For loop is an Entry control loop used widely for iteration purpose in c programming, first let’s observe syntax of For loop.

syntax

for(initiation ;test condition ;update)
{
statements(s);
}

there are 3 parts separated by a semicolon(;), the first part is called initiation, in this initiation, the index variable is initialized, means the first value of the variable is declared here. the second part is test condition, here the condition of the whole loop is represented here if the condition fails the loop stops (or) for loop executes the statements put in braces after for until the test variable reaches the end value, the condition expression is made with relational operators along with logical operators.The third one is step for the next upcoming value, the step should be in the arithmetic expression. every time when test condition is true code inside the braces is executed with the updated step condition until the test condition reaches end value

flowchart

For loop in Java flowchart
import java.util.*;
class forloop
{
public static void main(String args[])
{
Scanner s=new Scanner(System.in);
System.out.printf("Enter range number");
int x=s.nextInt();
int sum=0;
for(int i=1;i<=x;i++){
sum += i;
}
System.out.println(sum);
s.close();
}
}

output

Enter range number 50
1275

here, in the above example first, the initialization takes place, the index value of the variable i is 1 .next the condition is i should be lesser than or equal to x. the third one is the step where, for every loop ,the value i increases one time .after the test condition reaches end value x the loop stops by printing the total as output

Last updated on by vishal devxo