Computer Science
Java For Loop
A Java for loop is a control flow statement that allows for repeated execution of a block of code. It consists of three parts: initialization, condition, and iteration. The loop continues to execute as long as the condition is true, and the iteration statement updates the loop control variable. This construct is commonly used for iterating through arrays or collections in Java.
Written by Perlego with AI-assistance
Related key terms
1 of 5
12 Key excerpts on "Java For Loop"
- eBook - PDF
- Joyce Farrell(Author)
- 2017(Publication Date)
- Cengage Learning EMEA(Publisher)
It is easy for others to read, and because the loop control variable’s initialization, testing, and alteration are all performed in one location, you are less likely to leave out one of these crucial elements. Although for loops are commonly used to control execution of a block of statements a fixed number of times, the programmer doesn’t need to know the starting, final, or step value for the loop control variable when the program is written. For example, any of the values might be entered by the user, or might be the result of a calculation. Figure 5-15 Comparable while and for statements that each output Hello four times count = 0 while count <= 3 output "Hello" count = count + 1 endwhile for count = 0 to 3 step 1 output "Hello" endfor The for loop is particularly useful when processing arrays. You will learn about arrays in Chapter 6. In Java, C11, and C#, a for loop that displays 21 values (0 through 20) might look similar to the following: for(count 5 0; count <= 20; count11) { output count; } The three actions (initializing, evaluating, and altering the loop control variable) are separated by semi- colons within a set of parentheses that follow the keyword for. The expression count11 increases count by 1. In each of the three languages, the block of statements that depends on the loop sits between a pair of curly braces, so the endfor keyword is not used. None of the three languages uses the keyword output, but all of them end output statements with a semicolon. 200 C H A P T E R 5 Looping Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Both the while loop and the for loop are examples of pretest loops. In a pretest loop, the loop control variable is tested before each iteration. That means the loop body might never execute because the evaluation controlling the loop might be false the first time it is made. - eBook - PDF
- Joyce Farrell(Author)
- 2017(Publication Date)
- Cengage Learning EMEA(Publisher)
It is easy for others to read, and because the loop control variable’s initialization, testing, and alteration are all performed in one location, you are less likely to leave out one of these crucial elements. Although for loops are commonly used to control execution of a block of statements a fixed number of times, the programmer doesn’t need to know the starting, final, or step value for the loop control variable when the program is written. For example, any of the values might be entered by the user, or might be the result of a calculation. Figure 5-15 Comparable while and for statements that each output Hello four times count = 0 while count <= 3 output Hello count = count + 1 endwhile for count = 0 to 3 step 1 output Hello endfor The for loop is particularly useful when processing arrays. You will learn about arrays in Chapter 6. In Java, C 11 , and C#, a for loop that displays 21 values (0 through 20) might look similar to the following: for(count 5 0; count <= 20; count 11 ) { output count; } The three actions (initializing, evaluating, and altering the loop control variable) are separated by semi-colons within a set of parentheses that follow the keyword for . The expression count 11 increases count by 1. In each of the three languages, the block of statements that depends on the loop sits between a pair of curly braces, so the endfor keyword is not used. None of the three languages uses the keyword output , but all of them end output statements with a semicolon. 200 C H A P T E R 5 Looping Copyright 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-300 Both the while loop and the for loop are examples of pretest loops. In a pretest loop , the loop control variable is tested before each iteration. That means the loop body might never execute because the evaluation controlling the loop might be false the first time it is made. - Admittedly, it can be difficult to have a lot of sympathy for a musical ensem- ble whose publisher charges a lot of money for what seems to have been very little effort on their part, at least when compared to the effort that goes into designing and implementing a software package. Nevertheless, it seems only fair that artists and authors receive some com- pensation for their efforts. How to pay artists, authors, and program- mers fairly, without burdening honest custom- ers, is an unsolved problem at the time of this writing, and many computer scientists are engaged in research in this area. © RapidEye/iStockphoto. 6.3 The for Loop 183 6.3 The for Loop It often happens that you want to execute a sequence of statements a given number of times. You can use a while loop that is controlled by a counter, as in the following example: int counter = 5; // Initialize the counter while (counter <= 10) // Check the counter { sum = sum + counter; counter++; // Update the counter } Because this loop type is so common, there is a spe- cial form for it, called the for loop (see Syntax 6.2). for (int counter = 5; counter <= 10; counter++) { sum = sum + counter; } Some people call this loop count-controlled. In con- trast, the while loop of the preceding section can be called an event-controlled loop because it exe- cutes until an event occurs; namely that the balance reaches the target. Another commonly used term for a count-controlled loop is definite. You know from the outset that the loop body will be executed a defi- nite number of times; ten times in our example. In contrast, you do not know how many iterations it takes to accumulate a target balance. Such a loop is called indefinite. Syntax 6.2 for Statement for (int i = 5; i <= 10; i++) { sum = sum + i; } This loop executes 6 times. See Programming Tip 6.3. This initialization happens once before the loop starts. The condition is checked before each iteration. This update is executed after each iteration.
- eBook - PDF
- Joyce Farrell(Author)
- 2018(Publication Date)
- Cengage Learning EMEA(Publisher)
C H A P T E R 6 Looping Upon completion of this chapter, you will be able to: Describe the loop structure Create while loops Use shortcut arithmetic operators Create for loops Create do…while loops Nest loops Improve loop performance Copyright 2019 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it. 284 Looping C H A P T E R 6 Learning About the Loop Structure If making decisions is what makes programs seem smart, looping is what makes programs seem powerful. A loop is a structure that allows repeated execution of a block of statements. Within a looping structure, a Boolean expression is evaluated. If it is true, a block of statements called the loop body executes and the Boolean expression is evaluated again. The loop body can be a single statement, or a block of statements between curly braces. As long as the loop-controlling, Boolean expression is true, the statements in the loop body continue to execute. When the Boolean evaluation is false, the loop ends. One execution of any loop is called an iteration. Figure 6-1 shows a diagram of the logic of a loop. In Java, you can use several mechanisms to create loops. In this chapter, you learn to use three types of loops: • A while loop, in which the loop-controlling Boolean expression is the first statement in the loop, evaluated before the loop body ever executes • A for loop, which is usually used as a concise format in which to execute loops • A do…while loop, in which the loop- controlling Boolean expression is the last statement in the loop, evaluated after the loop body executes one time. - eBook - PDF
Microsoft® Visual C# 2015
An Introduction to Object-Oriented Programming
- Joyce Farrell, , , (Authors)
- 2015(Publication Date)
- Cengage Learning EMEA(Publisher)
With a for loop , you can indicate the starting value for the loop control variable, the test condition that controls loop entry, and the expression that alters the loop control variable, all in one convenient place. You begin a for statement with the keyword for followed by a set of parentheses. Within the parentheses are three sections separated by exactly two semicolons. The three sections are usually used for: • Initializing the loop control variable • Testing the loop control variable • Updating the loop control variable As with an if or a while statement, you can use a single statement as the body of a for loop, or you can use a block of statements enclosed in curly braces. The while and for statements shown in Figure 5-10 produce the same output—the integers 1 through 10. // Declare loop control variable and limit int x; const int LIMIT = 10; // Using a while loop to display 1 through 10 x = 1; while (x <= LIMIT) { WriteLine(x); ++x; } // Using a for loop to display 1 through 10 for (x = 1; x <= LIMIT; ++x) WriteLine(x); Figure 5-10 Displaying integers 1 through 10 with while and for loops The amount by which a loop control variable increases or decreases on each cycle through the loop is often called the step value . That’s because in the BASIC programming language, and its descendent, the Visual Basic language, the keyword STEP is actually used in for loops. Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it. - Joyce Farrell(Author)
- 2012(Publication Date)
- Cengage Learning EMEA(Publisher)
C H A P T E R 4 Looping In this chapter, you will learn about: The loop structure Using a loop control variable Nested loops Avoiding common loop mistakes Using a for loop Common loop applications Copyright 2012 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it. Understanding the Loop Structure Although making decisions is what makes computers seem intelligent, looping makes computer programming both efficient and worthwhile. When you use a loop, you can write one set of instructions that operates on multiple data items. For example, a large company might use a single loop to produce thousands of paychecks, or a big-city utility company might use a single loop to process millions of customer bills. Using fewer instructions results in less time needed for design and coding, less compile time, and fewer errors. Recall the loop structure that you learned about in Chapter 2. Along with sequence and selection, it is one of the three basic structures used in structured programming. Figure 4-1 shows a loop structure. This loop starts with a test of a Boolean expression. The statements within a loop constitute the loop body ; the body executes as long as the loop-controlling Boolean expression remains true. The same loop-controlling question is asked following each execution of the loop body; the structure is exited only when the test expression is false. You may hear programmers refer to looping as repetition or iteration .- Joyce Farrell(Author)
- 2017(Publication Date)
- Cengage Learning EMEA(Publisher)
You begin a for statement with the keyword for followed by a set of parentheses. Within the parentheses are three sections separated by exactly two semicolons. The three sections are usually used for: 1. Initializing the loop control variable 2. Testing the loop control variable 3. Updating the loop control variable As with an if or a while statement, you can use a single statement as the body of a for loop, or you can use a block of statements enclosed in curly braces. The while and for statements shown in Figure 5-10 produce the same output—the integers 1 through 10. Figure 5-10 Displaying integers 1 through 10 with while and for loops // Declare loop control variable and limit int x; const int LIMIT = 10; // Using a while loop to display 1 through 10 x = 1; while (x <= LIMIT) { WriteLine(x); ++x; } // Using a for loop to display 1 through 10 for (x = 1; x <= LIMIT; ++x) WriteLine(x); The amount by which a loop control variable increases or decreases on each cycle through the loop is often called the step value . That’s because in the BASIC programming language, and its descendent, the Visual Basic language, the keyword STEP is actually used in for loops. Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it. 196 C H A P T E R 5 Looping Within the parentheses of the for statement shown in Figure 5-10, the initialization section prior to the first semicolon sets a variable named x to 1. The program executes this statement once, no matter how many times the body of the for loop eventually executes.- No longer available |Learn more
Programming Fundamentals Using JAVA
A Game Application Approach
- William McAllister, S. Jane Fritz(Authors)
- 2021(Publication Date)
- Mercury Learning and Information(Publisher)
Nora Ryan Logan. String anArray = {"Nora", "Ryan", "Logan");for (String anElement: anArray){ System.out.print (anElement + " "); } System.out.println( );for ( int i = 0; i < 3; i++){ System.out.print (anArray[i] + " ") }Within the loop’s body, the variable used in the enhanced for statement (e.g., anElement ), can be used anywhere it is syntactically correct to use a variable of its type. An advantage of the enhanced for loop is that it cannot produce an ArrayIndexOutOfBounds error because it does not use a loop variable to access the elements of the array. The disadvantage is that the elements of the array cannot be changed inside the loop. We will see a more practical use of the enhanced for statement in Chapter 13, "Generics."5.11 CHAPTER SUMMARYMany applications require that the statements in a statement block be repeated, and in this chapter we discussed three ways to perform this repetition: a for loop, a while loop, and a do-while loop. The for loop is an automatic counting loop used when the number of times to repeat the statements is known. The do-while and while loops end when their Boolean condition becomes false and they are usually used to detect a sentinel value of the data they are processing. The do-while loop is used whenever the loop’s block should be executed at least once, and the while loop is a more general-purpose loop that can be used in most applications.The loop control variable of a for loop is used to control the number of iterations of the loop. The statement’s initialization expression sets its initial value. At the end of each loop iteration, the increment expression executes, which normally changes the value of the loop variable. The for and while loops are called pretest loops: they test their Boolean condition to continue at the beginning of the loop; the do-while - No longer available |Learn more
Introduction to Programming
Learn to program in Java with data structures, algorithms, and logic
- Nick Samoylov(Author)
- 2018(Publication Date)
- Packt Publishing(Publisher)
Control Flow Statements
This chapter describes one particular kind of Java statementIn this chapter, we will cover the following topics:, called control statements, which allow the building of a program flow according to the logic of the implemented algorithm, which includes selection statements, iteration statements, branching statements, and exception handling statements.- What is a control flow?
- Selection statements: if, if....else, switch...case
- Iteration statements: for, while, do...while
- Branching statements: break, continue, return
- Exception handling statements: try...catch...finally, throw, assert
- Exercise – Infinite loop
Passage contains an image
What is a control flow?
By convention, they are divided into four groups: selection statements, iteration statements, branching statements, and exception handling statements. In the following sections, we will use the term block, which means a sequence of statements enclosed in braces. Here is an example: { x = 42; y = method(7, x); System.out.println("Example"); } A block can also include control statements – a doll inside a doll, inside a doll, and so on.A Java program is a sequence of statements that can be executed and produce some data or/and initiate some actions. To make the program more generic, some statements are executed conditionally, based on the result of an expressionevaluation. Such statements are called control flow statements because, in computer science, control flow (or flow of control) is the order in which individual statements are executed or evaluated.Passage contains an image
Selection statements
The control flow statements of the selection statements group are based on an expression evaluation. For example, here is one possible format: if(expression) do something. Or, another possible format: if(expression) {do something} else {do something else}.The expression may return a boolean value (as in the previous examples) or a specific value that can be compared with a constant. In the latter case, the selection statement has the format of a switch statement, which executes the statement or block that is associated with a particular constant value. - eBook - ePub
Learn C Programming
A beginner's guide to learning C programming the easy and disciplined way
- Jeff Szuhay(Author)
- 2020(Publication Date)
- Packt Publishing(Publisher)
The simplest, yet most restrictive way is the brute-force method. This can be done regardless of the language being used. A more dynamic and flexible method is to iterate or repeatedly loop. C provides three interrelated looping statements—while()…, for()…, and do…while(). Each of them has a control or continuation expression, and a loop body. The most general form of these is the while()… loop. Lastly, there is the archaic goto label method of looping. Unlike other languages, there is no repeat … until() statement; such a statement can easily be constructed from any of the others. Each looping statement consists of the following two basic parts: The loop continuation expression The body of the loop When the loop continuation expression evaluates to true, the body of the loop is executed. The execution then returns to the continuation expression, evaluates it, and, if true, the body of the loop is again executed. This cycle repeats until the continuation expression evaluates to false; the loop ends, and the execution commences after the end of the loop body. There are two general types of continuation expressions used for looping statements, as follows: Counter-controlled looping, where the number of iterations is dependent upon a count of some kind. The desired number of iterations is known beforehand. The counter may be increasing or decreasing. Condition- or sentinel-controlled looping, where the number of iterations is dependent upon some condition to remain true for the loop to continue. The actual number of iterations is not known - eBook - PDF
Elementary Synchronous Programming
in C++ and Java via algorithms
- Ali S. Janfada(Author)
- 2019(Publication Date)
- De Gruyter Oldenbourg(Publisher)
https://doi.org/10.1515/9783110616484-006 6 Automated loops Any process that repeatedly implements a set of instructions, called the range of a loop, is called a loop . Designing this range is the most fundamental part of the job in creating a loop. In other words, knowing what to do in each repetition of the loop and how to use such repetition properly to design the algorithm is of great importance. A kind of loop is based on one or several variables so that, first, the initial values are often assigned to them before starting the loop. Then, a process is performed on the variables in each repetition of the loop. Finally, repeating or exiting the loop is determined by a condition called the repetition (or exiting) condition of the loop. This kind of loop is known as the conditional loop which is discussed in the next chapter. Another kind of loop is called the automated loop which depends on a counter. Three tasks are automatically performed by the compiler in this type of loop: 1. The initial value for the counter is assigned; 2. A constant (positive or negative) amount, called the growth of the loop, is added to the previous amount of the counter in each repetition of the loop; 3. The number r of the repetitions is calculated by the compiler and the range of the loop repeats to the number of r times. That is why this kind of loop is named the automated loop. 6.1 The for template The automated loop template, called hereafter the “ for template ” , or the “ for loop ” is used in the flowcharts with the shape displayed below. The translation of this template into both C++ and Java codes, which is called the for statement , is as follows. for (i=a; i<=b; i=i+step) { loop range } 5 The loop range, in the case of more than one statement, should be grouped by {} . i=a,b,step loop range 156 | Automated loops The items “ i , a , b ”, and “ step ” are called the “variable, initial value, final value”, and “growth value” of the loop, respectively. - eBook - ePub
Beginning Java Programming
The Object-Oriented Approach
- Bart Baesens, Aimee Backiel, Seppe vanden Broucke(Authors)
- 2015(Publication Date)
- Wrox(Publisher)
main method of a class, it is executable.Creating while Loops
A while loop is an alternative loop structure that’s based on meeting a certain condition, rather than iterating a set number of times. The standard syntax of a while loop is as follows:while (/*conditional expression*/) { /*execute these statements*/ }Remember the difference between a for loop and an enhanced for loop: the for loop iterator is initialized in the loop expression, but in an enhanced for loop, an array must be declared somewhere prior to entering the for loop. A while loop is similar to the enhanced for loop in this way. You will need to initialize some variable before the while loop that will be evaluated as part of the conditional expression.When the execution of a program reaches a while loop, it will first check to see if the conditional expression evaluates to true . If so, it will enter the loop and execute the statements inside the loop. When the end of loop is reached, it will return to the conditional expression and check if it still evaluates to true . If so, the loop will be repeated. It should be clear, then, that evaluation of the conditional statement should change at some point during the looping process. Otherwise, the loop iterations will never end. Consider the following code example:int i = 10; while (i > 0){ System.out.println(i); }Here, the integeriis given the value of 10 . When the while loop is first encountered, the conditional expressioni > 0is evaluated: 10 is greater than 0, so the expression is true . The program outputs "10" to the console, then returns to the start of the while loop again. The conditional expressioni > 0is evaluated again, butiis still equal to 10 and 10 is greater than 0 so the expression is still true . Again, you’ll see an output of "10" to the console. This will continue indefinitely, creating an infinite loop. To prevent this, you can add a statement inside the while loop to alter the value of the variablei
Index pages curate the most relevant extracts from our library of academic textbooks. They’ve been created using an in-house natural language model (NLM), each adding context and meaning to key research topics.











