I'm trying to put this formula into a loop
The function to put inside the loop
I've used if statements to give me a specific result if the input is zero, but if the input is one or higher, the for loop should run.
I was given a question regards recursion and supposed to execute it 3 different ways one of them using a loop that I've already made and runs but gives unexpected results.
public class Assignment5Recursion {
public static int puzzleLoop(int n) {
int v=0;
if(n>=1) {
for(int i=1; i<=n+1; i++) {
v = (2*i-1);
}
return ((2*n+1)+2*v);
}
else {
return 1;
}}}
if n is 1, the result should be 5, if n is 2, the result should be 13, if n is 3, the result should be 25, if n is 7, the result should be 113, but for some reason, I'm getting different outputs, so I'm assuming that I've set the loop wrong.
You need to make 2 changes.
1)The loop will run from i=1
to i=n+1
whereas you only require it to run till i=n
.
So the for loop exit condition should either be i<n+1
or i<=n
2)The variable v is going to be replaced every run of the loop as it is getting assigned a new value every time.
So the value for v will always be v=2*(n+1)-1
according to your code.
You need to make this v += (2*i-1)
so that the new value of v gets added to the old value to get sigma(sum).
Replacing your for loop as below will solve your problem.
for(int i=1; i<n+1; i++) {
v += (2*i-1);
}
or
for(int i=1; i<=n; i++) {
v = v+(2*i-1);
}