Java For Loop - What is i++ doing in For Loop? - java

So program problem, the program will print 4. My question is what does i++ do in the for loop? The i++ is throwing me off a bit because I'm thinking when the for loop runs, i=1 intially, the for loop runs, now i = 2, but because there is an i++ inside the for loop after total+= i, my thinking is that it goes from i = 1 to i = 3.
public class LoopExample {
public static void main(String[] args) {
int total = 0;
for (int i = 1; i < 5; i++)
{
total += i;
i++;
}
System.out.println(total);
}
}

Your thinking is right: you are incrementing i IN the for loop on top of the increment statement.
Just remove the i++ statement within the for loop if you want i to go from 1 to 5 with step of 1.

Your hypothesis is right the i++ inside the loop increment the i.
It's equivalent to
for (int i = 1; i < 5; i = i + 2) {
total += i;
}

Increments are happening twice here, yes you are correct here: i will be 1 then it will be 3 then it will be 5.
Because i is incremented twice, once inside the loop and then in for statement.
for loop has 3 operations: Initialization, condition check, increment/decrement
Initialization happens only once.
Condition is checked until it return false.
Increment/decrement operation is your i++
for (int i = 1; i < 5; i++)//int i=1 is initialization, which happens once. i<5 is condition, i++ is increment.
Here is how your loop works:
i=1
i<5 is true so it goes inside the loop
change the value of total to 1. 0 = 0+1
total+=total+i
increment the value of i by 1. Now i = 2.
now the control goes to the third operation of for loop that is
;i++. Again the value of i is incremented by 1. i=3
If you want increments in 1, delete the i++ statement inside the for loop
OR in the loop itself like this:
for(int i = 1; i < 5; )

Related

Why won`t this simple function output anything if I don`t use a break statement?

Function here is , implemented to find the largest number in an array .. if I don't put a break statement after while , it won't print out anything . I need someone to explain me how this code works .
What I was thinking is that ,
1- we go into first loop , and then the second loop..
2- we have the first and second elements compared in the while loop .
3- if condition is true , int largest is set to the large value..
4- and then we go back to the outer for loop again .
Isn't this true ? aren't we going back to the outer for loop after while statement is issued once ? If I don't put a break , while condition is true , the program won't come out of the loop , is that so ?
I`m testing the code in main , by calling this function and passing in an integer array . I forgot to mention this before . Sorry .
Thank you .
public int returnMax(int[] nums) {
int largest = 0;
for (int i = 0; i < nums.length; i++) {
for (int j = 1; j < nums.length; j++) {
while (nums[j] > nums[i]) {
largest = nums[j];
break;
}
}
}
return largest;
}
if nums[j] is larger than nums[i] it goes into your while loop.
In your while loop you never change any variable except for largest. Largest is never used except for returning a value. This causes an infinite loop because the next iteration your while expression is the still the same.
The program can't leave the while statement, because the condition is never changes and is always true (once it's true). You should replace the while with an if.
if (nums[j] > nums[i]) {
largest = nums[j];
System.out.println(largest);
}
Also you out commented System.out.println(largest);, so it will never be called
The first time your code gets to the while loop, j = 1 and i = 0, which means that j is greater than i. These numbers don't change inside this loop. Thus, the loop will never end and the code won't proceed.
You don't need 3 loops for this simple operation. Try the below.
public static int returnMax(int[] nums) {
int largest = nums[0];
for (int i = 1; i < nums.length; i++) {
if (largest < nums[i]) {
largest = nums[i];
}
}
return largest;
}
Kind Regards

How does that for loop doesn't goes out of bounds with unidimensional array in JAVA?

Take a look :
int[] v = new int[10];
for (int i = 0; i < v.length; i++) {
for (int j = i + 1; j < v.length; j++) {
if (v[i] > v[j]) {
aux = v[i];
v[i] = v[j];
v[j] = aux;
}
}
}
This works perfecly. But can someone explain how?
How this array DOES NOT goes out of bounds even if I start j with i + 1 ? How does this works?
You have confused the initialization with condition. The syntax for for loop() is-
for(initialization; condition; updation)
{
statement(s)
}
So even if you start j from 1 ( j = i+1 and initial value of i = 0), j will update only till it is equal to the length of the array v i.e., 10. So the moment, j = 10 ( when i = 9), the control will come out of j for loop() and when it will transfer to i for loop(), i will be updated to 10, thus meeting it's condition and moving the control out of i for loop() also.
I think you need to go back to basics on for loops
a for loop can be defined as for(before starting;continue when true;do at end of pass))
So it doesn't matter what your start value is, as soon as j is equal to v.length it will stop. It just does 1 less loop that if you started at i.
Your for loops are made up of a variable to keep track, the condition and the iteration. In your code, the condition of the for loops states that the variable that is keeping track cannot go past the length of v. Therefore, during the sort (because that's what the code is), the inner loop compares all of v's values using j as the index to swap if they meet the if condition. The outer loop is just there to make sure that each index of v is checked and are in the right place.

Java modulus operator and PreIncrement - SCJA

Im revising for my SCJA exam at the minute and im confused by this question and answer. The question is what is the result of running and compiling the code.
public class Test{
public static void main(String args[]){
int counter = 0;
for(int i=0; i< 4; ++i){
for(int k=0; k< 4; ++k){
system.out.println("Hello - "+ ++counter);
if((k % 4) == 0)
break;
}
}
}
}
So the answer they give is "Hello-1" because 0 % 4 = 0
But my question is should k not be 1 because its been pre-incremented?
Thanks in advance!
A for loop has the following structure:
for (initialization; condition; update)
The update is executed after every execution of the loop.
Therefore the following two loops are identical:
for (int i = 0; i < 10; i++) {
and
for (int i = 0; i < 10; ++i) {
my question is should k not be 1 because its been pre-incremented?
The ++k happens at the end of the loop iteration, i.e. after the if statement.
It makes no difference whether it's ++k or k++; in either case the first value of k is zero.
So the answer they give is "Hello-1"
This is clearly incorrect, since counter is never incremented and stays at zero throughout the program.
k cannot be 1.
This is because when a for loop runs, it only updates after it has executed all the code within the loop. Since the loop breaks even before the first iteration is completed, k remains 0.

Why is for/while loop variable incrementing by 1 after loop exit? Unwanted side effect

Here is the code -
int i = 0;
System.out.printf( "\n%d\n\n", i ); // show variable i before loop
for( i = 0; i < 8; i++ )
{
System.out.printf( "%d\t", i );
}
System.out.printf( "\n\n%d\n", i ); // show variable i after loop
Here is the output -
0
0 1 2 3 4 5 6 7
8
My problem arises when I want to use the variable i after the exit of the for loop. I would assume that i is reading 7, the 8th increment in zero based counting but it actually reads as 8!!! One more increment to variable i has been made on loop exit.
In order to remedy this I would have to do something like i-- at the end of the loop and before using it in any further code. This seems to me to make the code harder to understand.
Is there a better solution?
When i is 7, the condition i < 8 is still fulfilled, so there is no reason to exit the loop.
It is not very clear to declare the loop variable before the loop and use it afterwards anyway. Rather, consider declaring the loop variable with the loop statement.
int numIterations = 8;
for(int i = 0; i < numIterations; i++) {
// ...
}
// continue doing something with numIterations, or numIterations-1
If using numIterations-1 really bothers you, you could also instead use int maxCounter = 7 and use i <= maxCounter instead as loop invariant.
When you say
for( i = 0; i < 8; i++ )
the middle part, i < 8, is the loop invariant: as long as it holds, there will be a next iteration. Therefore once you leave the loop, it is because the invariant holds no longer and i cannot possibly be less than 8.
If you want something that is easier to read do the following:
int start = 0;
int end = 7;
System.out.printf( "\n%d\n\n", start );
for(int i = start; i <= end; i++ )
{
System.out.printf( "%d\t", i );
}
System.out.printf( "\n\n%d\n", end );
The loop exits when i == 8, because the loop condition says: keep iterating as long as i < 8. Or to put it another way: stop iterating when i >= 8.
So the last i++ inside the loop will assign 8 to i, exiting the loop. That explains the results you're obtaining, and they're as expected. Perhaps you incorrectly assumed that the last i++ isn't executed before exiting the loop.
To obtain the behavior you want, try this instead - the intent of the code is clearer:
int i = 0;
int iterations = 8;
System.out.printf( "\n%d\n\n", i );
while (i < iterations) {
System.out.printf( "%d\t", i );
i++;
}
System.out.printf( "\n\n%d\n", --i );
It's correct, otherwise it would never exit because 7 < 8.
In this code is of course useless to add more logic because you already know that at the end of the loop the variable will always be the same. I think you need it in a more complex code with conditionals statements, so in that case you can do this:
int i = 0;
System.out.printf( "\n%d\n\n", i ); // show variable i before loop
for( i = 0; i < 8; i++ )
{
if ( i == 3 ) // just for example
break;
System.out.printf( "%d\t", i );
}
System.out.printf( "\n\n%d\n", i ); // show variable i after loop
and this will print:
0
0 1 2 3
3
This is really simple if you know the order of operation
STEP_1 - Action before body operation.
SETP_2 - Evaluate logical expression that continue operation if true.
STEP_3 - Perform body operation.
STEP_4 - Action after body operation.
So:
for(STEP_1; STEP_2; STEP_4) {
STEP_3
}
Usually in step 1 we initialize our variable and in step 4 we modify it for next evaluation of loop.
int i = 0;
for(; i< 8; i++) {
}
The loop breaks when i == 8, as is declared before loop the value stay.
In the loop the variable i is incremented until it reaches 8 or more at which point the condition triggers leaving the loop.
This is just the way it works.
So you have two options that I can think of.
subtract one from the variable i after the loop.
put an if statement in the loop so that when i equals 7, it does a break.
for (i = 0; i < 8; i++) {
if (i == 7) break;
}
Another option would be do use a do while as in:
i = -1;
do {
i++; // increment i so that it is at the correct current value starting with zero
// loop stuff
} while (i < 7);

Does a for loop's while section execute each pass or only once in java?

for example would this be constant or change with each pass?
for(int i = 0; i < InputStream.readInt(); i++)
for(int i = 0; // executed once
i < InputStream.readInt(); // executed before each loop iteration
i++ // executed after each loop iteration
) {
....
}
The first section is executed once before the looping starts. The second section is checked before every loop and if it is true, the loop gets executed, if false the loop breaks. The last part is executed after every iteration.
It executes every time. The for syntax is sugar for
int i = 0
while(true)
{
if(!(i < InputStream.readInt()))
{
break;
}
// for body
i++
}
For times when a control-flow diagram is actually the best graphical representation of a concept.
http://upload.wikimedia.org/wikipedia/commons/0/06/For-loop-diagram.png
I think the main issue is the question: does
i < InputStream.readInt();
get executed each loop iteration? Yes, it does.
In this case it's not changing any sensitive variable, the only variable actually changing in your code is i, but InputStream.readInt() will be run each iteration to make the comparison and will therefore run readInt() again on InputStream.
What about something like:
for (int i=0; i < xObj.addOne().parseInt(); i++)
(given the method addOne returns a string representation of an integer one greater)
Is my "check" incrementing the value that would be incremented if I called xObj.addOne() like normal? Yes. and does it stay incremented to the next loop iteration? Yes.
It's just like doing
int x = 0;
for (int i=0; i < ++x; i++);
This will never terminate, as ++x is always greater than x (which is also i)
What about a nontrivial example?
int x = 6;
for (int i=0; i < x--; i++) {
System.out.print(i+" ");
}
outputs
0 1 2

Categories