in this code im confused as to why it prints out "0 1 2 3" instead of "3 2 1 0"
int y = 3;
String s = " ";
while (y>-1)
{
s = y + " " + s;
y--;
}
System.out.print(s);
Thanks.
s = y + " " + s;
adds y at the front of the string so:
s = 3
s = 2 3
s = 1 2 3
s = 0 1 2 3
step 1:
s = 3
step 2:
s = 2 3;
step 3:
s = 1 2 3
like wise in every loop y's value is added to the starting point of the string s
This is because you prepend the newest value to the string. If you want the output to be "3 2 1 0" you should change your line from
s = y + " " + s;
to
s = s + " " + y;
Related
I'm going through the Java Tutorial on HackerRank using Java 8. The goal is to print out a multiplication table of 2 from 1 - 10.
Here is what I came up with
public static void main(String[] args) {
int x = 2;
int y = 0;
int z;
while (y < 10) {
z = x * y;
y++;
System.out.println(x + " x " + y + " = " + z);
}
Here is the output I get from the code above
2 x 1 = 0
2 x 2 = 2
2 x 3 = 4
2 x 4 = 6
2 x 5 = 8
2 x 6 = 10
2 x 7 = 12
2 x 8 = 14
2 x 9 = 16
2 x 10 = 18
I've also tried while <= 10 instead of while < 10 as shown in my code above and for that my result was:
2 x 1 = 0
2 x 2 = 2
2 x 3 = 4
2 x 4 = 6
2 x 5 = 8
2 x 6 = 10
2 x 7 = 12
2 x 8 = 14
2 x 9 = 16
2 x 10 = 18
2 x 11 = 20
Neither of this outputs is what I'm looking for. Logically I am confident my code makes sense and should work so I'm looking for someone to give me tips as to something I may have missed or maybe I've made a mistake and I'm not aware of it. I am not looking for the code to the right answer, but rather advice and/or pointers which will allow to come up with a working solution on my own.
Start your y value at 1
Don't increment your y value until after the print statement
public static void main(String[] args) {
int x = 2;
int y = 1; //starts at 1
int z;
while (y < 10) {
z = x * y;
System.out.println(x + " x " + y + " = " + z);
y++; // increment y after the print statement
}
}
Assign value of y = 1 and increment it after your system.out.println();
The question is "Write a program that duplicates the sample run shown at the bottom , which displays the sum of the first n integers for each value of n from 1 to 10. As the output suggests, these numbers can be arranged to form a triangle and are therefore called triangle numbers
1 = 1
1 + 2 = 3
1 + 2 + 3 = 6
1 + 2 + 3 + 4 = 10
1 + 2 + 3 + 4 + 5 = 15
1 + 2 + 3 + 4 + 5 + 6 = 21
1 + 2 + 3 + 4 + 5 + 6 + 7 = 28
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 = 36
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 = 45
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 = 55"
I am able to output 1 2 3 4 5... to 10, but I just can't figure out how to get it to look like the triangle above and make it add the next consecutive number. I'm assuming that I am missing something very obvious.
import java.util.Scanner;
public class prob3
{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
for (int n = 1; n <= 10; n++) {
for (int i = n; i <= n; i++){
System.out.println(n);
}
}
}
}
Your problem is that you print whole lines just with those numbers.
You print:
1
2
3
But you need something like
1=1
1+2=3
Instead, you need to accumulate the content to be printed, like:
StringBuilder builder = new StringBuilder();
for (int i = n; i <= n; i++) {
builder.append(n);
builder.append("+");...
System.out.println(builder.toString() + "=" + sum);
}
The above is just meant to to get you going; as there are still some things missing that you will have to work with:
A) figuring how to use the StringBuilder to "remember" that part of the previous line that you can reuse!
B) computation of overall sum is missing (as it is in your code, too!)
Split the handling of each row into a helper method.
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
printRow(i);
}
}
/**
* Print one row.
* 1 + 2 + 3 + ... + n = sum
* #param n the max for this row
*/
private static void printRow(int n) {
int sum = 0;
StringBuilder sb = new StringBuilder();
// 1 through n-1
for (int i = 1; i < n; i++) {
// TODO - update the sum
// TODO - update sb with the number and plus
}
// final number n
// TODO - update the sum
// TODO - update the sb with the final number, equals, and sum
// display
System.out.println(sb.toString());
}
I am having some problems with Recursion in Java.
Here is my code
public class recursionTrial {
public static void main(String[] args)
{
System.out.println(doSomething(6));
}
public static int doSomething(int n)
{
if (n==0 || n==1)
return 0;
else
return n + doSomething(n-1) + doSomething(n-2);
}
}
Which gives me an output of 38. However I am unable to trace the recursive function in my head or on paper. How will the working out look? 6+5.... and so on.
I get if it were just
return n + doSomething(n-1)
then it would be 6+5+4+3+2 = 20 ; it is the second part of the code that is confusing me. If someone could explain to me how to trace the recursive function properly and write the working out I would appreciate it! Also is there a way to write a piece of code that prints the value of n before it changes each time?
In the absence of side effects one can think of this recursive function as of a regular function. You can draw a small table showing the results of invocation of your function, starting with zero:
n res computation
- --- -----------
0 0 0
1 0 0
2 2 2+0+0
3 5 3+2+0
4 11 4+5+2
5 21 5+11+5
6 38 6+21+11
No special mental treatment is required for the second recursive invocation: it is the same as the first one.
Note: your function will be taking progressively longer time as the value of n goes up, because it would be re-doing a lot of computations it has already done. Fortunately, this can be addressed with a simple and very common trick, called memoization.
Your recursive function is
f(n) = n + f(n-2) + f(n-1)
The execution flow is as follows.
f(n-2) is evaluated first... To compute f(n-2) the program again makes a recursive call to f(n-4) and f(n-3) and so on...
Next, f(n-1) is evaluated... this again depends on computed values of f(n-3) and f(n-2) and so on...
These two values are added with n to get the final result...
For example, the recursion tree for n=4 is as follows (I'm not showing the addition with n for simplicity):
f(4) {
f(2) {
f(0) {0}
f(1) {0}
}
f(3) {
f(1) {0}
f(2) {
f(0) {0}
f(1) {0}
}
}
}
doSomething(1)= return 0,
doSomething(2)== 2+dosomething(1)= 2+0=2,
doSomething(3)=3+doSomething(2)=3+2=5,
doSomething(4)=4+doSomething(3)+doSomething(2)=4+5+2=11
doSomething(5)=5+doSomething(4)+doSomething(3)=5+11+5=21,
doSomething(6)=6+doSomething(5)+doSomething(4)=6+21+11=38
Start at doSomething(6), it calls: doSomething(5) go to that line, to figure out doSomething(5) we need to know doSomething(4) and doSomething(3).... and work your way up the tree, till you get to an actual "Return value" which in this case would be when we reach doSomething(1), then put those values in as you back down the tree.
public static int doSomething(int n) {
if (n==0 || n==1)
return 0;
else
return n + doSomething(n-1) + doSomething(n-2);
}
You could try to expand recursively, this is conceptually what the program does.
doSomething(6) expands to 6 + doSomething(5) + doSomething(4)
doSomething(5) expands to 5 + doSomething(4) + doSomething(3)
doSomething(4) expands to 4 + doSomething(3) + doSomething(2)
...
Simply go down the recursion. For example (I use dS for doSomething):
dS(6) = 6 + dS(5) + dS(4) =
6 + 5 + dS(4) + dS(3) + 4 + dS(3) + dS(2) =
6 + 5 + 4 + dS(3) + dS(2) + 3 + dS(2) + dS(1) + 4 + 3 + dS(2) + dS(1) + 2 + dS(1) + dS(0) =
6 + 5 + 4 + 3 + dS(2) + dS(1) + 2 + dS(1) + dS(0) + 3 + 2 + dS(1) + dS(0) + 0 + 4 + 3 + 2 + dS(1) + dS(0) + 0 + 2 + 0 + 0 =
6 + 5 + 4 + 3 + 2 + dS(1) + dS(0) + 0 + 2 + 0 + 0 + 3 + 2 + dS(1) + 0 + 0 + 4 + 3 + 2 + 0 + 0 + 0 + 2 + 0 + 0 =
6 + 5 + 4 + 3 + 2 + 0 + 0 + 0 + 2 + 0 + 0 + 3 + 2 + 0 + 0 + 0 + 4 + 3 + 2 + 0 + 0 + 0 + 2 + 0 + 0 =
38 <-- Final result
Beware that this has exponential complexity.
doSomething(6) calls doSomething(5) and doSomething(4)
doSomething(5) calls doSomething(4) and doSomething(3)
doSomething(4) calls doSomething(3) and doSomething(2)
doSomething(3) calls doSomething(2) and doSomething(1)
doSomething(2) calls doSomething(1) and doSomething(0)
doSomething(1) is 0
doSomething(0) is 0
This illustrates callings of doSomething(), they are not results, since you are adding n for each call.
6
_______|_______
/ \
5 4
____|____ _|_
/ \ / \
4 3 3 2
_|_ | | |
/ \ / \ / \ / \
3 2 2 1 2 1 1 0
/ \ / \ / \ / \
2 1 1 0 1 0 1 0
/ \
1 0
System.out.println("1 + 2 = " + 1 + 2);
output: 12
can you explain why this is ? I tried to look through some documentation but did not find anything...
Because the + operator works from left to right, it adds the string "1 + 2 = " to 1 first, and gets "1 + 2 = 1", then adds 2 to get "1 + 2 = 12".
It's equivalent to
System.out.println(("1 + 2 = " + 1) + 2);
Try this instead.
System.out.println("1 + 2 = " + (1 + 2));
Since the left-hand operand is a String, then the left-hand operand gets cast to a String.
"1 + 2 = " + 1 is evaluated first. The result is the String "1 + 2 = 1". Then the next operation is "1 + 2 = 1" + 2. The result of that operation is "1 + 2 = 12"
The operator + always groups from left to right. So you get "1 + 2 = " + 1, (which gives "1 + 2 = 1"), and then the 2 gets added on last, giving "1 + 2 = 12".
If you want it to group from right to left, you need to use parentheses, like "1 + 2 = " + (1 + 2) and this will give "1 + 2 = 3"
This is because of priority. It goes from left to right, if you are using only +. First, the string 1 + 2 = is created, then you add number to the string, resulting in string 1 + 2 = 1 and then you add next int to string resulting in string 1 + 2 = 12.
You can avoid that by using brackets "1 + 2 = " + (1 + 2)
According to the Java Specification §15.7:
The Java programming language guarantees that the operands of operators appear to be evaluated in a specific evaluation order, namely, from left to right.
And §15.18:
The additive operators have the same precedence and are syntactically left-associative (they group left-to-right).
If the type of either operand of a + operator is String, then the operation is string concatenation.
So the first half, "1 + 2 = " + 1, is the first part to get evaluated. Because the first half of that is a String, it evaluates to: "1 + 2 = 1". The whole expression is now "1 + 2 = 1" + 2. Once again, one of the two operands in this expression is a String, so the + operand concatenates. The whole expression then evaluates to the String "1 + 2 = 12", which is then printed.
I am trying to practice understanding recursion but the following program has me stumped. How is the answer being returned as 14? Can someone show me how this is calculating? I tried to put in afew print statments to help me identify what is going on but I do not see how spot is decremented after it goes up to 4. I have the program and output to console below, please help.
from console:
The spot 1 is 0
The spot 1 is 1
The spot 1 is 2
The spot 1 is 3
The spot 1 is 4
when spot = length. the spot is 4
The value is 4
spot after return 3
the spot 2 is 3
The value is 8
spot after return 2
the spot 2 is 2
The value is 11
spot after return 1
the spot 2 is 1
The value is 13
spot after return 0
the spot 2 is 0
The answer is 14
Code:
public class Recurs1 {
public static void main (String [] arg) {
Recurs1 r = new Recurs1();
r.compute();
}
public void compute() {
int [] stuff = {1, 2, 3, 4};
int answer = go(stuff, 0);
System.out.println("The answer is " + answer);
}
private int go(int[] numbers, int spot) {
System.out.println("The spot 1 is " + spot);
//System.out.println("0 is " + numbers[0] + " 1 is " + numbers[1] + " 2 is " + numbers[2] + " 1 is " + numbers[3]);
if (numbers.length == spot) {
System.out.println("when spot = length. the spot is " + spot); return spot;
}
int value = go(numbers, spot + 1 );
System.out.println(" The value is " + value);
System.out.println("spot after return " + spot);
System.out.println(" the spot 2 is " + spot);
return value + numbers[spot];
}
}
Try returning 0 instead of spot when you've reached the end. You're tacking 4 (the current value of spot) onto the end.
If your goal is to write a method which is summing the array, then the problem is that on the line of go() where you have if(numbers.length == spot) you are returning spot, which is 4, and it is adding that to the total value (because the method that called go(numbers, 4) is setting value to that and adding it.) Instead, you should be returning 0 to stop recursion (because the result will be 1+2+3+4+0)
Try this on for size:
private int go(int[] numbers, int spot){
if(numbers.length == spot) return 0;
return go(numbers, spot+1) + numbers[spot];
}
Maybe I can help walk you through it. Your program works it's way up until it calls go(numbers, 3+1), which returns 4, because numbers has 4 elements and spot is of value 4 (3+1).
At this point you are looking at a call stack of something like this:
answer = go(stuff, 0);
value = go(numbers, 0 + 1);
value = go(numbers, 1 + 1);
value = go(numbers, 2 + 1);
value = go(numbers, 3 + 1) = 4
Now it will work it's way back up the stack.
go(numbers, 2 + 1 );
Calling this will give you value+numbers[3], which is 4 + 4, with value coming from go(numbers, 3 + 1).
Next we have
go(numbers, 1 + 1 );
This will return go(numbers, 2 + 1 ) + numbers[2], which is 8 + 3 (or 11).
And then go(numbers, 0 + 1 ) is called, which returns go(numbers, 1 + 1 ) + numbers[1], which is 11 + 2 or 13.
Lastly, go(stuff, 0) can be calculated. This returns go(numbers, 0 + 1 ) + numbers[0], which is 13+1, or 14 - the answer you are currently getting.
I'm not sure if I actually explained much, but hopefully walking through it can show where your confusion is.
Another way of visualizing it would be something like this:
answer = go(stuff, 0);
go(stuff, 0) = go(numbers, 0 + 1) + 1;
go(numbers, 0 + 1) = go(numbers, 1 + 1) + 2;
go(numbers, 1 + 1) = go(numbers, 2 + 1) + 3;
go(numbers, 2 + 1) = go(numbers, 3 + 1) + 4;
go(numbers, 3 + 1) = 4;