Java Tutorial

Java methods, java classes, java file handling, java how to, java reference, java examples, java for loop.

When you know exactly how many times you want to loop through a block of code, use the for loop instead of a while loop:

Statement 1 is executed (one time) before the execution of the code block.

Statement 2 defines the condition for executing the code block.

Statement 3 is executed (every time) after the code block has been executed.

The example below will print the numbers 0 to 4:

Try it Yourself »

Example explained

Statement 1 sets a variable before the loop starts (int i = 0).

Statement 2 defines the condition for the loop to run (i must be less than 5). If the condition is true, the loop will start over again, if it is false, the loop will end.

Statement 3 increases a value (i++) each time the code block in the loop has been executed.

Another Example

This example will only print even values between 0 and 10:

Nested Loops

It is also possible to place a loop inside another loop. This is called a nested loop .

The "inner loop" will be executed one time for each iteration of the "outer loop":

Test Yourself With Exercises

Use a for loop to print "Yes" 5 times.

Start the Exercise

Get Certified

COLOR PICKER

colorpicker

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: [email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail: [email protected]

Top Tutorials

Top references, top examples, get certified.

The Java Tutorials have been written for JDK 8. Examples and practices described in this page don't take advantage of improvements introduced in later releases and might use technology no longer available. See Java Language Changes for a summary of updated language features in Java SE 9 and subsequent releases. See JDK Release Notes for information about new features, enhancements, and removed or deprecated options for all JDK releases.

The for Statement

The for statement provides a compact way to iterate over a range of values. Programmers often refer to it as the "for loop" because of the way in which it repeatedly loops until a particular condition is satisfied. The general form of the for statement can be expressed as follows:

When using this version of the for statement, keep in mind that:

  • The initialization expression initializes the loop; it's executed once, as the loop begins.
  • When the termination expression evaluates to false , the loop terminates.
  • The increment expression is invoked after each iteration through the loop; it is perfectly acceptable for this expression to increment or decrement a value.

The following program, ForDemo , uses the general form of the for statement to print the numbers 1 through 10 to standard output:

The output of this program is:

Notice how the code declares a variable within the initialization expression. The scope of this variable extends from its declaration to the end of the block governed by the for statement, so it can be used in the termination and increment expressions as well. If the variable that controls a for statement is not needed outside of the loop, it's best to declare the variable in the initialization expression. The names i , j , and k are often used to control for loops; declaring them within the initialization expression limits their life span and reduces errors.

The three expressions of the for loop are optional; an infinite loop can be created as follows:

The for statement also has another form designed for iteration through Collections and arrays This form is sometimes referred to as the enhanced for statement, and can be used to make your loops more compact and easy to read. To demonstrate, consider the following array, which holds the numbers 1 through 10:

The following program, EnhancedForDemo , uses the enhanced for to loop through the array:

In this example, the variable item holds the current value from the numbers array. The output from this program is the same as before:

We recommend using this form of the for statement instead of the general form whenever possible.

About Oracle | Contact Us | Legal Notices | Terms of Use | Your Privacy Rights

Copyright © 1995, 2022 Oracle and/or its affiliates. All rights reserved.

Java Guides

Java Guides

Search this blog, java for loop with examples, table of contents, java for loop syntax.

  • How for Loop Works

Simple for Loop Example

Using the comma, the for-each version of the for loop, for-each loop with break.

  • for-each Loop is Essentially Read-Only
  • for-each - Iterating Over Multidimensional Arrays

Search an Array Using for-each Style Example

Nested for loops.

  • The initialization expression initializes the loop; it's executed once, as the loop begins.
  • When the termination expression evaluates to false, the loop terminates.
  • The increment expression is invoked after each iteration through the loop; it is perfectly acceptable for this expression to increment or decrement a value.

How for Loop Works (Flow of Execution of the for Loop)

for loop assignment java

The for-each Loop is Essentially Read-Only

The for-each loop - iterating over multidimensional arrays, post a comment.

Leave Comment

My Top and Bestseller Udemy Courses

  • Spring 6 and Spring Boot 3 for Beginners (Includes Projects)
  • Building Real-Time REST APIs with Spring Boot
  • Building Microservices with Spring Boot and Spring Cloud
  • Full-Stack Java Development with Spring Boot 3 & React
  • Testing Spring Boot Application with JUnit and Mockito
  • Master Spring Data JPA with Hibernate
  • Spring Boot Thymeleaf Real-Time Web Application - Blog App

Check out all my Udemy courses and updates: Udemy Courses - Ramesh Fadatare

Copyright © 2018 - 2025 Java Guides All rights reversed | Privacy Policy | Contact | About Me | YouTube | GitHub

Popular Articles

  • Java Hashmap Methods (Nov 17, 2023)
  • Java And Operator (Nov 17, 2023)
  • Java Wait (Nov 17, 2023)
  • Java Multiline String (Feb 14, 2024)
  • Java For Loop Syntax (Nov 17, 2023)

Java For Loop

Java For Loop

Switch to English

Table of Contents

Understanding the Basics

Structure of a for loop, example of a for loop, tips and tricks, common errors and how to avoid them.

Introduction

  • Initialization: It is the initial condition which gets executed once when the loop starts. Here, we can initialize the variable, or we can also use an already initialized variable. It is an optional condition.
  • Condition: It is the second condition which is executed each time to test the condition of the loop. If the condition is true, the loop will continue, otherwise it breaks. It is an optional condition.
  • Iteration: It is the third condition which runs every time after all the statements in the loop have been executed.
  • The int variable i is initialized to 1.
  • Then the condition is checked. If i is less than or equal to 5, the loop continues; otherwise, it stops.
  • The print statement inside the loop is executed, and the value of i is printed.
  • After executing all the statements inside the loop, the value of i is increased by 1 because of the i++ statement.
  • This process continues until the condition i<=5 becomes false.
  • Always initialize the loop control variable correctly and make sure that the initialization is done before the loop starts.
  • Ensure that the iteration statement is written correctly. For example, if your loop variable is decreasing during each iteration, but your condition is checking for an increase, then your loop might run infinitely.
  • Make sure that your condition is correct. If your condition never becomes false, the loop will run indefinitely. This will cause the program to crash or behave unexpectedly.

Javatpoint Logo

Java Tutorial

Control statements, java object class, java inheritance, java polymorphism, java abstraction, java encapsulation, java oops misc.

JavaTpoint

  • Send your Feedback to [email protected]

Help Others, Please Share

facebook

Learn Latest Tutorials

Splunk tutorial

Transact-SQL

Tumblr tutorial

Reinforcement Learning

R Programming tutorial

R Programming

RxJS tutorial

React Native

Python Design Patterns

Python Design Patterns

Python Pillow tutorial

Python Pillow

Python Turtle tutorial

Python Turtle

Keras tutorial

Preparation

Aptitude

Verbal Ability

Interview Questions

Interview Questions

Company Interview Questions

Company Questions

Trending Technologies

Artificial Intelligence

Artificial Intelligence

AWS Tutorial

Cloud Computing

Hadoop tutorial

Data Science

Angular 7 Tutorial

Machine Learning

DevOps Tutorial

B.Tech / MCA

DBMS tutorial

Data Structures

DAA tutorial

Operating System

Computer Network tutorial

Computer Network

Compiler Design tutorial

Compiler Design

Computer Organization and Architecture

Computer Organization

Discrete Mathematics Tutorial

Discrete Mathematics

Ethical Hacking

Ethical Hacking

Computer Graphics Tutorial

Computer Graphics

Software Engineering

Software Engineering

html tutorial

Web Technology

Cyber Security tutorial

Cyber Security

Automata Tutorial

C Programming

C++ tutorial

Control System

Data Mining Tutorial

Data Mining

Data Warehouse Tutorial

Data Warehouse

RSS Feed

  • Java Tutorial
  • What is Java?
  • Installing the Java SDK
  • Your First Java App
  • Java Main Method
  • Java Project Overview, Compilation and Execution
  • Java Core Concepts
  • Java Syntax
  • Java Variables
  • Java Data Types
  • Java Math Operators and Math Class
  • Java Arrays
  • Java String
  • Java Operations
  • Java if statements
  • Java Ternary Operator
  • Java switch Statements
  • Java instanceof operator

Java for Loops

  • Java while Loops
  • Java Classes
  • Java Fields
  • Java Methods
  • Java Constructors
  • Java Packages
  • Java Access Modifiers
  • Java Inheritance
  • Java Nested Classes
  • Java Record
  • Java Abstract Classes
  • Java Interfaces
  • Java Interfaces vs. Abstract Classes
  • Java Annotations
  • Java Lambda Expressions
  • Java Modules
  • Java Scoped Assignment and Scoped Access
  • Java Exercises

Loop Initializer

Post iteration operation, the java for each loop, the continue command, the break command, variable visibility in java for loops, for loops in other languages.

The Java for loop repeats a set of Java operations. A for loop repeats a block of code as long as some condition is true. Here is a simple Java for loop example:

This example is a standard Java for loop. Inside the parentheses () after the for keyword, are three statements separated by semicolon (;).

The first statement declares an int variable named i and assigns it the value 0 . This statement is only executed once, when the for loop starts.

The second statement compares the value of the i variable to the value 10 . If the value of i is less than 10 , then the for loop is executed one more time. This statement is executed before each repetition of the for loop.

The third statement increments the value of i . This statement is also executed once per iteration of the for loop, after the body of the for loop is executed.

The result of the for loop shown above is that the body of the loop is executed 10 times. Once for each of the values of i that are less than 10 (0 to 9).

You don't actually need the curly braces around the for loop body. If you omit the curly braces, then only the first Java statement after the for loop statement is executed. Here is an example:

In this example, only the first System.out.println() statement is executed inside the for loop. The second System.out.println() statement is not executed until after the for loop is finished.

Forgetting the curly braces around the for loop body is a common mistake. Therefore it can be a good habit to just always put them around the for loop body.

Loop Initializer, Condition and Post Iteration Operation

As mentioned earlier, the for loop contains three statements, separated by semicolons. Here is the example from above, showing the three statements:

These statements each have a different role in the execution of the for loop. These roles are:

  • Loop initializer
  • Loop condition
  • Post iteration operation

I'll explain the roles in a bit more detail below.

The loop initializer statement is only executed once, before the for loop begins. The loop initializer statement is typically used to initialize variables or objects that are used by the loop condition statement. In the example above (repeated below) the loop initializer statement (marked in bold) declares an int variable and assigns it the value 0.

You don't need a loop initializer statement. It is optional. Here is a for loop without a loop initializer statement:

Notice how an object is used to keep the state which controls the loop. Of course this object could have been declared inside the loop initializer statement. I just moved it outside the for loop to show that it is possible.

You can also initialize multiple variables inside the loop initializer statement. Here is an example of that:

Notice how two variables are declared. The i variable used as iteration counter, and the n variable which is used as an iteration boundary. Notice also, how the loop condition now compares the i variable to the n variable, instead of to a constant value.

The condition statement is the second statement inside the for loop parentheses. This statement is an expression that should evaluate to either true or false . If the statement evaluates to true , the for loop is evaluated one more time. If the statement evaluates to false , the for loop is not executed anymore, and execution jumps to the first statement after the body of the for loop.

Here is an example for loop with the condition statement marked in bold:

The third statement in the for loop is the post iteration statement. This statement is executed after each iteration of the for loop. This statement is typically used to update the variables that control the condition statement. For instance, increment a counter variable.

Here is an example for loop with the post iteration statement marked in bold:

The post iteration statement increments the variable i . In the condition statement the variable i is compared to the value 10 . If i is less than 10 , the for loop is executed one more time.

The post iteration statement is optional, like the loop initializer statement. Here is an example without post iteration statement:

In Java 5 a variation of the for loop was added. This variation is called the for each loop. Here is a Java for each loop example:

Notice the String array. This array is used inside the for each loop. Notice how a String aString variable is declared inside the parentheses of the for loop. For each iteration of the for each loop this variable will be bound to one of the String objects from the strings array. The for each loop will repeat once for each element in the strings array.

The Java for each loop can also be used with generic collections. I have explained that in more detail in my Java Iterable tutorial , which is part of my Java Collections tutorial .

Java contains a continue command which can be used inside Java for (and while ) loops. The continue command is placed inside the body of the for loop. When the continue command is met, the Java Virtual Machine jumps to the next iteration of the loop without executing more of the for loop body. The next iteration of the for loop body will proceed as any other. If that iteration also meets the continue command, that iteration too will skip to the next iteration, and so forth.

Note: When the continue command skips to the next iteration of the loop, the post-iteration action is still executed for that iteration.

Here is a simple continue example inside a for loop:

Notice the if statement inside the for loop. This if statement checks if each String in the strings array does not start with with the letter j . If not, then the continue command is executed, and the for loop continues to the next iteration.

If the current String in the strings array does start with the letter j , then the next Java statement after the if statement is executed, and the variable wordsStartingWithJ is incremented by 1.

The continue command also works inside for each loops. Here is a for each version of the previous example:

The for loop looks a bit different, but the logic and functionality remains the same.

The break command is a command that works inside Java for (and while ) loops. When the break command is met, the Java Virtual Machine breaks out of the for loop, even if the loop condition is still true. No more iterations of the for loop are executed once a break command is met. Here is a break command example inside a for loop:

Notice the second if statement inside the for loop. This if statement checks if 3 words or more have been found which starts with the letter j . If yes, the break command is executed, and the program breaks out of the for loop.

Like with the continue command, the break command also works inside for each loops. Here is the example from before, using a for each loop instead:

Just a little difference in the for loop, but the overall functionality remains the same.

Variables declared inside the parentheses or the body of a Java for loop are only visible inside the for loop body. This is true for variables of for each loops too. Look at this Java for loop example:

The variables i and iAsNo are only visible inside the for loop body. They cannot be referenced outside the for loop body.

The same is true for the aString variable in this Java for each loop example:

Since the aString variable is declared inside the parentheses of the Java for each loop, the variable is only visible inside the for each loop.

For the curious reader, here are links to tutorials about for loop instructions in all the programming languages covered here at Jenkov.com :

  • for in Java
  • for in Python

P2P Networks Introduction

Previous Section | Next Chapter | Main Index

Programming Questions and Exercises : Loops

Write a program to print numbers from 1 to 10.

Show the answer.

Write a program to calculate the sum of first 10 natural number.

Write a program that prompts the user to input a positive integer. It should then print the multiplication table of that number. 

Write a program to find the factorial value of any number entered through the keyboard. 

Two numbers are entered through the keyboard. Write a program to find the value of one number raised to the power of another. (Do not use Java built-in method)

Write a program that prompts the user to input an integer and then outputs the number with the digits reversed. For example, if the input is 12345, the output should be 54321.

Write a program that reads a set of integers, and then prints the sum of the even and odd integers.

Write a program that prompts the user to input a positive integer. It should then output a message indicating whether the number is a prime number. 

Write a program to calculate HCF of Two given number.

Question 10

Write a do-while loop that asks the user to enter two numbers. The numbers should be added and the sum displayed. The loop should ask the user whether he or she wishes to perform the operation again. If so, the loop should repeat; otherwise it should terminate. 

Question 11

Write a program to enter the numbers till the user wants and at the end it should display the count of positive, negative and zeros entered. 

Question 12

Write a program to enter the numbers till the user wants and at the end the program should display the largest and smallest numbers entered.

Question 13

Write a program to print out all Armstrong numbers between 1 and 500. If sum of cubes of each digit of the number is equal to the number itself, then the number is called an Armstrong number. For example, 153 = ( 1 * 1 * 1 ) + ( 5 * 5 * 5 ) + ( 3 * 3 * 3 )

Question 14

Write a program to print Fibonacci series of n terms where n is input by user : 0 1 1 2 3 5 8 13 24 ..... 

Question 15

Write a program to calculate the sum of following series where n is input by user.  1 + 1/2 + 1/3 + 1/4 + 1/5 +…………1/n 

Question 16

Compute the natural logarithm of 2, by adding up to n terms in the series 1 - 1/2 + 1/3 - 1/4 + 1/5 -... 1/n where n is a positive integer and input by user.

Question 17

Write a program that generates a random number and asks the user to guess what the number is. If the user's guess is higher than the random number, the program should display "Too high, try again." If the user's guess is lower than the random number, the program should display "Too low, try again." The program should use a loop that repeats until the user correctly guesses the random number.

Question 18

Write a program to print following :

Question 19

Write a program to compute sinx for given x. The user should supply x and a positive integer n. We compute the sine of x using the series and the computation should use all terms in the series up through the term involving x n

sin x = x - x 3 /3! + x 5 /5! - x 7 /7! + x 9 /9! .......

Question 20

Write a program to compute the cosine of x. The user should supply x and a positive integer n. We compute the cosine of x using the series and the computation should use all terms in the series up through the term involving x n

cos x = 1 - x 2 /2! + x 4 /4! - x 6 /6! .....

  • 1.1 Getting Started
  • 1.2 Creating Your First Application
  • 1.3 Parts of a Java Program
  • 1.4 Variables and Literals
  • 1.5 Primitive Data Types
  • 1.6 Arithmetic Operators
  • 1.7 Operator Precedence
  • 1.8 Type Conversion and Casting
  • Questions and Exercises
  • 2.1 Class String
  • 2.2 Objects and Reference Variables
  • 2.3 Class Math Methods
  • 2.4 String Methods
  • 2.5 Reading Keyboard Input
  • 2.6 Dialog Boxes for Input/Output
  • 3.1 The if-else Statement
  • 3.2 The if-else-if Statement
  • 3.3 Nested if Statement
  • 3.4 Logical Operators
  • 3.5 Comparing String Objects
  • 3.6 The switch Statement
  • 3.7 Conditional Operator
  • 4.1 The Increment and Decrement Operators
  • 4.2 The while Loop
  • 4.3 The do-while Loop
  • 4.4 The for Loop
  • 4.5 Nested Loops
  • 4.6 The break and continue Statements
  • 5.1 Introduction to Methods
  • 5.2 void Methods
  • 5.3 Passing Arguments to a Method
  • 5.4 Local Variables
  • 5.5 Returning a Value from a Method
  • 6.1 Objects and Classes
  • 6.2 Designing a Class
  • 6.3 Constructors
  • 6.4 Overloading Methods
  • 6.5 UML Diagram
  • 7.1 Introduction to Arrays
  • 7.2 Processing Array Elements
  • 7.3 Passing Arrays as Arguments to Methods
  • 7.4 Common Array Operations
  • 7.5 Returning Arrays from Methods
  • 7.6 String Arrays
  • 7.7 Arrays of Objects
  • 7.8 Two-Dimensional Arrays
  • 7.9 Variable-Length Argument Lists
  • 7.10 The ArrayList Class
  • 8.1 Static Class Members
  • 8.2 Passing Objects as Arguments to Methods
  • 8.3 Returning Objects from Methods
  • 8.4 The toString Method
  • 8.5 The this Reference Variable
  • 8.6 Aggregation
  • 8.7 Garbage Collection
  • 9.1 What Is Inheritance?
  • 9.2 Calling the Superclass Constructor
  • 9.3 Overriding Superclass Methods
  • 9.4 Protected Member
  • 9.5 Multilevel Inheritance
  • 9.6 The object Class
  • 9.7 Polymorphism
  • 9.8 Abstract Classes and Abstract Method
  • 9.9 Interfaces
  • 10.1 Introduction to File Input and Output
  • 10.2 Writing Data to Text File
  • 10.3 Reading Data from Text File
  • 10.4 Reading and Writing Premitive Data
  • 11.1 Handling Exception
  • 11.2 Try Catch Block and Multi Catch
  • 11.3 Finally Block
  • 11.4 Try with Resources
  • 11.5 Checked and Unchecked Exceptions
  • 11.6 Rethrowing and Throwing an Exception
  • 11.7 Creating Your Own Exception Classes

Home | Contact us | About us

Learn Java practically and Get Certified .

Popular Tutorials

Popular examples, reference materials, learn java interactively, java introduction.

  • Get Started With Java
  • Your First Java Program
  • Java Comments

Java Fundamentals

  • Java Variables and Literals
  • Java Data Types (Primitive)
  • Java Operators
  • Java Basic Input and Output
  • Java Expressions, Statements and Blocks

Java Flow Control

  • Java if...else Statement
  • Java Ternary Operator

Java for Loop

  • Java for-each Loop

Java while and do...while Loop

Java break Statement

Java continue Statement

  • Java switch Statement
  • Java Arrays
  • Java Multidimensional Arrays
  • Java Copy Arrays

Java OOP(I)

  • Java Class and Objects
  • Java Methods
  • Java Method Overloading
  • Java Constructors
  • Java Static Keyword
  • Java Strings
  • Java Access Modifiers
  • Java this Keyword
  • Java final keyword
  • Java Recursion
  • Java instanceof Operator

Java OOP(II)

  • Java Inheritance
  • Java Method Overriding
  • Java Abstract Class and Abstract Methods
  • Java Interface
  • Java Polymorphism
  • Java Encapsulation

Java OOP(III)

  • Java Nested and Inner Class
  • Java Nested Static Class
  • Java Anonymous Class
  • Java Singleton Class
  • Java enum Constructor
  • Java enum Strings
  • Java Reflection
  • Java Package
  • Java Exception Handling
  • Java Exceptions
  • Java try...catch
  • Java throw and throws
  • Java catch Multiple Exceptions
  • Java try-with-resources
  • Java Annotations
  • Java Annotation Types
  • Java Logging
  • Java Assertions
  • Java Collections Framework
  • Java Collection Interface
  • Java ArrayList
  • Java Vector
  • Java Stack Class
  • Java Queue Interface
  • Java PriorityQueue
  • Java Deque Interface
  • Java LinkedList
  • Java ArrayDeque
  • Java BlockingQueue
  • Java ArrayBlockingQueue
  • Java LinkedBlockingQueue
  • Java Map Interface
  • Java HashMap
  • Java LinkedHashMap
  • Java WeakHashMap
  • Java EnumMap
  • Java SortedMap Interface
  • Java NavigableMap Interface
  • Java TreeMap
  • Java ConcurrentMap Interface
  • Java ConcurrentHashMap
  • Java Set Interface
  • Java HashSet Class
  • Java EnumSet
  • Java LinkedHashSet
  • Java SortedSet Interface
  • Java NavigableSet Interface
  • Java TreeSet
  • Java Algorithms
  • Java Iterator Interface
  • Java ListIterator Interface

Java I/o Streams

  • Java I/O Streams
  • Java InputStream Class
  • Java OutputStream Class
  • Java FileInputStream Class
  • Java FileOutputStream Class
  • Java ByteArrayInputStream Class
  • Java ByteArrayOutputStream Class
  • Java ObjectInputStream Class
  • Java ObjectOutputStream Class
  • Java BufferedInputStream Class
  • Java BufferedOutputStream Class
  • Java PrintStream Class

Java Reader/Writer

  • Java File Class
  • Java Reader Class
  • Java Writer Class
  • Java InputStreamReader Class
  • Java OutputStreamWriter Class
  • Java FileReader Class
  • Java FileWriter Class
  • Java BufferedReader
  • Java BufferedWriter Class
  • Java StringReader Class
  • Java StringWriter Class
  • Java PrintWriter Class

Additional Topics

  • Java Keywords and Identifiers
  • Java Operator Precedence
  • Java Bitwise and Shift Operators
  • Java Scanner Class
  • Java Type Casting
  • Java Wrapper Class
  • Java autoboxing and unboxing
  • Java Lambda Expressions
  • Java Generics

Nested Loop in Java

  • Java Command-Line Arguments

Java Tutorials

If a loop exists inside the body of another loop, it's called a nested loop. Here's an example of the nested for loop.

Here, we are using a for loop inside another for loop.

We can use the nested loop to iterate through each day of a week for 3 weeks.

In this case, we can create a loop to iterate three times (3 weeks). And, inside the loop, we can create another loop to iterate 7 times (7 days).

Example 1: Java Nested for Loop

In the above example, the outer loop iterates 3 times and prints 3 weeks. And, the inner loop iterates 7 times and prints the 7 days.

We can also create nested loops with while and do...while in a similar way.

Note : It is possible to use one type of loop inside the body of another loop. For example, we can put a for loop inside the while loop.

Example 2: Java for loop inside the while loop

Here you can see that the output of both Example 1 and Example 2 is the same.

Example 3: Java nested loops to create a pattern

We can use the nested loop in Java to create patterns like full pyramid, half pyramid, inverted pyramid, and so on.

Here is a program to create a half pyramid pattern using nested loops.

To learn more, visit the Java program to print pyramid and patterns .

  • break and continue Inside Nested Loops

When we use a break statement inside the inner loop, it terminates the inner loop but not the outer loop. For example,

In the above example, we have used the break statement inside the inner for loop. Here, the program skips the loop when i is 2 .

Hence, days for week 2 are not printed. However, the outer loop that prints week is unaffected.

Similarly, when we use a continue statement inside the inner loop, it skips the current iteration of the inner loop only. The outer loop is unaffected. For example,

In the above example, we have used the continue statement inside the inner for loop. Notice the code,

Here, the continue statement is executed when the value of j is odd. Hence, the program only prints those days that are even.

We can see the continue statement has affected only the inner loop. The outer loop is working without any problem.

Table of Contents

  • Java nested loop
  • Example: Nested for Loop
  • Example: for loop inside while loop
  • Java nested loop to create a pattern

Sorry about that.

Related Tutorials

Java Tutorial

Looking for expert advice on how to improve your coding skills? The AvanTutor blog provides a wealth of resources and insights to help you become a better programmer. Our experienced tutors share tips and tricks for mastering popular programming languages such as Java, and JavaScript, as well as insights into the latest trends in software development. With regular updates and engaging content, the AvanTutor blog is your go-to resource for all things coding.

  • Get Tutoring
  • Ask a Coding Question
  • View All Coding Questions and Answers

10 Simple Java For-Loop Exercises

The following java for-loop exercises have been collected from various internet sources such as programmr.com and codewars. Go to my tutoring page if you need more help and would like to talk to a tutor.

User input does not work with the embedded compiler (paiza) below. That is why you see the problems being worded and setup slightly differently than on the rest of the page.

Happy Coding!

Exercise 1:

Determine and print the number of times the character ‘a’ appears in the input entered by the user.

Exercise 2:

Write a program that will print a box of #’s taking from user the height and width values.

Write a program to find the sum of 5 integers.

Write a java program to calculate the factorial value of given number. Factorial x –> x * x-1 * x-2…x*1

Example: factorial 4 = 4 * 3 * 2 * 1 = 24

Suppose we have a database composed of two fields or columns (arrays), the first field is for the username (user[]) and the other one is for the password(pass[]) .

This is how it looks like:

user[0] = “Hassan” ;

user[1] =”Idris”;

 user[2]=”Trevor” ;

And their passwords correspond with their indexes.

pass[0] = “homecomingking”;

pass[1] = “turnupcharlie”;

pass[2] = “afraidofthedark”;

Then if one of them had successfully login, the output should be:

Enter username: Hassan

Enter password: homecomingking

Hello Hassan!

But if not, “Incorrect Login!”

You can ignore case for the username but not for the password.

You have to design the code such that the user has only three tries to guess the correct pin of the account. You set the pin as a constant with a final attribute. When correct display “Correct, welcome back.” When incorrect display “Incorrect, try again.”. When ran out of tries display “Sorry but you have been locked out.”

Write a program that prompts user for a word and prints “Yes” if it is a palindrome and “No” if it is not.

Exercise 8 (Advanced)

This is a code wars kata. click here to train on “Abbreviate a Two Word Name” on code wars.

Write a function to convert a name into initials. You can assume the program takes in two words with one space in between them.

The output should be two capital letters with a dot separating them.

It should look like this:

This is a code wars kata. click here to train on “Grasshopper – Summation” on code wars.

Write a program that finds the summation of every number from 1 to num. The number will always be a positive integer greater than 0.

Exercise 10

This is a code wars kata. click here to train on “Sentence Smash” on code wars.

Write a method smash  that takes an array of words and smashes them together into a sentence and returns the sentence. You can ignore any need to sanitize words or add punctuation, but you should add spaces between each word.  Be careful, there shouldn’t be a space at the beginning or the end of the sentence!

March 24, 2019

Coding Basics , Java

coding , exercises , for-loops , java

Leave a Reply Cancel reply

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

Save my name, email, and website in this browser for the next time I comment.

Recent Posts

  • Too Many Tabs Open! – Tips for a Minimalist Coding Environment
  • How to Ask a Coding Question on Stack Overflow
  • Understanding Semantic Search and Its Impact on SEO
  • How to Choose the Right Coding Bootcamp for Your Goals
  • How to Get Coding Help When You’re Stuck: Tips from Expert Tutors

© 2024 AvanTutor Blog – Tips, Tricks, and Resources for Mastering Coding — Powered by WordPress

Theme by Anders Noren — Up ↑

web analytics

Tutorial World

36+ Java Coding questions on For loop statement

  • Post author: Tutorial World
  • Post published:
  • Post category: Java Coding
  • Java program to print all natural numbers from 1 to n using for loop.
  • Java program to print all even numbers between 1 to 100 using for loop.
  • Java program to print all odd number between 1 to 100 using for loop.
  • Java program to print sum of all even numbers between 1 to n using for loop.
  • Java program to print sum of all odd numbers between 1 to n using for loop.
  • Java program to print multiplication of any number using for loop.
  • Java program to count the digits of a given number using for loop.
  • Java program to print the sum of digits of a given number using for loop.
  • Java program to print all natural numbers in reverse order using for loop.
  • Java program to check whether a given number is Prime or not using for loop.
  • Java program to print all Prime numbers between 1 to n using for loop.
  • Java program to find sum of all prime numbers between 1 to n using for loop.
  • Java program to check a given number is Armstrong or not using for loop.
  • Java program to print all Armstrong numbers between 1 to n using for loop.
  • Java program to check a given number is Perfect or not using for loop.
  • Java program to check all Perfect numbers between 1 to n using for loop.
  • Java program to check a given number is Strong number or not using for loop.
  • Java program to print all Strong numbers between 1 to n using for loop.
  • Write a program in Java to swap first and last digit of number using for loop.
  • Java program to swap values using third variable using for loop.
  • Java program to swap values without using third variable using for loop.
  • Java program to calculate power of a number without using pow method using for loop.
  • Java program to find power of a number without using pow method using for loop.
  • Java program to calculate power of a number using pow method using for loop.
  • Java program to check number is palindrome or not using for loop.
  • Java program to print Fibonacci series of a given number using for loop.
  • Java program to print Fibonacci series of a given number using recursion using for loop.
  • Java program to print the frequency of digits in given number using for loop.
  • Write a program in Java to print ASCII character with values using for loop.
  • Java program to print all alphabets from a to z using for loop.
  • Java program to print all uppercase alphabets using for loop.
  • Java program to print all lowercase alphabets using for loop.
  • Java program to print all factors of a number using for loop.
  • Java program to print HCF (GCD) of two numbers using for loop.
  • Java program to print LCM of two numbers using for loop.
  • Write a Java program to find all prime factors of a number using for loop.

You Might Also Like

Read more about the article Java Program to Check given number is divisible by 11

Java Program to Check given number is divisible by 11

Read more about the article Print all natural numbers from 1 to n using while loop in Java

Print all natural numbers from 1 to n using while loop in Java

Read more about the article Java Program to Print all unique elements of an array

Java Program to Print all unique elements of an array

  • Skip to main content
  • Skip to search
  • Skip to select language
  • Sign up for free
  • Português (do Brasil)

The for statement creates a loop that consists of three optional expressions, enclosed in parentheses and separated by semicolons, followed by a statement (usually a block statement ) to be executed in the loop.

An expression (including assignment expressions ) or variable declaration evaluated once before the loop begins. Typically used to initialize a counter variable. This expression may optionally declare new variables with var or let keywords. Variables declared with var are not local to the loop, i.e. they are in the same scope the for loop is in. Variables declared with let are local to the statement.

The result of this expression is discarded.

An expression to be evaluated before each loop iteration. If this expression evaluates to true , statement is executed. If the expression evaluates to false , execution exits the loop and goes to the first statement after the for construct.

This conditional test is optional. If omitted, the condition always evaluates to true.

An expression to be evaluated at the end of each loop iteration. This occurs before the next evaluation of condition . Generally used to update or increment the counter variable.

A statement that is executed as long as the condition evaluates to true. You can use a block statement to execute multiple statements. To execute no statement within the loop, use an empty statement ( ; ).

The following for statement starts by declaring the variable i and initializing it to 0 . It checks that i is less than nine, performs the two succeeding statements, and increments i by 1 after each pass through the loop.

Initialization block syntax

The initialization block accepts both expressions and variable declarations. However, expressions cannot use the in operator unparenthesized, because that is ambiguous with a for...in loop.

Optional for expressions

All three expressions in the head of the for loop are optional. For example, it is not required to use the initialization block to initialize variables:

Like the initialization block, the condition part is also optional. If you are omitting this expression, you must make sure to break the loop in the body in order to not create an infinite loop.

You can also omit all three expressions. Again, make sure to use a break statement to end the loop and also modify (increase) a variable, so that the condition for the break statement is true at some point.

However, in the case where you are not fully using all three expression positions — especially if you are not declaring variables with the first expression but mutating something in the upper scope — consider using a while loop instead, which makes the intention clearer.

Lexical declarations in the initialization block

Declaring a variable within the initialization block has important differences from declaring it in the upper scope , especially when creating a closure within the loop body. For example, for the code below:

It logs 0 , 1 , and 2 , as expected. However, if the variable is defined in the upper scope:

It logs 3 , 3 , and 3 . The reason is that each setTimeout creates a new closure that closes over the i variable, but if the i is not scoped to the loop body, all closures will reference the same variable when they eventually get called — and due to the asynchronous nature of setTimeout , it will happen after the loop has already exited, causing the value of i in all queued callbacks' bodies to have the value of 3 .

This also happens if you use a var statement as the initialization, because variables declared with var are only function-scoped, but not lexically scoped (i.e. they can't be scoped to the loop body).

The scoping effect of the initialization block can be understood as if the declaration happens within the loop body, but just happens to be accessible within the condition and afterthought parts. More precisely, let declarations are special-cased by for loops — if initialization is a let declaration, then every time, after the loop body is evaluated, the following happens:

  • A new lexical scope is created with new let -declared variables.
  • The binding values from the last iteration are used to re-initialize the new variables.
  • afterthought is evaluated in the new scope.

So re-assigning the new variables within afterthought does not affect the bindings from the previous iteration.

A new lexical scope is also created after initialization , just before condition is evaluated for the first time. These details can be observed by creating closures, which allow to get hold of a binding at any particular point. For example, in this code a closure created within the initialization section does not get updated by re-assignments of i in the afterthought :

This does not log "0, 1, 2", like what would happen if getI is declared in the loop body. This is because getI is not re-evaluated on each iteration — rather, the function is created once and closes over the i variable, which refers to the variable declared when the loop was first initialized. Subsequent updates to the value of i actually create new variables called i , which getI does not see. A way to fix this is to re-compute getI every time i updates:

The i variable inside the initialization is distinct from the i variable inside every iteration, including the first. So, in this example, getI returns 0, even though the value of i inside the iteration is incremented beforehand:

In fact, you can capture this initial binding of the i variable and re-assign it later, and this updated value will not be visible to the loop body, which sees the next new binding of i .

This logs "0, 0, 0", because the i variable in each loop evaluation is actually a separate variable, but getI and incrementI both read and write the initial binding of i , not what was subsequently declared.

Using for without a body

The following for cycle calculates the offset position of a node in the afterthought section, and therefore it does not require the use of a statement section, a semicolon is used instead.

Note that the semicolon after the for statement is mandatory, because it stands as an empty statement . Otherwise, the for statement acquires the following console.log line as its statement section, which makes the log execute multiple times.

Using for with two iterating variables

You can create two counters that are updated simultaneously in a for loop using the comma operator . Multiple let and var declarations can also be joined with commas.

Specifications

Browser compatibility.

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

  • Empty statement
  • Python Basics
  • Interview Questions
  • Python Quiz
  • Popular Packages
  • Python Projects
  • Practice Python
  • AI With Python
  • Learn Python3
  • Python Automation
  • Python Web Dev
  • DSA with Python
  • Python OOPs
  • Dictionaries
  • Decrement in While Loop in Python
  • How to Access Index in Python's for Loop
  • How to Create a Nested For Loop in R?
  • Eliminating Loop from Python Code
  • Python Dictionary with For Loop
  • How to get the first and last elements of Deque in Python?
  • Python | How to get the last element of list
  • How to Initialize a Dictionary in Python Using For Loop
  • Convert a nested for loop to a map equivalent in Python
  • Difference between for loop in C and Python
  • How to Access Dictionary Values in Python Using For Loop
  • How to Create List of Dictionary in Python Using For Loop
  • Update a Dictionary in Python using For Loop
  • Python - Decrement Dictionary value by K
  • How to Write Memory Efficient Loops in Python
  • How to Create a List of N-Lists in Python
  • Increment and Decrement Operators in Python
  • For Loops in Python
  • Difference between for loop and while loop in Python
  • Python - Remove rear element from list
  • Python - Create list of tuples using for loop
  • How to Use For Next Loop in Excel VBA?
  • Python | for loop quiz | Question 5
  • Python | for loop quiz | Question 3
  • Python | for loop quiz | Question 8
  • Python | for loop quiz | Question 16
  • Python | for loop quiz | Question 1
  • Python | for loop quiz | Question 24
  • Python | for loop quiz | Question 23

How to Decrement a Python for Loop

Python’s for loop is a fundamental construct used for iterating over sequences. While Python does not have a built-in feature to decrement a loop index directly, there are multiple approaches to achieve this functionality. In this article, we’ll explore different methods to decrement a for loop in Python, each with its advantages and use cases.

Decrement a For Loop in Python

Below are some of the ways by which we can decrement a for loop in Python :

  • Using the reversed() Function
  • Iterating Over a Reversed Range
  • Decrementing the Loop Index Manually

Decrement a For Loop Using the reversed() Function

In this example, the reversed() function is used with range(5) to create an iterator that yields values from 4 to 0. The for loop then iterates over these values, printing each one in reverse order.

Decrement a For Loop Using Negative Step Value

In this example, the range(4, -1, -1) function generates a sequence starting from 4 and decrementing by 1 until reaching -1 (exclusive). The for loop iterates over this sequence, printing each value in reverse order.

Decrement a For Loop By Decrementing the Loop Index Manually

In this example, the code iterates over the indices of “my_list” in reverse order using a for loop. The elements of “my_list” are printed in reverse order by accessing them with reverse indices.

Please Login to comment...

Similar reads.

  • Python loop-programs

advertisewithusBannerImg

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

IMAGES

  1. Java For loop with Examples

    for loop assignment java

  2. Java For Loop

    for loop assignment java

  3. Java For Loop Syntax and Example

    for loop assignment java

  4. Java For Loop with Example

    for loop assignment java

  5. Last Minute Java FOR Loop with Break and Continue Tutorial

    for loop assignment java

  6. Java Loops

    for loop assignment java

VIDEO

  1. Java Programming Session 09

  2. While Loop Assignment

  3. loop use in java program #java #codelover # loop

  4. Java 38: for loop exercise ( Assignment)

  5. Java Loop Advance Tracing Problem

  6. For Loop example in java

COMMENTS

  1. For Loop in Java

    Java for loop provides a concise way of writing the loop structure. The for statement consumes the initialization, condition, and increment/decrement in one line thereby providing a shorter, easy-to-debug structure of looping. Let us understand Java for loop with Examples. Syntax: for (initialization expr; test expr; update exp) {.

  2. Java for Loop (With Examples)

    Java for Loop. Java for loop is used to run a block of code for a certain number of times. The syntax of for loop is:. for (initialExpression; testExpression; updateExpression) { // body of the loop } Here, The initialExpression initializes and/or declares variables and executes only once.; The condition is evaluated. If the condition is true, the body of the for loop is executed.

  3. Java For Loop

    Example explained. Statement 1 sets a variable before the loop starts (int i = 0). Statement 2 defines the condition for the loop to run (i must be less than 5). If the condition is true, the loop will start over again, if it is false, the loop will end. Statement 3 increases a value (i++) each time the code block in the loop has been executed.

  4. The for Statement (The Java™ Tutorials > Learning the Java Language

    The for statement provides a compact way to iterate over a range of values. Programmers often refer to it as the "for loop" because of the way in which it repeatedly loops until a particular condition is satisfied. The general form of the for statement can be expressed as follows: for ( initialization; termination ; increment) {.

  5. Java for Loop with Examples

    Previous Chapter Next Chapter In this quick chapter, we will discuss for loop with examples. The for statement provides a compact way to iterate over a range of values. Programmers often refer to it as the "for loop" because of the way in which it repeatedly loops until a particular condition is satisfied. Table of contents. Java for Loop Syntax; How for Loop Works

  6. Mastering Java For Loops

    None of the above. Here is a simple example of a For loop that prints the numbers from 1 to 5. for (int i = 1; i <= 5; i++) {. System.out.println(i); } In this code: The int variable i is initialized to 1. Then the condition is checked. If i is less than or equal to 5, the loop continues; otherwise, it stops.

  7. Loops in Java

    Comparison for loop while loop do-while loop; Introduction: The Java for loop is a control flow statement that iterates a part of the programs multiple times.: The Java while loop is a control flow statement that executes a part of the programs repeatedly on the basis of given boolean condition.

  8. Java for Loops

    The Java for loop repeats a set of Java operations. A for loop repeats a block of code as long as some condition is true. Here is a simple Java for loop example: . for(int i=0; i < 10; i++) { System.out.println("i is: " + i); } . This example is a standard Java for loop. Inside the parentheses after the for keyword, are three statements separated by semicolon (;).

  9. Java For Loop

    A for loop is a special loop that is used when a definite number of loop iterations is required. For loop have 3 sections, loop variable initialization, testing loop control variable, updating loop control variable. Enhanced for loop can be used to iterate through Array or collections. Java Code Editor:

  10. Questions and Exercises in Loops

    Programming Questions and Exercises : Loops. Question 1. Write a program to print numbers from 1 to 10. Show the answer. Question 2. Write a program to calculate the sum of first 10 natural number. Show the answer. Question 3. Write a program that prompts the user to input a positive integer.

  11. java

    Since an array in Java is an object reference, now both array[0] and array[1] point to the same location. If you want/need to clear the data of an array, use a loop: for, while, do-while, the one you feel more comfortable. ... Java: Object Array assignment in for loop. 1. Assigning array variable inside of a loop. 5.

  12. Nested Loop in Java (With Examples)

    In the above example, the outer loop iterates 3 times and prints 3 weeks. And, the inner loop iterates 7 times and prints the 7 days. We can also create nested loops with while and do...while in a similar way. Note: It is possible to use one type of loop inside the body of another loop. For example, we can put a for loop inside the while loop.

  13. 10 Simple Java For-Loop Exercises

    Try any of these basic for-loop exercises to test your Java for-loop skills. Exercises come with their own editor and compiler right here on the page! Skip to the content. Search for: AvanTutor Blog - Tips, Tricks, and Resources for Mastering Coding ... Write a java program to calculate the factorial value of given number. Factorial x -> x ...

  14. 36+ Java Coding questions on For loop statement

    36+ Java Coding questions on For loop statement. Java program to print all natural numbers from 1 to n using for loop. Java program to print all even numbers between 1 to 100 using for loop. Java program to print all odd number between 1 to 100 using for loop. Java program to print sum of all even numbers between 1 to n using for loop.

  15. Java programming Exercises, Practice, Solution

    Java is the foundation for virtually every type of networked application and is the global standard for developing and delivering embedded and mobile applications, games, Web-based content, and enterprise software. With more than 9 million developers worldwide, Java enables you to efficiently develop, deploy and use exciting applications and ...

  16. for

    initialization Optional. An expression (including assignment expressions) or variable declaration evaluated once before the loop begins.Typically used to initialize a counter variable. This expression may optionally declare new variables with var or let keywords. Variables declared with var are not local to the loop, i.e. they are in the same scope the for loop is in. Variables declared with ...

  17. java

    Short answer: no, there is no way. Longer answer: With a for-each loop you lose the index information, i.e. within the loop you don't know if you are dealing with thefirst, the second or the hundredth element. You need the index to address the position to write to in the array. So with using only the for-each there is no way.

  18. How to Decrement a Python for Loop

    Using the reversed() Function; Iterating Over a Reversed Range; Decrementing the Loop Index Manually; Decrement a For Loop Using the reversed() Function. In this example, the reversed() function is used with range(5) to create an iterator that yields values from 4 to 0. The for loop then iterates over these values, printing each one in reverse order.. Python3