0

I'm trying to increment the following sequence in a for loop (Java):

1, 4, 9, 16, 25 etc the difference increasing by two each time. I tried using 'i+=3 + i' but I know that's wrong since it doesn't take into account that the variable i changes along the sequence.

Any help? Thanks

1
  • i += 3 + i would give i = 3 + i + i kind of 1, 5, 13 .. Commented Nov 22, 2015 at 10:51

4 Answers 4

2

You could have an increment of i+=k and change k inside the loop in order to change the increment.

int k=1;
for (int i=1;i<1000;i+=k) {
   k+=2;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks it seems to work! I was thinking about creating another variable but wasn't sure how to go about it. It's clear now.
0

If your i is changing, the simple logic is, use another variable that is declared outside the scope of the loop. This will make sure that it is not recreated everytime the loop runs.

int num = 1;
for(int i=1; i<maxValue; num+=2,i+=num){
    //Use the value of `i` here, it will be as you wanted. 
}

3 Comments

That looks like C++ to me, the OP is using Java
That souldn't make make much difference though. Made appropriate changes. Thank you for pointing that out. @MrWiggles
Thanks! It's what I was looking for
0

The sequence is to start with j=1 and k=4 and then derive next values of the series n times. The formula as follow:

Initial loop (i=0): 
j = 1, k = 4; 

Loop (i > 0 less than n):
Repeat below n times: 
temp = k; 
k = k + (k - j + 2); 
j = temp;
print value of j being the series;    

I assume that you take n as input from user and then generate the series nth times. Let's look at the following code example

int n = 10;  
for(int i = 0, temp = 0, j = 1, k = 4; i < n; i++, temp = k, k += (k-j+2), j = temp) {
   System.out.println(j);
}

Assuming that user inputs n = 10, the loop initializes i = 0 and continues until i < n is satisfied. It initializes j = 1 and k = 4 and then execute the body of the loop (printing j) followed by backing up the value of k, calculating new value for k and replacing the old value of j. The output for n = 10 is as follow:

1
4
9
16
25
36
49
64
81
100

Comments

0

Read Series number from the user and generate series based on given number.

Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int ans;
for(int i = 1; i <= n; i++){
  ans = i * i;
  System.out.println(ans);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.