Kindly assist. I am preparing for the Java 7 Programmer 1 exam and came across this question in one of the enthuware Tests.
Question :
Consider the following method:
static int mx(int s)
{
for(int i=0;i<3;i++)
{
s=s+i;
}
return s;
}
And the following code snippet:
` int s=5;
s += s + mx(s) + ++s;
System.out.println(s);`
What will it print ?
End Question
According to the rules on operator precedence , I started by evaluating ++s getting a value of 6 for s, followed by using 6 in the mx method to get a value of 8. Next I added 6+8+6 =20. Then finally carried out the assignment operation as s = 6+ 20 = 26.
The correct answer is 24. I cannot seem to figure out how they come to that answer. Kindly shed some light.
You shouldn't start with ++s, since the evaluation is from left to right.
s += s + mx(s) + ++s;
is the same as
s = 5 + 5 + mx (5) + 6;
which is
s = 5 + 5 + 8 + 6 = 24
The value of s does not change on the ++s because the evaluation of the expression is left to right.
You can check this by modifying your code like this:
public static int mx(int s){
System.out.println(s);
for(int i=0;i<3;i++){
s=s+i;
}
return s;
}
public static void main(String[] args){
int s=5;
s += s+mx(s)+ ++s;
System.out.println(s);
}
The print statement in mx(int s) will print out the value for s, revealing that it is still 5.
Additionaly, if mx(int s) had been passed the value 6 it would return 9 instead of 8.
Related
I think I've gotten mostly to a solution for a homework problem.
This is for a 201 CS class. Right now I just want to get the logic right. At present, it doesn't operate as intended, but it's close.
We don't want to use .toBinary, bitwise, or anything else. We also haven't been taught stringBuilder, so I'd like to avoid using it.
There's a System.out.println(); within the method which provides the correct answer if you read the console from bottom to top.
public static void main(String[] args) {
System.out.println(addBin(1100111011,1101110011));
}
public static String addBin(int num1,int num2){
String result = "";
if(num1 > 0 || num2 > 0){
int part1 = num1%10, part2 = num2%10;
int rem1 = num1/10, rem2 = num2/10;
result += Integer.toString((part1 + part2)%2);
//System.out.println(result);
int carry = (part1 + part2) /2;
addBin(rem1 + carry, rem2);
return result;
}
return result;
}
So, this example adds 1100111011 and 1101110011 with the output
0
1
1
1
0
1
0
1
0
1
1
0
when the correct answer is 11010101110.
I'm having trouble understanding how to properly "pop" the "result" part properly. Could you please help me understand this process, possibly within the context of this problem?
Thanks!
As you can see from your output, you are getting the correct result in the reverse order but you are not appending any of your older result to the ones that are being currently computed.
Inside your if condition, you are calling the addBin() function but you are not using the result that it gives anywhere. Just change that line to the following:
result = addBin(rem1 + carry, rem2)+result;
That should effective append all your results in front of the current answer so that you do not get the result in backwards direction. Hope this helps.
This question already has answers here:
How do the post increment (i++) and pre increment (++i) operators work in Java?
(14 answers)
Closed 7 years ago.
This causes a Stack Overflow error. I just need help explaining why this one crashes compared to the correct one which is similar. I have used the debugger, but it is still unclear to me.
public static void main(String[] args) {
countForwards(5);
}
public static void countForwards( int num ) {
if (num >= 0){
countForwards(num--);
}
System.out.print(num + " ");
}
I know this is the solution but I don't understand why it is different
public static void countForwards( int num ) {
if (num >= 0){
countForwards(num - 1);
}
System.out.print(num + " ");
}
countForwards(num--) passes the original value of num to the recursive call, which means the recursion never ends.
countForwards(--num) would allow the recursion to end.
After seeing all the traffic this question got, I thought it would be worth it to expand the answer a little.
As paxdiablo commented, even though countForwards(--num) allows the recursion to terminate, it behaves differently than countForwards(num-1).
Both variants would cause the following series of recursive calls :
countForwards(5)
countForwards(4)
countForwards(3)
countForwards(2)
countForwards(1)
countForwards(0)
countForwards(-1)
but they will output a different series of numbers when the recursion unwinds :
num - 1
-- num
-1
-1
0
-1
1
0
2
1
3
2
4
3
5
4
The reason for the difference is that num-1 doesn't change the value of num while --num decrements num.
num-- uses a postfix operator -- which means that original value i.e. num is passed and its value is decremented after it is passed.
The interesting thing about a postfix operator i.e. the one we are using in this example is that operation is performed and then the value is incremented or decremented. Please refer to official documentation about operators in java
class PrePostDemo {
public static void main(String[] args){
int i = 3;
i++;
// prints 4
System.out.println(i);
++i;
// prints 5
System.out.println(i);
// prints 6
System.out.println(++i);
// prints 6
System.out.println(i++);
// prints 7
System.out.println(i);
}
}
Post-Decrement
Post-Decrement takes the form variable-name operator. This tells the compiler to first use the original value and afterawrds decrement it, so if we have something like this:
for (int i = 10; i > 0; i--)
{
System.out.println(i);
}
The output will be as follows
1: 10
2: 9
3: 8
4: 7
5: 6
6: 5
7: 4
8: 3
9: 2
10: 1
Pre-Decrement
Pre-Decrement takes the form operator variable-name and is used when you want to decrement before you use the value. The same code above would terminate at 0 instead of 1. This is because the function decremented the value before it used the value.
How does this apply to recursive calls?
Each recursive call is it's own stack, so when you pass num-- to the recursive function, you're literally passing the original value of num, and when the child call terminates (in this case never) the parent call will then decrement num. Since you don't have another base case which correctly terminates the call, it results in infinite recursion.
Actually it is happening due to post decrement operator in the method.
public static void countForwards( int num ) {
if (num >= 0){
countForwards(num--);
}
System.out.print(num + " ");
}
Now when the function is calling the countForwards again it is always taking value of num as 5 due to post decrement in the method, please try to change as pre-decrement
public static void countForwards( int num ) {
if (num >= 0){
countForwards(--num);
}
System.out.print(num + " ");
}
This will be work because value is first decremented and then that value is using method.
as function is calling again and these are primitive and stores in the stack. Thats why it is showing stack overflow.
public static void countForwards( int num ) {
if (num >= 0){
countForwards(num - 1);
}
System.out.print(num + " ");
}
This is working because this is an expression which try to solve first itself and then the function can use the value of that expression. I hope it will answer your question.
I am trying to understand the working of return statement in JAVA.
My doubt is if inside a method with a Non void return type, I have a decision block which also has a return statement of its own, Still I have to return some value .
For understanding here is a sample code I have written :-
public int bunnyEars(int bunnies) {
//int count=0;
if (bunnies >=1) {
count = count + 2;
bunnyEars(bunnies -1);
return count1;
}
return count2 ;
}
In the mentioned code I just want to return the no. of bunnies which I am being able to do from inside the bunnyEars method count1. But still JAVA wont allow to have a non-void method without a return type which is totally understood and I have to add count2 return also. Now I am suspecting that I am having a conceptual understanding failure here. Kindly let me know if I am missing something? Kindly let me know If I am missing some more info here.
[Edited] Full code:
public class Test5 {
//public int ears=1;
public int count=0;
public int bunnyEars(int bunnies) {
//int count=0;
if (bunnies >=1) {
count = count + 2;
bunnyEars(bunnies -1);
return count;
}
return count ;
}
public static void main(String args[]){
Test5 test5= new Test5();
System.out.println(test5.bunnyEars(90));
}
}
Yes you need to return count2 which should be zero. Which means if there are no bunnies then there are no ears. So which returning you should be returning some value irrespective of the conditional block.
So in this case
return count1;
represents the number of ears if the bunnies are represent, while
return count2;
represents the number of ears when there are no bunnies, which should be 0.
I hope that gives you some clarification
I think your conceptual misunderstanding lies with understanding the flow of the program.
Supposed you were to use this method by calling:
bunnyEars(2)
Then, once you enter the method, the first thing the program does is check if 3 >= 1. Since this is true, you proceed into the code inside the {..} (called a 'block'). Inside this block, you increment count by 2. I am assuming count is defined elsewhere in the class, but suppose the current value for count is 10. Then, the new value of count will be 12.
After this, the program executes the line:
bunnyEars(bunnies - 1)
Which translates to:
bunnyEars(1)
Now, basically, you are calling the same method again, but passing in 1 instead of 2.
Once again, the program checks to see that 1 >= 1, which is true. So it goes into the
if-block which, again, increments count by 2. So now, count = 14. Then it calls the
same method again but this time passing in 0.
bunnyEars(0)
Since 0 >= 1 evaluates to false, you the program skips the if-block and continues
execution after the block. So know, you are in the method bunnyEars(), but you have
completely skipped over your "return" statement. But, alas, bunnyEars MUST return an int.
So this is why you must have a return after the block. In your case, bunnyEars(0) returns count2 and the program-execution returns to where you called bunnyEars(0).
Read up on recursive calls. The basic idea of a recursive method is that, inside the recursive method, you must have some case that terminates the recursion (otherwise you will loop forever).
For example, the following code will go on forever:
public int sum(int in)
{
return in + sum(in - 1);
}
This will keep going on forever, because sum(1) will call sum(0) which calls sum(-1).
So, I must have a condition that terminates the recursion:
public int sum(int in)
{
if(in == 0) return 0;
return in + sum(in - 1);
}
Now, I have a terminating-case. So if I call sum(1), it will call sum(0) which returns 0. So my result is 1 + 0 = 1.
Similarily,
sum(2) = 2 + sum(1) = 2 + 1 + sum(0) = 2 + 1 + 0
sum(3) = 3 + sum(2) = 3 + 2 + sum(1) = 3 + 2 + 1 + sum(0) = 3 + 2 + 1 + 0 = 6
Hope this helps!
So as I understand it, your question is why you still need to return count2 if you return count1. The answer is basically 'what happens if you don't enter the if block?'. In that case, without return count2, you wouldn't have a return value, which is what Java is complaining about. If you really don't want two return statements, you could probably do something like:
public int bunnyEars(int bunnies) {
int count=0;
if (bunnies >=1) {
count = count + 2;
bunnyEars(bunnies -1);
}
return count ;
}
On a side note, this and the code you posted in your question won't work for regression purposes, but the one in your comment does, and there it looks like you have a static variable for count, in which case you could set the return type to void and just print count.
This question already has answers here:
Java recursive Fibonacci sequence
(37 answers)
Closed 8 years ago.
I am learning Java and I have this code from the internet and running it in Eclipse:
public class Fibonacci {
public static void main (String [] args) {
for (int counter = 0; counter <= 3; counter++){
System.out.printf("Fibonacci of %d is: %d\n", counter, fibonacci(counter));
}
public static long fibonacci(long number) {
if ((number == 0) || (number == 1))
return number;
else
return fibonacci(number - 1) + fibonacci(number - 2);
}
}
I've tried to understand it but cannot get it. So I run through the code and counter gets passed in through the fibonacci method. As counter starts at 0 and this is what gets passed first, then 1 and I understand the method passes back 0 and then 1.
When it reaches 2: it will return 2-1 + 2-2 = 2 and it does return this.
When it reaches 3: it will return 3-1 + 3-2 = 3 but it does not return 3 it returns 2.
Please can someone explain to me why as I cannot figure this out?
Thanks
First, I have to tell you that this recursive version has a dramatic exponential cost. Once you understand how it works, my advice for you would be to learn about tail recursivity, write a tail-recursive solution, an iterative solution, and compare them to your current method for high values of "number".
Then, your function basically uses the mathematical definition of the Fibonacci sequence :
f0 = 1, f1 = 1, fn = fn-1 + fn-2 for all n >= 2
For example if we call fibonacci(3), this will return fibonacci(2) + fibonacci(1). fibonacci(2) will be executed first and will return fibonacci(1) + fibonnacci(0). Then fibonacci(1) will return immediately 1 since it is a terminal case. It happens the same thing with fibonnacci(0), so now we have computed fibonnacci(2) = 1 + 0 = 1. Let's go back to fibonacci(3) which has been partially evaluated at this point : 1 + fibonnacci(1). We just have to compute fibonnacci(1) and we can finally return 1 + 1 = 2.
Even in this little example, you can see that we evaluated twice fibonacci(1), that is why this version is so slow, it computes many times the same values of the sequence, and it gets worth when "number" is high.
I'm trying to understand some String class functions in Java. So, here's is a simple code:
/* different experiments with String class */
public class TestStrings {
public static void main(String[] args) {
String greeting = "Hello\uD835\uDD6b";
System.out.println("Number of code units in greeting is " + greeting.length());
System.out.println("Number of code points " + greeting.codePointCount(0,greeting.length()));
int index = greeting.offsetByCodePoints(0,6);
System.out.println("index = " + index);
int cp = greeting.codePointAt(index);
System.out.println("Code point at index is " + (char) cp);
}
}
\uD835\uDD6b is an ℤ symbol, so it's ok surrogate pair.
So, the string has 6(six) code points and 7(seven) code units (2-byte chars). As it's in documentation:
offsetByCodePoints
public int offsetByCodePoints(int index,
int codePointOffset)
Returns the index within this String that is offset from the given index by codePointOffset code points.
Unpaired surrogates within the text range given by index and codePointOffset count as one code point each.
Parameters:
index - the index to be offset
codePointOffset - the offset in code points
So we do give an argument in code points. But, with given arguments (0,6) it still works fine, without exceptions. But fails for codePointAt(), because it returns 7 which is out of bounds. So, maybe the function gets its args in code units? Or I've missed something.
codePointAt takes a char index.
The index refers to char values (Unicode code units) and ranges from 0 to length() - 1.
There are six code-points in that string. The offsetByCodePoints call returns the index after 6 code-points which is char-index 7. You then try to get the codePointAt(7) which is at the end of the string.
To see why, consider what
"".offsetByCodePoints(0, 0) == 0
because to count past all 0 code-points, you have to count past all 0 chars.
Extrapolating that to your string, to count past all 6 code-points, you have to count past all 7 chars.
Maybe seeing codePointAt in use will make this clear. This is the idiomatic way to iterate over all code-points in a string (or CharSequence):
for (var charIndex = 0, nChars = s.length(), codepoint;
charIndex < nChars;
charIndex += Character.charCount(codepoint)) {
codepoint = s.codePointAt(charIndex);
// Do something with codepoint.
}
Helpful answer, Mike... For easily understanding String#offsetByCodePoints, I commented its usage and modified a bit of the question example:
I personally find the Java documentation ambiguous here.
public class TestStrings
{
public static void main(String[] args)
{
String greeting = "Hello\uD835\uDD6b";
// Gets the `char` index a.k.a. offset of the code point
// at the code point index `0` starting from the `char` index `6`¹.
// ---
// Since `6` refers to an "unpaired" low surrogate (\uDD6b), the
// returned value is 6 + 1 = 7.
//
int charIndex = greeting.offsetByCodePoints(0,6);
System.out.println("charIndex = " + charIndex);
int cp = greeting.codePointAt(charIndex);
System.out.println("Code point at index is " + (char) cp);
}
}