I try this below program which find midpoint between two no.
class FindMidPoint
{
public static void main(String args[])
{
int i, j;
i = 100;
j = 200;
// find midpoint between i and j
while(++i < --j) ;
System.out.println("Midpoint is " + i+" OR "+j);
}
}
Output:
Midpoint is 150 OR 150
But If I make changing in while condition that is
while(i++<j--)
Then output is:
Midpoint is 16 OR 14
I also refer the below Link then also I'm not understanding the difference between ++i & i++ in this program.
what is the difference between i++ & ++i in for loop (Java)?
Please explain me if anyone have idea about.
If you have i = 1 and j = 2. The first one compares 2 < 1 and the second one compares 1 < 2. (In the first one the decrementation/incrementation are done before the comparing, while in the second one they are done after the comparison)
The ++ before any variable present in an expression indicates that increment has to be made before the expression executes.
For example
int i=2;
int x = ++i + 2
Here since ++ is present before i, so first there will be an increment on i, and then the expression will be executed.
The steps involved is :
Step 1 :
++i : i=(i+1) = 3
Step2:
int x = ++i + 2 = 3+2=5
So after this expression executes : x=5 and i=3
But if you consider post increment:
For example:
int i=2;
int x = i++ + 2;
This means that increment will happen after the line is executed.
The steps are:
Step 1 :
int x = i++ + 2 = 2 + 2 =4; // i is still 2 here since the increment didn't happen by now
Step 2:
i++ : i=i+1 = 3;
So after the execution x=4 and i=3
++i
You could think something like increment the value and then use the incremented value in the expression
i++
Use the value in the expression before it gets incremented
Say we have the following code:
int i = 100;
int j = ++i + 50; // statement 1
Here j would have a value of 151, saying increment i first and then evaluate the expression, so 101+50.
Lets way we have
int j = i++ + 50; // statement 2
Here j would have a value of 150, saying evaluate the expression first, then increment the value i
However, i would be 101 after executing the second statement
Basic difference between pre and post should be applied here.
Pre increment operator ++i : equivalent to replacing i with i+1 and using result in the expression.
while(++i < --j);
//read as while( (i_new = i_old+1) < (j_new =j_old -1) );
//In next expression i will be value of i_new and j value will be j_new
Post increment operator i++ : equivalent to using the same value of i in the current expression. And in the next immediate expression use the increased value.
while(i++ < j--);
//read as while( (i_old < j_old );
//In next expression(even in next iteration of same above while) i will be value of i_old+1 and j value will be j_old-1
Its all about precedence, in java every operator has a precedence, pre-increment has very high precedence while post-increment come at last as compared to other operators.
Related
If I were to make a for loop like so:
for(int i = 1; i<=25; i++){
if((i % 2) == 0){
i += 5;
}
}
Would I be able to change the value of i like this to where when i reaches 2, it adds 5 to the value so now i = 7?
Yes the value of i will be changed but it becomes 8 ,not 7.
Because when i = 1, then the condition i%2==0 doesn't satisfy and the if statement will be terminated without performing the addition. Then the value of i increment by 1.Now i=2 which satisfy the if condition. Then value of i will be i=2+5=7. Now the if statement will terminate and for the step expression i++ the value increment by 1.
So now the value of i = 8.
This question already has answers here:
How do the post increment (i++) and pre increment (++i) operators work in Java?
(14 answers)
Closed 2 years ago.
The code I used is
int i=0, j=0;
j=i++ + ++i;
And the output I got is i=2 and j=2
Could anyone explain how this happens!
i++ will "retrieve" 0 and then add 1 to i. ++i will add 1 to i and then retrieve its value. Thus, this is equivalent to j = 0 + 2. It also adds 1 to i twice. Hence, i = 2 and j = 2.
The expression is evaluated in below steps:
Step 1 : j = i++ + ++i; => j = 0 + ++i; step result i = 1 and j = 0 (post increment will update the value but returns the old value)
Step 2 : j = 0 + ++i; => j = 0 + 2; step result i = 2 and j = 0 (pre increment will update the value and returns the updated value)
Step 3 : j = 0 + 2; => j = 2; step result i = 2 and j = 2 (direct addition and assign value to j)
i++ increments the value of i and returns the previous value it held and ++i increments the value and returns the new value. So in your equation the i++ increments i by 1 and returns the previous value 0. And as i is already incremented by 1 so now value of i is 1. Then this i will be incremented in ++i and return value will be the new value 2. So 0+2 is the value of j in the equation.
I've been scratching my head over why Java will go beyond a specified condition in some loops, while seemingly adhering to the condition in other loops. I know it's a lack of understanding on my part, but I'm confused as to when I should go over or adhere to the condition when I'm manually calculating code.
As an example, I've put in a short for loop which has an end result of 15 in iTotal, and 0 in iNumber. When I originally did the calculation on paper step by step, I ended up with the answers of 14 in iTotal, and 1 in iNumber. I assumed that the code would not go below one, as the condition was greater than zero, not equal to or greater than zero.
My original attempt -
iTotal
0
5
9
12
14
iNumber
5 4 3 2 1
int iTotal = 0;
for (int iNumber = 5; iNumber > 0; iNumber--)
iTotal = iTotal + iNumber;
In comparison, the below code snippet will at 19 with a condition of less than 20, with the last statement being value of x : 19. I calculated that correctly, but I'm not sure why the above code ignores the condition and goes to zero, while the below code adheres to the condition and stops at 19.
for(int x = 10; x < 20; x = x+1) {
System.out.print("value of x : " + x);
System..out.print(num2 + " " + num1);
Could anyone clarify how java interprets when to go over or stop at specified conditions?
In comparison, the below code snippet will at 19 with a condition of
less than 20, with the last statement being value of x : 19. I
calculated that correctly, but I'm not sure why the above code ignores
the condition and goes to zero, while the below code adheres to the
condition and stops at 19.
What you said is incorrect. The last statement printed is 19 but the last value of x is 20. This loop that you have given does in fact execute 20 times. A for loop in Java like the one you given has 3 components an integer to use as a count, a condition to test, and how to transform the count variable. In a general form it looks like this:
for(count variable, condition, transformation){
//Code goes here
//End loop
}
This for loops executes until the condition is no longer true, which is caused by applying a transformation of some sort the count variable.
Using the for loop you gave as an example:
for(int x = 10; x < 20; x = x+1) {
System.out.print("value of x : " + x);
System..out.print(num2 + " " + num1);
}
We create the count variable (int x) and set it equal to 10.
We check the count variable (int x) against the condition ( x<20 ) and evaluate the result, x < 20 == true so the code within the loop is run. At the end of the code, which I have marked "End Loop" above the transformation (x + 1) is applied to the count variable before the condition is tested again to see if the loop should proceed.
x = 11 now because x was equal to 10 but we added one as specified at the end of last loop. x < 20 == true is still true so the code within the loop will be executed again. This is continued in this way until the last number.
When x = 19 we test against the condition as we have been doing and see if x < 20 == true is still true, which it is so the code is executed. When the code execution ends, the count variable is again incremented, so x = 20.
With x = 20we once again test against x < 20. This time x < 20 == false so the code inside the loop is not executed nor is another transformation applied to the variable. At this point, when the condition becomes false the loop ends. So because we said x < 20 and not x <= 20 on the 20th loop, when x = 20, this code:
System.out.print("value of x : " + x);
System..out.print(num2 + " " + num1);
will not run. This means that the final output of the program would occur when x = 19 not when x=20 although if you were still able to access the count variable after the loop ends (which I believe you can do with a debugger) you would see x=20
The first loop does this:
iTotal = 0
iTotal = 5
iTotal = 9
iTotal = 12
iTotal = 14
iTotal = 15
Loop end
also as the first loops transformation is written as x-- instead of x - 1 the second loop can be rewritten as:
for(int x = 10; x < 20; x++) {
System.out.print("value of x : " + x);
System..out.print(num2 + " " + num1);
}
in Java the ++ operator increments by 1, it is the same as x+1.
Your first loop
for (int iNumber = 5; iNumber > 0; iNumber--)
iTotal = iTotal + iNumber;
is 5+4+3+2+1 = 15 (you must have printed iTotal before you added the first iNumber). Your second loop is similar the loop body isn't entered when the condition evaluates to false.
int x = 10;
for(; x < 20; x = x+1) {
System.out.print(x + " ");
}
System.out.println(x); // x is 20
as 10,11,12,13,14,15,16,17,18,19,20 but at twenty the loop terminates.
The condition is checked before each loop, not after. So in your first example, the logic would go:
iNumber = 5
first loop iteration
check iNumber > 0. 5 > 0, so continue the loop
add 5 to iTotal (iTotal=5 after this)
decrement iNumber
second loop iteration
check iNumber > 0. 4 > 0, so continue the loop
add 4 to iTotal (iTotal=9 after this)
decrement iNumber
...
fifth loop iteration
check iNumber > 0. 1 > 0, so continue the loop
add 1 to iTotal (iTotal=15 after this)
decrement iNumber
sixth loop iteration
check iNumber > 0. 0 > 0 is false, so break out of the loop
A similar process happens with the second loop.
int x = 10;
x += x++;
System.out.println(x);
why the answer of above statement is 20 ?
The operator += is an addition assignment operator. Like Alya said above, x += x++ is equivalent to x = x + x++, which in your case is x = 10 + 10. However, it's a very messy statement and I'll explain why towards the end of this post.
Now, you're probably thinking "Why is it 20 and not 21 (10 + 11) since you have the ++?" and that's valid. There's actually a difference between a post-increment and a pre-increment. x++ is the post-increment and will actually evaluate the value of x first and THEN increment x, while ++x is the pre-increment which will increment x and THEN evaluate the value of x.
For example, x = 10; System.out.println(x++); System.out.println(x); will print 10 and then print 11 because the first print line prints x and THEN performs the ++ calculation, making x 11 which the next line prints. Conversely, x = 10; System.out.println(++x); System.out.println(x); will print 11 on both print statements.
Going back to why I said x += x++; is very messy is because technically the ++ operator isn't performed in this case. x++ is technically the same as x=x+1 and remembering that x+=y is the same as x = x+y) , the line x += x++; is kind of like saying x = x + (x = x + 1); which is kind of weird looking because you do 2 assignment statements in one and won't actually "work how you want it". Back to your example int x = 10; x += x++; if you print x, you will get 20 even though you could look at it as: x is now the value of x + the value of x, then finally + 1 to it. But unfortunately, that's not how it works.
To solve your problem, if you change your code from a post-increment to a pre-increment, then it should work, ie: x+=++x; will print your 11 but I would argue the that's quite unreadable and a bit confusing. x+=x; x++; System.out.println(x); is easier to follow.
x++ will execute first. It returns x and then increments x by 1.
Finally, the += operator will add to x the return value of x++, which was 10.
Thus, x will be 20 and it will overwrite the changes to x by the statement x++.
So first x is initialized to be 10. Then the x++ has higher precedence so that gets carried out first. the "++" is a post-increment in this case (because it is after the variable as opposed to pre-increment which would be ++x). Post-increment means "first use the variable then increment it by one" so in this case it first uses x to be 10 then increments it to 11 after it is used. Then we look at the "+=" which is short hand for "x = x+x++". so we have x = 10+10 which = 20. If you were to carry this out again it would equal x = 20+20 = 40.
In this particular case, the x++ isn't necessary as x is reassigned the value after it is incremented each time.
int x = 10; x += x++;
will equal to x=x+x
where x++ mean use the x value then increament it , so it's value will be 10
so the result will equal 20
if you want to see the change of the x , see this example:
int x = 10;
int y = 10;
y +=x++;
System.out.println(y);
System.out.println(x);
will print :
y=20
x=11////////////according to x++ and without to overwrite it
//
// Shows how increments work.
//
int i = 0;
System.out.println(i);
i++; // Add one
System.out.println(i);
i += 2; // Add two
System.out.println(i);
i += 3; // Add three
System.out.println(i);
++i; // Add one
System.out.println(i);
i += i; // Added itself
System.out.println(i);
//
// Uses increments and assigns.
//
int v = 0;
v = i++; // Increment after value copy
System.out.println(v);
System.out.println(i);
v = ++i; // Increment before value copy
System.out.println(v);
System.out.println(i);
//Output
0 -
1
3
6
7
14
14
15
16
16
x+=x++ first assigns the value to x and then increments (post-increment)
x+=++x first increments then assign the value to x (pre increment)
there are two types of increments/decrements in programming
1. pre-increment/decrement
2. post-increment/decrement
In programming both of these have same operations but differ in there nature as they both used for increment or decrement; they can be written as,
x+=1; (increment by 1)
x-=1; (decrement by 1)
you can use a variable instead in the above cases as well
I just want to make sure if I am doing this correct. I am trying to count the number of operations performed for the worst case scenario in java
int sum = 0;
for (int i = 0; i < n; i++ )
sum++;
Is the number of operations 2+3n or 3+3n?
I got the answer from counting int sum = 0 and int i = 0 for the "2" and i < n, i++, and sum++ as the "3n". Or is it a 3 rather than a 2 because I have to count i < n before going through the loop?
But either way, is the theta characterization going to be Θ(n)?
Now what if there is a nested for loop like this:
int sum = 0;
for (int i = 0; i < n; i++ )
for (int a = 0; a < i; a++)
sum++;
would it be 3+n*(6a+2) = 6na+2n+3? with Θ(n^2)?
if i change the inner for loop from a < i to a < i*i, would the equation still hold as above or change?
Maybe it's easier to count the number of executions of each statement if there's only one per line:
int sum = 0; // 1 time
int i = 0; // 1 time
while (i < n) { // n+1 times
sum++; // n times
i++; // n times
}
Hence, T(n) = 3*n+3 = Θ(n).
int sum = 0; // 1 time
int i = 0; // 1 time
while (i < n) { // n+1 times
int a = 0; // n times
while (a < i) { // 1 + 2 + ... + n = n*(n+1)/2 times
sum++; // 0 + 1 + ... + n-1 = n*(n-1)/2 times
a++; // 0 + 1 + ... + n-1 = n*(n-1)/2 times
}
i++; // n times
}
Hence, T(n) = 3*n+3 + n*(n-1) + n*(n+1)/2 = Θ(n^2).
I would it count as 3+3n, because when n = 0 then you execute the following 3 commands:
int sum = 0;
int i = 0;
i < n
Now when n != 0 then you execute the declarations once (2) and for each execution of the loop each command once (3n) and the final comparison (which fails; 1). That makes 3+3n.
And yes, that would be Θ(n) (and O(n) and o(n)).
Yes, exactly. Look here for a mathematical definition.
It doesn't matter if you use 2+3n or 3+3n. You have lim_n->infty ( (3+3n)/n ) = 3 (both lim sup and lim inf are the same here). Because of that limites (which is greater 0 and not infinity), you know that is Big Theta n.
In your second example, you cannot use the inner-loop variables (a or i). The amount of sum++ operations:
When i == 0: zero sum++s are executed.
When i == 1: exactly one sum++ get's executed (when a==0).
When i == 2: 2 sum++s (a==0 and a==1)
When i == 3: 3 sum++s (a==0, a==1 and a==2)
...
When i == n-1: n-1 sum++s (a==0, a==1, ... and finally a==n-1)
That are all sum++s in your code. So let's sum them together:
0 + 1 + 2 + ... + n - 1
That is the same as (n-1)(n-2)/2.
I.e. we have Θ(n^2 + n). The same thing for a++ and a < i (well, one more to be exact but that doesn't matter). The amount of i++ ops is just n. So you end up with Θ(n^2).
It'll be 3+3n, because the comparison runs for each value of i from 0 to n inclusive. I'd says that's O(n).