Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
This is a very simple for loop:
for(int i=0;i<=100;i++)
{
System.out.println(i);
}
I know how it mostly works, but I don't understand how the i++ works at the end: its supposed to add 1, if I'm correct, but when it prints out the i, it prints out 0 and then 1.
Why doesn't it just start out with 1 because of the i++? Why does it still just print out the original value instead of the i++ value?
A for loop works as follows:
Initialization is done (int i=0 in your case; only executed once)
Condition is checked (i<=100 here), if condition is false leave the loop
Code within the braces is executed (System.out.println(i); in your case)
Update statement is executed (i++)
Goto 2.
It's similar to this while loop :
{
int i = 0;
while (i <= 100) {
System.out.println(i);
i++;
}
}
i is incremented only at the end of each iteration.
Because the increment is evaluated after the first execution of the loop body. This is by design, and remember that programmers generally treat 0 as the first number. For example, with arrays and String(s) the first element is 0.
The Java Tutorial on The for Statement says,
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) {
statement(s)
}
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.
Here it is how it works
The for statement is used to repeat a block of statements enclosed in curly braces. An increment counter is usually used to increment and terminate the loop. The for statement is useful for any repetitive operation, and is often used in combination with arrays to operate on collections of data/pins.
There are three parts to the for loop header:
for (initialization; condition; increment / decrement) {
//statement(s);
}
The initialization happens first and exactly once. Each time through the loop, the condition is tested; if it's true, the statement block, and the increment is executed, then the condition is tested again. When the condition becomes false, the loop ends.
Credits : For
If you use ++ operator as prefix like: ++var; then, the value of operand is increased by 1 then, only it is returned but, if you use ++ as postfix like: var++; then, the value of operand is returned first then, only it is increased by 1.
For example,
class Example
{
public static void main(String[] args)
{
int var = 1;
System.out.println(var++);
System.out.println("\n" + ++var);
}
}
the following program prints
1
3
In the prefix form, the increment or decrement takes place before the value is used in expression evaluation, so the value of the expression is different from the value of the operand. In the postfix form, the increment or decrement takes place after the value is used in expression evaluation, so the value of the expression is the same as the value of the operand.
Think of the i++ as the statement that says "Use then increment"
The value of i will first be used in the loop and then incremented by 1.
So the loop is executed once, then the declaration and incremental statements checked.
Related
I just want to understand the difference between for(int i =1;i<4;i++)
and for(int i =1;i++<4;)
The first one prints 123
The second one prints 234
for(int i =1;i<4;i++)
System.out.print(i);
for (int i =1;i++<4;)
System.out.print(i);
I do not understand why are the results different, I expect 123 from both of them.
This loop:
for (int i =1;i++<4;)
increments i before System.out.print(i), which means the first printed value of i will be 2.
In the standard for loop, i is incremented after the loop iteration. From the Java Tutorials:
The increment expression is invoked after each iteration through the loop; it is perfectly acceptable for this expression to increment or decrement a value.
In the second example, it is incremented in the expression where it is evaluated, but because the post increment operator is used, the value evaluated is the old value. This means that by the time it is printed, it has already been incremented.
To explain I've refactored the statements only by using curly braces...
for(int i =1;i<4;i++) {
System.out.print(i);
}
System.out.println();
for (int i =1;i++<4;) {
System.out.print(i);
}
System.out.println();
Inside the first 'for' statement - the third clause with "i++" doesn't happen until the contents of the loop is executed.
Next consider the second 'for' statement, the comparison clause (the 2nd clause). that will be completely evaluated before the contents of the loop is started. So going into the first iteration, "i++" gets evaluated as "1" for the purpose of the comparison, but immediately gets incremented after the boolean clause is evaluated.
So when it hits the print statement it's already equal to 2. (and so on)
I hope that helps!
[edited the post to be more clear]
The code below is supposed to represent a number of trial runs, and within each trial assume a is the number of cases that need to be checked.
while(testCaseAmt > 0) {
for(int i = 0; i < a; i++) {
if(some condition)
//code when i is not the last element
//then I would like to break/return here.
if(i = a - 1)
//code when i is the last element
//then if the above if statement never runs during the a amt of trials
//i will print out something else
}
testCaseAmt--;
}
My question is if there is another way to access specifically the last element within a for loop to give it specific instructions. I want to loop through a set trials and if they meet the first condition, I stop the loop immediately and return. However, if the condition isn't found I still need to print out not found.
Cheers.
To me this seems related to "off-by-one errors" or "fencepost errors", see here.
If the code you're executing when i is not the last element isn't too complex, it could be better to just end the for loop one iteration earlier and write the specific code for the last element outside the for loop.
Adding an if statement inside a for loop where you know it will only be true at the very last iteration could be seen as bad-style.
You can define a boolean conditionMet = false before the for-loop and iterate until i < a-1.
If some condition applies, execute your code, then set conditionMet = true and break out of the for-loop.
After the for-loop, check if !conditionMet and in this case, execute the code for the last element.
I am a beginner in Java, can somebody please explain me what this code means and how it comes to the answer of 15. I understand for loop but not what it is doing with int max.
int count;
int max = 3;
for (count = 1; count < 7; count++) {
max = max + 2;
}
System.out.println(max);
So for loops are counting loops. The can do something a certain number of times. In this case count starts at 1 and goes until 6 because last run that count is less than 7. So in effect the amount of max that starts at 3 and then has 2 added to it 6 times, the number of times the for loop runs. Hope this helps! I just finished my first year of CS, so Im glad I had a chance to help.
Max is initiated at 3. The code is adding 2 to max each time it goes through the for loop, a total 6 times (7 - 1). 3 + 2 + 2 + 2 + 2 + 2 + 2 = 15.
The for Loop:
A for loop is a repetition control structure that allows you to
efficiently write a loop that needs to execute a specific number of
times.
A for loop is useful when you know how many times a task is to be
repeated.
From the definition, you want to do the addition which the task 6 times. In better sense, in your case, the relation ship between for loop and addition process is the for loop do the addition the 6 times.
For better understanding read following
Here is the flow of control in a for loop:
1. The initialization step is executed first, and only once. This step allows you to declare and initialize any loop control variables. You are not required to put a statement here, as long as a semicolon appears.
2. Next, the Boolean expression is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and flow of control jumps to the next statement past the for loop.
3. After the body of the for loop executes, the flow of control jumps back up to the update statement. This statement allows you to update any loop control variables. This statement can be left blank, as long as a semicolon appears after the Boolean expression.
4. The Boolean expression is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then update step, then Boolean expression). After the Boolean expression is false, the for loop terminates.
Note: read step 2 for your better understanding
This question already has answers here:
How does a for loop work, specifically for(;;)?
(6 answers)
Closed 4 years ago.
Like many other question explained that while(true) {} is an infinite loop and so is for( ; ;) my question is while(true) makes sense the conditions is always true but there is no vivid condition true/false in for( ; ;) so how is the later an infinite loop.
According to Java Language Specification, section 14.14.1.2:
for ( ForInitopt ; Expressionopt ; ForUpdateopt ) Statement
If the Expression is not present, or it is present and the value resulting from its evaluation (including any possible unboxing) is true, then the contained Statement is executed.
Since the standard treats missing expressions and expressions evaluating to true in the same way, the for loop with the missing expression is equivalent to an infinite loop.
You do not specify any condition to continue the loop, so it is executed forever.
The three parts of for loop: variable initialization, condition and variable update are optional. If the condition is absent, it is evaluated as true. The loop continues till something else in for loop block stops it. Since in your example for loop is empty, it is an infinite loop.
A loop becomes infinite loop if a condition never becomes false. The for loop is traditionally used for this purpose. Since none of the three expressions that form the for loop are required, you can make an endless loop by leaving the conditional expression empty.
When the conditional expression is absent, it is assumed to be true.
The loop for( ; ;) is garbage. If that provides an infinite loop, it is at the control of that specific languages compiler that turns it into a infinite loop.
in Java, when using a for loop, you need to write a termination condition of course. This is my for loop:
for(int i=1; i<=infix.length()-2; i++){
if(infix.charAt(i)==' '){
infix=infix.substring(0,i)+infix.substring(i+1);
}
(infix is a string i got as a parameter). As you can see, I'm using substring inside the loop, which shortens the length of infix, which means that the termination condition of the loop is changed after every single iteration.
My question is this: Is the value "infix.length-2" saved at the beginning of the for and doesn't change later on? Or it changes every time, and if so, what happens with i? When will the for stop? Is there a chance for an index out of bounds or something like that?
Thank you very much in advance! :D
The string length gets calculated every loop, and your for could throw an IndexOutOfBoundsException if your string becomes too short.
IMHO yours is a very bad practice, for loops are intended to make a determined number of loops and should never be stopped, also their stop condition should never be changed inside the loop, you should use a while if you don't know how many iterations you want to do. But this is my personal opinion :)
Yes, you can change the upper limit. No, it's not cached at the beginning of the loop. Yes, anything you do wrong might cause errors -- but this is neither especially dangerous or uncommon. On the contrary, it's quite common.
you can put multiple end criteria in a for loop, just for a sample syntax
for(int i = 0; i < 2 || i< 5; i++)
System.out.println(i);
As a short hint: Your for-loop is equivalent to the following while-loop
{
int i=1;
while(i<=infix.length()-2) {
if(infix.charAt(i)==' '){
infix=infix.substring(0,i)+infix.substring(i+1);
}
i++
}
}
That means the condition of a the for-loop is evaluated in the same way as the condition of a while-loop. There is nothing special about it.
My question is this: Is the value "infix.length-2" saved at the beginning of the for and doesn't change later on? Or it changes every time, and if so, what happens with i?
It changes with every iteration of the for loop. i gets incremented, with each iteration.
When will the for stop? Is there a chance for an index out of bounds or something like that?
The for loop will stop when the termination condition is true.
i<=infix.length()-2.
i initialized to 1 will result in a loop that terminates if the length
If you modify the termination condition variables with incorrect logic, then you have a chance of running into an infinite loop.