I have a small issue performing a subtraction on numbers using prefix and postfix operators.
This is my program:
public class postfixprefix
{
public static void main (String args[])
{
int a = 5;
int b;
b = (a++) - (++a);
System.out.println("B = " +b);
}
}
Doing this, theoretically I am supposed to get 0 as the answer, but however, I am getting a -2.
When I try to individually try to increment the values like in this program:
public class postfixprefix
{
public static void main (String args[])
{
int a = 5;
int b, c;
b = a++;
c = ++a;
System.out.println("B = " +b);
System.out.println("C = " +c);
}
}
I get the values as B = 5, C = 7.
So i get the idea that 'c' takes the value of 'a' from 'b' (Please correct me if i am wrong), but what I want to know is
How can I have it not take the value of 'a' from 'b', and
using prefix - postfix, can I have 0 as an answer when they're subtracted.
If you go through this step by step, you can see what happens:
b = (a++) - (++a); //a is now 5
b = 5 - (++a); //read a, then increment it. a is now 6
b = 5 - 7; //increment a, then read it. a is now 7
b = -2
If you do it the other way, you get:
b = (++a) - (a++); //a is now 5
b = 6 - (a++); //increment a, then read it. a is now 6
b = 6 - 6; //read a, then increment it. a is now 7
b = 0
b = a++;
means:
assign to b the value of a
increase a by 1
c = ++a
means:
increase a by 1
assign to c the value of a
b = (a++) - (++a)
means:
get the value of a (5) (a without the ++)
increase the value of a by 1 (thus making it 6) (the result of a++)
increase a by 1 (++a) (thus making it 7)
assign to b thae value 5-7=-2 (5 from step 1, 7 from step 3)
So i get the idea that 'c' takes the value of 'a' from 'b' (Please correct me if i am wrong), but what I want to know is 1) How can I have it not take the value of 'a' from 'b'
Its not like this, in c = ++a; value is taken from a only, in b = a++; statement, a was incremented but after assigning value to b, and then while c = ++a; a is again incremented and assigned to c (as this is pre-increment now)
2) using prefix - postfix, can I have 0 as an answer when they're subtracted.
you can have like: b = (++a) - (a++); as first a increments first and then the second a (which is now 6) is substracted from first a (still 6). And then the final value of a is 7
int a = 5;
int b, c;
b = a++;
c = ++a;
About this code b has a value 5 because posting fix increment/decrement happens after assingment is completed. So the value is 5.
c has a value 7 because prefix increment/decrement happens before assingment is completed. So the value is 7 beause previous statement made the value of a as 6.
About this code
int a = 5;
int b;
b = (a++) - (++a);
System.out.println("B = " +b);
when brackets are applied, your prefix/postfix operations will be completed first in (a++) - (++a); from left to right fashion.
So firstly if we go left to right
(a++) -(++a)
1. (a++) -- Take 5 from a.
2. (++a) -- 5 becomes 6 with ++a take 6.
3. (a++) - (++a) -- Subtract results of (a++) - (++a) operations which makes it -2.
Solutions for you first query -- How can I have it not take the value of 'a' from 'b', and
int a = 5;
int temp = a;
int b, c;
b = a++;
c = ++temp;
System.out.println("B = " +b);
System.out.println("C = " +c);
**Solutions for you first query has been well explained by Sir #Keppil **
Related
Got two int a and b, need to find the sum of all the numbers between including them too.
Got Recursion Method:
with two if statements, if use only one if statement code work fine,
otherwise fall with StackOverflowError.
public static int getSum(int a, int b) {
int result = 0;
if (a <= 0 && b <= 0) result = getSum(a + 1, b + 1) + a + b;
if (a >= 0 && b >= 0) result = getSum(a - 1, b - 1) + a + b;
return result;
}
How can I fix it?
Lets assume a is 1, and b is 2.
if (a <= 0 && b <= 0) result = getSum(a + 1, b + 1) + a + b;
if (a >= 0 && b >= 0) result = getSum(a - 1, b - 1) + a + b;
The 2nd kicks in:
result = getSum(1 - 1, 2 - 1) + a + b;
So you call: with a = 0, b = 2. That one picks:
result = getSum(0 + 1, 1 + 1) + a + b;
So you are back to call with 1, 2.
And it starts from scratch. Leading into an endless recursion.
So, there are multiple problems with your current approach:
both if conditions might apply. As you use "<=" and ">=", when a or b are 0, both if conditions kick in
worse: as shown, your setup allows to easily go down-up-down-up-... forever
beyond that: a correct "stop recursion" is missing. For certain input, your code will simply always go and call itself, again.
guessing here: you are also missing corner cases, such as a < 0, but b > 0
So, long story short: your whole algorithm is bogus, and you need to step back and rethink what you are doing here!
This doesn't need recursion, but I assume you are trying to learn recursion.
Please see comments for explanation.
public static int getSum( int a, int b ) {
if ( a == b ) { // if both are equal there are no numbers in between - so sum is number itself.
return a;
}
// if a < b then increment a to reach b otherwise increment b to reach a.
// this works even if a or b or both are negative.
// So when you increment a, add 'a' only to current sum and then move forward
// When you increment b, add 'b' only to current sum and then move forward.
return a < b ? a + getSum( a + 1, b ) : b + getSum( a, b + 1 );
}
You don't need those if statements. Just do it as follows:
public static int getSum(int a, int b){
if (b < a) return 0;
if (b == a) return b;
return a + getSum(a + 1, b);
}
a = b-(a-(b = a)); //swapping a and b
also, if a=20,b=10 why does
System.out.println(b = a);
give 20 as result?
a = b-(a-(b = a)); //swapping a and b
It's a way of swapping numeric types without the need of a support variable.
They usually ask you this in interviews.
It is particularly unreadable as it's written in one line, but consider this step by step:
int a = 5;
int b = 2;
a = b - a; // <- -3
b = b - a; // <- 2 - ( - 3) <- 5
a = a + b; // <- (- 3) + 5 = 2
You still can't swap non-numeric types without a temporary variable.
With
System.out.println(b = a);
I guess you wanted to check if b equals a, in which case you should have written System.out.println(b == a), which evaluates to a boolean result.
With b = a, you are assigning a's value to b and then print its result.
This question already has answers here:
Understanding recursion [closed]
(20 answers)
Closed 5 years ago.
I am in a java class at my highschool so I am very new to writing code.
For a recursive method, how does using the word return effect the output? I assume return means and end to the program.
For this program, what would random(15) output? Would it just keep looping until inevitably c was 10 and then return 80? If possible, please break this down step by step as I am having trouble understanding it.
public int random(int c)
{
if( int c > 10)
return random(c - 1);
return c * 8;
}
How does this code differ from this code, that does not have the return keyword.
public int random(int c)
{
if( int c > 10)
random(c - 1);
return c * 8;
}
First of all I'm not sure why you need to ask this question, in fact I think you understand the concept of recursive methods quite good.
First Snippet
As you explained correctly random(15) returns a value of 80.
public static void main(String[] args) {
System.out.println("Result: " + random(15));
}
private static int random(int c) {
if (c > 10) {
System.out.println("c is greater than 10");
return random(c - 1);
}
System.out.println("multiplying c=" + c + " by 8");
return c * 8;
}
Output:
run:
c is greater than 10
c is greater than 10
c is greater than 10
c is greater than 10
c is greater than 10
multiplying c=10 by 8
Result: 80
BUILD SUCCESSFUL (total time: 0 seconds)
Just for explanation, the variable c is decreased by 1 five times and then finally multiplied by 8.
Second Snippet
I just assume that your second method should look something like this:
public static void main(String[] args) {
System.out.println("Result: " + random(15));
}
private static int random(int c) {
if (c > 10) {
System.out.println("c is greater than 10");
random(c - 1);
}
System.out.println("multiplying c=" + c + " by 8");
return c * 8;
}
This time, the output looks different and also the result is different.
Output:
run:
c is greater than 10 // method a
c is greater than 10 // b
c is greater than 10 // c
c is greater than 10 // d
c is greater than 10 // e
multiplying c=10 by 8 // --> random(c - 1); in method e
multiplying c=11 by 8 // happening in method e
multiplying c=12 by 8 // d
multiplying c=13 by 8 // c
multiplying c=14 by 8 // b
multiplying c=15 by 8 // a
Result: 120
BUILD SUCCESSFUL (total time: 0 seconds)
You can see that your variable c is decreased by 1 in each method (a - e) and then equal to 10-15. At the end only the last multiplication matters, which is 15 * 8 of course, and the result of this operation is then displayed as the result.
Cobra_8
Even though you should probably do some research about recursive methods, I'll try to explain the difference as simple as possible.
In your first method, if c > 10 then the method returns the result of the call to itself with the parameter c - 1, this means that as long as c is greater than 10, the method will get called and c will decrease by one until it's equal to 10 to then return 80 (10 * 8).
The second method does nothing special, in fact you can say that it's like only returning c * 8, why? Because you're calling the same method with c - 1 but you're not using the result and the code gets out of the if statement and goes to the return c * 8; so no matter how much is c, the result will always be c * 8.
On the other hand with the first method, it'll get called recursively until c reachs 10 and will then return 80 back to the very first call of the method (see https://introcs.cs.princeton.edu/java/23recursion/ for more informations).
I try to split a string to an array of equal-length substrings and the first thing I do is to calculate how many substrings there would be. While I wrote it myself I used the first expression down below. When I checked an answer given by someone else I saw the second one, which is not very obvious to me. Actually I couldn't figure out why they produce the same result though I could verify with concrete examples. So how do you prove they are equivalent in terms of generating the same result?
int groups = s.length() % subLen == 0 ? s.length() / subLen : s.length() / subLen + 1;
int groups = (s.length() + subLen - 1) / subLen;
Try to substitute s.length() with different values and see how the two calculations arrive at their respective result.
In essence, your version considers two cases that are handled differently and is doing the 'rounding up' explicitly in its second code branch.
The second version adds sublen-1 to the original string length so that the rounding down / truncation of the integer division arrives at the desired result for all given values of s.length().
First let's think about the actual context of the problem, that is , dividing a string, suppose its length is a, into a group of substrings whose lengths are equal, suppose that length is b, and then we know the range of a and b should be a >= b >= 1. If c is the result of the integer division a / b, which always rounds down, and if d is the result of the normal division a / b, and if d is an integer, a + (b - 1) would have no effect on making c bigger because only a + b can increase c by 1. But why does it have to be b - 1 instead of b - 2 or b - 3 etc? Because the minimum of b is 1 and if in b - ? the ? is bigger than 1 there's a chance that b - ? is negative, which means there's a chance that c would be reduced at least by 1 because a could be reduced at least by 1. If d is not an integer, then we know d == c * b + r where r is the remainder and (1) 1 <= r <= b - 1. So (a + b - 1) / b could be written as (c * b + r + b - 1) / b. According to (1) we have b <= r + b - 1 <= 2 * (b - 1), and then have b <= r + b - 1 < 2 * b, and then have (c + 1) * b <= a + b - 1 < (c + 2) * b, and then c + 1 <= (a + b - 1) / b < c + 2, which means c would be increased by 1 exactly when normal division a / b is not an integer.
I was doing a practice Computer Science UIL test form when I came across this problem:
What is output by the following?
int a = 5;
int b = 7;
int c = 10;
c = b+++-c--+--a;
System.out.println(a + " " + b + " " + c);
I put down the answer "No output due to syntax error" but I got it wrong. The real answer was 4 8 1! (I tested it out myself)
Can someone please explain to me how line 4 works?
Thanks
I added some parentheses:
int a = 5;
int b = 7;
int c = 10;
c = (b++) + (-(c--)) + (--a);
System.out.println(a + " " + b + " " + c);
b++ :
b = b + 1 after b is used
c-- :
c = c - 1 after c is used
--a :
a = a - 1 before a is used
Look at it like this:
(b++) + (-(c--)) + (--a)
That should make more sense!
Look at Operator Precedence to see why it works this way.
Look at initialization of c like this, c = (b++) + (-(c--)) + (--a);
They had it compressed and intentionally confusing for your learning purposes. The code is essentially saying this, c = (b + 1) + (-(c - 1)) + (a - 1);
Break up the statement a bit. It's intentionally obfuscated.
c = b++ + -c-- + --a;
What this means:
The variable c is assigned the result of...
b (incrementation will take effect after this line), plus
the unary operation - of c (decrementation will take effect after this line), plus
a (decrementation takes immediate effect).
Replace the variables with the values, and you get:
c = 7 + (-10) + 4
c = 1
...and the result of your print statement should be:
4 8 0
Let's slow down, and look hard at the equation. Think about this carefully.
int a = 5;
int b = 7;
int c = 10;
c = b+++-c--+--a;
b++ means increment b after assignment, so b stays equal to its original value in the equation, but will be incremented afterward the equation.
Then there's a +.
Then a negated c--. c gets decremented but will remain the same for the equation.
Then add that to --a, which means a gets decremented immediately.
So the variables values at the print statement will be:
c = 7 + -10 + 4 = 1
a = 4
b = 8
May I add that in my opinion this is a bad question for a test. All its really asking is if you understand i++ vs ++i.