For loop in Java

For loop in Java

Loops are used to repeat some steps until the desired condition is satisfied. Loops basically execute certain piece of code which programmer does not want to write again and again. For e.g. if I want print numbers from 1 to 100, I have to declare 100 variables assign values to them and print them. It will definitely make my program large and will consume a lot of memory. Thus to avoid this problems looping structure provides easiest way by re-executing everything written inside it. For loop in Java is also one kind of looping structure. It comes under branching looping structure. Syntax-

for(initialization; condition; increment/decrement)
{
    ...
    ...
    ...
}

Q. Write a program to print 1-10 numbers using for loop in java.

Code-

class example
{
  public static void main(String[] args) {
    for(int x = 1; x <= 10; x++)
    {
	System.out.println(x);
    }
  }
}

Output-

for loop java output

Explanation-

In For loop, it will first initialize ‘x’ to 1, then will check if ‘x’ is less than or equal to 10. If the condition is true then it will execute the commands written inside it. After executing print statement the value of ‘x’ will be increased by 1. Now it checks again if ‘x’ is less than or equal to 10 and will continue to execute print statement. Once value of ‘x’ becomes 11 then it won’t satisfy the condition. Thus it will come out of the for loop and the program execution will stop. Hence we have successfully printed 1 to 10 numbers.

Program parts-

  1. class– Used to declare a class in java.
  2. public– Access modifier which represents it is visible to all.
  3. static– The main method is declared as static, so it doesn’t require to create an object to invoke the main method.
  4. void– Return type of the method.
  5. main– Represents the starting point of the program.
  6. String[] args– Used for command line argument.
  7. System.out.println()– System is a class, out is the object of PrintStream class, println() is the method of PrintStream class. System.out.println is used to print a statement.

Conclusion-

So this is the concept of for loop in Java. We hope it was clear to you. If you have any doubts tell us in the comment section. For daily updates and more such content do follow us on Instagram.

Keep programming!

ErrorFreeProgram.

Leave a Reply

Your email address will not be published. Required fields are marked *