Custom functions in Processing Language - java

doing some uni work on 'Processing' Programming language (a form of java).
So my question is 'Write a function called twoNumbers(int a,int b) which takes in two parameters a and b. If a is greater than b, then the two numbers are added together and the string 'the sum of a and b is sum' is displayed in the console window, where a and b and the sum are the values of a, b and their sum. Finally, the function should return the sum.'
..soo here is my attempt at the code, if I put (int a,int b) after the customer function, it just says that my other int a = number, is a duplicate, which is true, but im not sure how I am ment to give a and b a number without it thinking its a duplicate? Should I be putting it out of a void setup tag? as im unsure if this would then cause too many { brackets...
/* Question 1 */
int twoNumbers(){
int a = 30;
int b = 20;
if (a > b) {println(a+b);}
println("The sum of a and b is sum");
int sum;
sum = a+b;
println(sum);
}
Any help would be massively helpful in getting this and the other questions done :)
Thanks!!

Also your function is not returning a value, which will give you an error. It looks like you are confusing things. Either declare it a void or return a value of declared type (that last is what your assignment calls for). Either way a function, or a method, needs to be called to execute, and you are not calling it! So the code inside your the function is not being run!!
The following:
void imAMethod()
{
println("hello");
}
It is a valid method, but will do nothing, you need to call it, like:
imAMethod();// calling your method
void imAMethod()
{
println("hello");
}
But this won't work also, will give you the error "It looks like you're mixing "active" and "static" modes". Thats because to use a function in Processing you need to have at least a setup() method in the sketch, so:
void setup()
{
imAMethod();
}//end of setup
void imAMethod()
{
println("hello");
}
will work as expected.
But you need a function, so as Jesper pointed you will have to do something like:
int a = 30; // those are global variables to pass to your function
int b = 20;
void setup()// this is a builtin basic Processing method
{
//call your function
println("The sum of " + a + " and " + b + " is "+ twoNumbers(a, b));
}
int twoNumbers(int a, int b)
{
//do your math and tests here
return result;
}
There is another thing not clear in the assignment. A function must return something, so it is not clear what the function should return if a is not greater than b. You will have to handle this case, or compiler will complain. You may want to move this test out of the function to make things easier, like:
if (a < b)
println("The sum of " + a + " and " + b + " is "+ twoNumbers(a, b));//call your function
else
println(a + " is smaller than " + b);
and in the function just do the sum. But this may be not what the assignment requires... Anyway you will need to return something even if a is not greater than b. Note that the printing to console can be done inside the function also.
Hummm, re reading the assignment a think what is expected is: Aways return the sum, and just print if a is greater than b, which makes more sense and is easier, something like:
int twoNUmbers(int a, int b)
{
if (a < b){/*print the string*/}
return a + b;
}
Just a note for jlordo. In Processing.org you don't have a main, or better, it is transparent/hidden from user. Processing is like a "dialect" of java. So the code above would run as it is. There are two basic builtin functions: setup() and draw(). If the user do not use none of them the IDE will warps it in a setup() function, that will call the main() somewhere else. It will run once. Draw() instead loops forever.

'Write a function called twoNumbers(int a,int b) which takes in two parameters a and b.
That's not what your code looks like. Your method twoNumbers doesn't take two parameters a and b. Your code should start like this (exactly as mentioned in the assignment):
int twoNumbers(int a, int b) {
Remove the next two lines, int a = 30; and int b = 20;. Those lines declare two local variables named a and b. You should use the a and b that are passed in as parameters instead.
This also looks wrong:
if (a > b) {println(a+b);}
println("The sum of a and b is sum");
Carefully look at what the assignment says:
If a is greater than b, then the two numbers are added together and the string 'the sum of a and b is sum' is displayed in the console window, where a and b and the sum are the values of a, b and their sum.
That's not what your code is doing. Take it step by step, carefully think about what is meant in the assignment.

Related

Does the program stop excuting once it returns something?

public int max1020(int a, int b) {
// First make it so the bigger value is in a
if (b > a) {
int temp = a;
a = b;
b = temp;
}
// Knowing a is bigger, just check a first
if (a >= 10 && a <= 20) return a;
if (b >= 10 && b <= 20) return b;
return 0;
}
so if both a and b are within the range [10,20], would it just return a, and stop excuting the next two lines of code?
so if both a and b are within the range [10,20], would it just return a, and stop executing the next two lines of code?
It first checks a, if it matches the first condition then the function is returned with the value of a. The next two lines of code will not be executed as the function has returned.
Does the program stop executing once it returns something?
No, the value is not returned by the whole program it is just returned by the particular function. Let me give you an example.
public class Main {
public static void main(String[] args) {
int result;
// The method max1020 returns the value of 'a' here
result = max1020(11,14);
System.out.println(result);
// The method max1020 returns the value of 'b' here
result = max1020(31,11);
System.out.println(result);
// The method max1020 returns the value of '0' here
result = max1020(50,60);
System.out.println(result);
}
private static int max1020(int a, int b) {
// First make it so the bigger value is in a
if (b > a) {
int temp = a;
a = b;
b = temp;
}
// Knowing a is bigger, just check a first
if (a >= 10 && a <= 20) return a;
if (b >= 10 && b <= 20) return b;
return 0;
}
}
The return keyword just gets you out of the function you are in, it does not get you out of your whole program. When you call the max1020() for the first time it returns a. See it returns the value of a but the program will still execute the other lines. It will print the value of the variable result then it'll again call the max1020() on another pair of values.
If both a and b are within the range [10,20] it will always return a.
You are correct, once a return statement is reached, it will not execute any further code.
You are correct in the assumption that the program checks if a is withing the range, and given that the result of the evaluation is true it will return the value bond to variable a.
In Java the keyword return means that the program will return the value associated with it and stops further execution.
As for your question about the void method. In Java and many other languages you have something called "state" which means that there exists some values outside of the current scope of execution, e.g in pseudocode
int a = 0
public void inc (){
a++
}
Method inc does not take any arguments (it has an arity of 0) but increments the variable a that is defined outside the scope of the function it self. Any method that has other return type than void returns the defined type.
I hope that my answer was helpful.
You seem to be mixing method return and program exit (which can also be called "program return code").
In a method, whenever the line return is reached, the method stops right there and will not execute further instructions.
When that method is the main method, it also is the entry-point of the program. Therefore, when the main calls return, the program will effectively stop, returning code 0 (which means "success").
In Java, you can also stop a program execution by calling System.exit(ret). In that particular case, the JVM process (which is "your program") will stop executing further instructions, even if return is not explicitly called (though some IDE will give you errors or warnings). The return code (seen by the caller process) will be the one you specified with ret.

Scope of variable instantiated inside a method - Java

Is this code safe in Java?
public class HelloWorld {
public static void main (String args[]) {
HelloWorld h = new HelloWorld();
int y = h.getNumber(5);
int z = h.getNumber (6);
if (y == 10)
System.out.println("true");
}
public int getNumber(int x) {
int number = 5;
number = number + x;
return number;
}
}
My co-worker says that int number will be placed on the stack and when getNumber returns it will be popped off and could potentially be overwritten.
Is the same code potentially unsafe in C?
The HelloWorld class has no fields, and is therefore immutable. You can call your getNumber(x) function as many times as you'd like, from any thread, using the same object, and it will always give the same result for the same argument.
Maybe your co-worker is recalling horror stories in C where you can have something like static int number, which "belongs" to the method and which would get overwritten. Or maybe she's thinking about "return by reference"; even if it were, you'd be referencing a brand-new object every time because number is newly instantiated for every method call.
Your coworker is correct, sort of, but they apparently misunderstand what is going on.
public int getNumber(int x) {
int number = 5;
number = number + x;
return number;
}
Yes the value of 5 + 5 or 5 + 6 will be placed on the stack, but there is no danger of them being overwritten, they will properly be placed into y or z.
I suspect the confusion is from C (this type code works fine in C as well), but for pointers instead of primitives. Returning a result of malloc from a function in C can be "challenging" if you don't do it right.

fibonacci works in python but fails in Java

I have this code for calculating fibonacci number in python. It works and gives the expected result. but when I translated the same to Java, it fails. Any idea of what is going wrong here?
In python:
def fib3(n):
a,b=0,1
while n>0:
a,b=b,a+b
n-=1
return a
fib3(12) --> 144
In Java:
public static int fib2(int n){
int a = 0;
int b =1;
while(n-- >0){
a=b;
b=a+b;
}
return a;
}
fib2(12) --> 2048
In this section:
a=b;
b=a+b;
you're assigning b to a+b, but a is already b. So really you're doubling b
Easiest solution is a temp variable:
public static int fib2(int n){
int a = 0;
int b =1;
while(n-- >0){
int old_a;
old_a = a;
a=b;
b=old_a+b;
}
return a;
}
In python, a, b = b, a + b stores an intermediate tuple automatically before assigning the new values to the variables, while in Java you need to be explicit about it
Breaking down Python's instructions, a, b = b, a + b is executing this disassembly:
5 17 LOAD_FAST 1 (b)
20 LOAD_FAST 0 (a)
23 LOAD_FAST 1 (b)
26 BINARY_ADD
27 ROT_TWO
28 STORE_FAST 0 (a)
31 STORE_FAST 1 (b)
In a simpler sense, staying python, here's the process:
temp_tuple = (b, a + b)
a, b = temp_tuple
The issue is that you've got to one value from b to a at the same time as assigning to b the sum of a and b. Get that simultaneous swap wrong and you get the wrong answer.
In the spirit of the Python code, I present:
public static int fib(int n) {
int a = 0, b = 1;
while (n-->0)
b = a + (a = b);
return a;
}
This does the swap effectively at the same time as the add (strictly not, but it's good enough). Note that this is well-defined Java, as the language defines the evaluation order of operators precisely, unlike in C and C++ (where the equivalent of the above code is permitted to make demons fly out of your nose due to being Undefined Behavior).
OK, if it did make you experience problems with nasal demons, I'd suggest not using that compiler in future. But you wouldn't have any assurance of getting a correct fib() function…
a = b;
b = a+b;
This computes b = 2*b because a's value is overwritten by the time you compute the new value for b. Replace it with:
t = b;
b = a+b;
a = t
a=b;
b=a+b;
... is the problem. You need to save the old value of a before adding it to b.
The code is not equivalent, and relies on python's ability to assign multiple primitives in one line a,b=b,a+b; you need a temporary variable -
public static int fib2(int n){
int a = 0;
int b =1;
while(n-- >0){
int t = b; // <-- to hold the original value of b.
b = a + b;
a = t;
}
return a;
}
In java - When you write "a=b; b=a+b;" you are essentially saying that a should be equal to be and then that (since 'a' is now equal to 'b') that 'b' should just be twice what it originally was.
There are two ways you can fix this.
1) You can either continue the function you are originally using and then create a int 'temp' to store 'a' before you change 'a'.
2) You can also do what I would rather do ( this will use a lot more time however for a algorithm like fibonacci and would generally be a terrible idea for real world applications) is use a recursive function that will call itself.
It would generally look something like the following.
public static int fib2(int n){
if(n<=0){return 0;}
if(n<2){return 1;}
else{ return fib2(n-1)+fib2(n-2);}
}
That would probably not be the exact code but something very similar. Hope that was helpful!

Using recursion how can i keep the local variable updated [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
Using recursion how can i keep the local variable updated till a condition is met. I have an instance below that explains why question very well. The count variable is a local variable and very time the method goes through the count is set to 0. I cannot move the count outside the method it has to be local variable not static or anything else.. The desired output should be (3 6)
public static int returnInt(int b) {
int count = 0;
if (b == 6) {
System.out.println(count + " " + b);
}
b += 2;
count++;
return returnInt(b);
}
Pass count as an additional parameter to the method:
public static int returnInt(int b, int count) {
... do some stuff to b, print something, check whether end-condition has been met ...
return returnInt(b, count + 1);
}
Then, call returnInt with an extra argument of 0 to start things off.
You cannot. Local variable is local by definition. It exists only in scope of current execution of the method.
BUT you have the following solutions.
The best one is to pass it as a parameter of your method (exactly as you do with other parameter b.
public static int returnInt(int b) {
return returnInt(b, 0)
}
private static int returnInt(int b, int count) {
// your code here.
}
If (for some strange reason) you cannot change the method signature you can put this variable into ThreadLocal. In this case even if several threads execute your method simultaneously your code stays thread safe.
Moving this variable to class level is the worst solution cause it is not thread safe and breaks encapsulation.
This function will overflow your stack. You must provide a way out when using recursion. And as for the variable count, you are redefining it back to 0 every time; it cannot be initialized inside the recursive function. Try passing it to your function as a parameter, and also providing a way out for your function.
public static int returnInt(int b,int count) {
if (b == 6) {
System.out.println(count + " " + b);
return b;
}
b+=2;
count++;
return returnInt(b);
}
the 'return b' line can be your way out...and you don'y necessarily have to return b... return whatever you need.
public static int returnInt(int b) {
return returnInt(b, 0);
}
private static int returnInt(int b, int count) {
if (b == 6) {
System.out.println(count + " " + b);
// My guess is you should be returning something here???
// Actually, this shouldn't be your exit point from the recursion because depending on the starting value of b, since you are always adding 2, it might never equal 6, so again you would get a StackoverflowException.
}
b += 2;
count++;
return returnInt(b, count);
}
In general, create returnIntInner(int b, boxed count), move the bulk of the logic to that, and call that from a "thin" version of returnInt. To box count the "old style" way is to pass the count as an int[1] array, so that it can be returned -- I've not studied up on the new Java reference parm syntax. But since your code is tail-recursive and doesn't need to access count after the recursive call, you can simply pass count as a regular parameter.

Recursion output ambiguity

Ok so i am just learning recursion and i am confused on one point.
This is the code
public class RecursiveDemo {
public static void showRecursion (int num) {
System.out.println("Entering method. num = " + num);
if (num > 1) {
showRecursion(num - 1);
}
System.out.println("Leaving method. num = " + num);
}
public static void main(String[] args){
showRecursion(2);
}
}
The output i am getting is :
Entering method. num = 2
Entering method. num = 1
Leaving method. num = 1
Leaving method. num = 2
My question is why am i getting the output "Leaving method. num = 2". Shouldn't it stop at "Leaving method. num = 1" since num has already reached 1?
Once the original invocation of this method leaves the if statement, it passes to System.out.println("Leaving method. num = " + num);. Since you invoked the message originally with value 2, 2 is the value of num for this part of the code.
Your code runs like this (pseudocode):
Start First Call
if statement
Start Second call
Skips if statement
Print from Second Call
End of Second Call
End of if Statement
Print From First Call
End of First Call
It looks like you have a fundamental misunderstanding of recursion.
When you call your method with (num-1) as arguments, the parent call (the first call, in this case), retains the value num as its argument, which is 2, in this case.
So let's comment out the line below
//showRecursion(num - 1);
What would you get? It must be
Entering method. num = 2
Leaving method. num = 2
And if you uncomment the line above. You should get the one you had.
No.
main will call showRecursion(2), which in turn will call showRecursion(1) (so you get two "Entering" messages). At which point, the condition will fail, so no more recursion occurs. So now the program simply begins returning from each function call in turn, printing both of the "Leaving" messages.
It's because the initial call to showRecursion(2) hasn't finished yet.
Consider the following:
public static void showFirstRecursion (int num) {
System.out.println("Entering method. num = " + num);
if (num > 1) {
showSecondRecursion(num - 1);
}
System.out.println("Leaving method. num = " + num);
}
public static void showSecondRecursion (int num) {
System.out.println("Entering method. num = " + num);
if (num > 1) {
showThirdRecursion(num - 1);
}
System.out.println("Leaving method. num = " + num);
}
// I won't bother showing an implementation for showThirdRecursion, because it won't be called.
public static void main(String[] args){
showFirstRecursion(2);
}
No problem here, right? You'd expect to see the first method entered, second entered, (third not entered because num == 0), second left, first left.
There is really nothing special about recursion. It's just making a function call that happens to be calling the function that the call is a part of. A recursive call behaves, conceptually, in all respects like any other function call. The trick is the design of a recursive algorithm, i.e., coming up with a reason why you'd want to call the same function you're already in.
The other answers already cover the specific question, but here is some information on using a debugger. This tutorial is for Eclipse, but pretty much tells you what you need to know for any visual debugger.
The basics are pretty straightforward, and it would be well worth your time to at least learn how to step through the code. A debugger is an invaluable tool for quickly verifying the logic of your program, and is far easier than scattering print statements everywhere.
Try "showRecursion(5);".
[Answer: This is recursion. There's more than one copy of the variable "num" in memory. "num" is a parameter; it's not a field, and it's not static.]
So what I understood was
with every method call, Stack is getting populated ie. 2,1
but when i>1 doesn't matches it returns/breaks the call and control is given to the system.out.println line, that prints the value starting from the top of stack ie 1,2

Categories

Resources