MOCKSTACKS
EN
Questions And Answers

More Tutorials









Java for Loop


For loop:
For loop in java is used to iterate a block of code multiple times.
Use for loop only when the exact number of iterations needed is already known to you.
Syntax :
/* for (initialize; check_bool_expression; update){

            //code;

} */

  • Initializer: Initializes the value of a variable. This part is executed only once.

  • check_bool_expression: The code inside the for loop is executed only when this condition returns true.

  • update: Updates the value of the initial variable.

  • Example :
    for (i=7; i!=0; i--){
    
                System.out.println(i);
    
    }

    The above for loop initializes the value of i=7 and keeps printing as well as decrementing the value of i till i do not get equals to 0.

    Flow control of for loop :



    Example


    package com.company;
    
    public class cwh_23_for_loop {
        public static void main(String[] args) {
            for (int i=1; i<=10; i++){
                System.out.println(i);
            }
    
              int n = 3;
              for (int i =0; i<n; i++){
                  System.out.println(2*i+1);
               }
    
               for(int i=5; i!=0; i--){
                  System.out.println(i);
               }
        }
    }

    Output

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    1
    3
    5
    5
    4
    3
    2
    1


    Conclusion

    In this page (written and validated by ) you learned about Java for Loop . What's Next? If you are interested in completing Java tutorial, your next topic will be learning about: Java break and continue.



    Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue: mockstacks@gmail.com.


    Share On:


    Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using Mockstacks.com, you agree to have read and accepted our terms of use, cookies and privacy policy.