Re: Need loop idea please!

Do you have any ideas? What have you tried? Where are you stuck?

How would you do this in your head, without a computer?

Recommended reading: The for Statement (The Java™ Tutorials > Learning the Java Language > Language Basics)

Actually, why do you want to do this with a loop? You seem to already have the math figured out. Can you give an example with a larger range?

Re: Need loop idea please!

I know what I need the loop to do, I just don't know how to execute it in the body of the loop. I'm very new to java and need to do this for a homework assignment. Let's use another example - m= 7 and n = 101

Here is what I have so far: (I know the loop will not break the way it is written)

import javax.swing.JOptionPane;

public class OddSum {

public static void main(String[] args) {

int m,n;

String num1Str, num2Str;

//Get a pair of integers from users

num1Str = JOptionPane.showInputDialog("Enter a positive odd integer: ");

m = Integer.parseInt(num1Str);

num2Str = JOptionPane.showInputDialog("Enter a positive odd integer that is larger than " + m );

n = Integer.parseInt(num2Str);

System.out.println (myOddNum(m,n));

}

public static int myOddNum(int m, int n){

int localSum = 0;

int temp = 0;

while (m <=n){

temp = m - (m + 2) + (n - 2) + n;

localSum = localSum + temp;

}

return localSum ;

Re: Need loop idea please!

What should the answer be when m is 7 and n is 101?

Re: Need loop idea please!

7 - 9 + 11 - 13 + 15 - 17 + 19 - 21 + 23 - 25 + 27 - 29 + 31 - 33 + 35 - 37 + 39 - 41 + 43 - 45 + 47 - 49 + 51 - 53 + 55 - 57 + 59 - 61 + 63 - 65 + 67 - 69 + 71 - 73 + 75 - 77 + 79 - 81 + 83 - 85 + 87 - 89 + 91 - 93 + 95 - 97 + 99 - 101 = -48

Re: Need loop idea please!

Quote:

Originally Posted by

**Montrell79**
needs to calculate the following series: 5 - 7 + 9 = 7

Which is the same as (m - (m + 2) + (n -2) + n)

Erm.. no it isn't :P

**M - (M + 2) + (N - 2) + N** == **5 - 7 + 7 + 9**

Re: Need loop idea please!

I think I'm a little closer now, but this method only works using the example given of m =5 and n =9, but not if I plug in other numbers that are more than 4 digits apart. I know there is an error in my logic. Can anyone help? Thanks!!

while (m <=n){

temp = m *(Math.pow(1, -3)) - 2;

m+= 2;

localSum = (int) temp;

Sorry but I don't know what this means: Please use tags when posting your code

Re: Need loop idea please!

Let's try this again:

Code Java:

//
while (m <=n){
temp = m *(Math.pow(1, -3)) - 2;
m+= 2;
localSum = (int) temp;

Re: Need loop idea please!