I have no idea how this works.

• December 12th, 2011, 08:47 PM
GeneralPihota
I have no idea how this works.
1st Post, I'm taking a high school AP computer science class based around java, and my teacher told me to do the commented out statement.

I've never seen "for" before or "+=" and i don't know what addSum(int n) means.
Really i have no idea how this works and my class is too big for my teacher help me, since i suck less at java than other students.
Can anyone explain this to me? I just guessed it was an algorithm, really i have no idea.

//calcualate and return the sum of all odd integers from 1 to n
{
int sum = 0;
for(for i = 1;i<=n;i+=2)
sum += i;
return sum;
• December 12th, 2011, 09:19 PM
KevinWorkman
Re: I have no idea how this works.
• December 13th, 2011, 08:01 AM
GeneralPihota
Re: I have no idea how this works.
Thanks a lot i'll read those and look at tutorials before posting
• December 29th, 2011, 09:55 PM
elisha.java
Re: I have no idea how this works.
Let me try to describe to you what the method means:
methods are designed to do things - you probably know that. Some methods take arguments or commonly known as parameters. Your method above takes in a primitive of type int (n). You might ask yourself where you will find the int variable to be passed into the method when called: It is easy, after you instantiate your class(the same class your method was created for), you will be able to call the addSum(int n) method by for instance saying myObject.addSum(4);
After you pass the argument to the method, the method will loop through (the number of times depend on the size of your int value passed). After that, each time a value of i is produced by the loop (for loop), it gets added to the sum - which was initialized to zero at first(during declaration). After int i is no longer less than n, the loop ends and the sum is shown.
There are other ways of calculating variables in java. Eg: "X *= Y" is same as X * Y then assign value to X
X/=Y is like division (x/y) then assign to X. X%=Y means getting the modulus (remainder) then assign to x. All of the work the same way. Just check out some tutorials and you will be fine. javabeginner.com is cool too.
I hope this helps.