Hi guys,

I'm having some trouble with my Java homework, and I was wondering if any of you could point me in the right direction. I need to find a loop that will add all the whole numbers from 1 to 1000 and print only the total. I've been spending much of time working with a for loop, but I'm not sure if that's the right loop to be using.

Any help would be greatly appreciated.

Thanks

Yes, a for loop is appropriate. Post what you have so far and ask specific questions about the troubles you are having.

Here are some steps:

Declare a variable of type integer and initialise it to 0
Look up the structure of a for loop and change one of the numbers to 1000.
You will also have to play with the operators too to make sure it only goes up to 1000.
In the for loop body you add current integer to the one you declared in the first step.

If you do it right you should get 499,500 - Ezzaral, care to confirm?

Member Avatar for coil

Actually, I got 500,500. I think you forgot to add the last 1000 - check your for-loop, it should just be a simple error.

Actually, I got 500,500. I think you forgot to add the last 1000 - check your for-loop, it should just be a simple error.

The OP asked for the numbers up to 1000, not including 1000 :P score 1 for Katana lol

Member Avatar for coil

Well...1 to 1000...I suppose you can interpret it both ways :)

Okay, I will try all methods posted, but right when I posted this question, I had to leave for work. The code I have just counts up to 1000. I can't get it to add all the numbers between.

This is the code I already have:

public class CHomework3A
{

	public static void main(String astrCommandLine[])
	{
		// A loop that adds all the whole numbers between 1 and 1000
		int intCounter = 0;
		int intTotal;
		
		for (intCounter = 0; intCounter <= 1000; intCounter++)
		{
			intTotal = 0 + intCounter;
			System.out.println("The total is " + intTotal + ".");
		}
	}

}

(1) The code in the line 12 is not correct. The code in line 12 could be:
intTotal = intTotal + intCounter;
or
intTotal += intCounter;
(2) The code in line 13 should be moved/inserted into the place between the line 14 and 15.
(3) The initial value for the control parameter intCounter in the for loop could be 1 rathern than 0
jwmollman , in the future can you try to use while or do while loop to accomplish the task? or use a recursive/iterative method to do the job? We have various ways to go.

(1) The code in the line 12 is not correct. The code in line 12 could be:
intTotal = intTotal + intCounter;

Thanks for the reply. I have tried this and I get a compiler error. It tells me "the local variable intTotal may not have been initialized".

jwmollman , in the future can you try to use while or do while loop to accomplish the task? or use a recursive/iterative method to do the job? We have various ways to go.

We can try a while or a do while loop. How would I go about it that way?

Thanks.

Member Avatar for coil

Basically it's the same as the for-loop. Pseudocode:

int i=1, sum=0; //initialize counter & sum variable

while(i<[the upper limit, e.g. 1001]) { //termination condition
<add i to sum>
}

Basically it's the same as the for-loop. Pseudocode:

int i=1, sum=0; //initialize counter & sum variable

while(i<[the upper limit, e.g. 1001]) { //termination condition
<add i to sum>
}

Okay I have tried using a while loop in this situation as you have suggested. I retyped my program and have the following, but all it does it print numbers 1 to 100, and then my console sits there (doesn't show the prompt as if the program exited).

// -----------------------------
// Name: John Mollman
// Class: Java 1 - 5271
// Abstract: CHomework3A
// -----------------------------



public class CHomework3A
{

	public static void main(String astrCommandLine[])
	{	
		// ********************************
		// Step 2
		// ********************************
		
		// A loop that adds all the whole numbers between 1 and 1000
		int intCounter = 1;
		int intSum = 0;
		
		while (intCounter < 1001)
		{
			intSum = intCounter + intSum;
		}
		
		System.out.println("The total is " + intSum + ".");
	}

}

A for loop is a specialized sort of while loop, with a little syntactic sugar on it.
You can pretty much always rewrite the one as the other.

A do...while() is a little different, in that it executes once before it evaluates the test condition. This can be useful.

Like so:

do
{
// body of loop
} while (condition)

Stick that in the back of your head, it's handy once in a while.
Generally, you can get around it by manipulating the condition so it's true going into the loop.

boolean cond = true;
while (true)
{
//do some stuff
if (youFeelLikeIt()) 
  cond = false;
}

is basically a do...while() loop. I use this form because I like to have the condition at the top of the loop. Having it at the bottom is annoying to me.

I have tried this and I get a compiler error. It tells me "the local variable intTotal may not have been initialized".

That's correct. It hasn't. For that code to work you have to initialize intTotal to zero, probably at declaration.

Line 8 would read

int intTotal =0;

I managed to solve the issue. I went ahead and used a for loop for this problem.

int intIndex = 0;
int intTotal = 0;
		
for (intIndex = 1; intIndex <= 1000; intIndex += 1)
{
	intTotal += intIndex;
}
		
System.out.println("The total is " + intTotal + ".");

the local variable intTotal may not have been initialized

The code in line 8 should be:
int intTotal=0; //so that the intTotal is initialized.

We can try a while or a do while loop. How would I go about it that way?

Define the condition for the while loop, as Jon.kiparsky discussed earlier, as follows
while(intCounter <=1000) {
...
}
You may add the rest of the code before, within the loop body, and after the loop.

Okay, now that you've got it done that way, can you think of any shorter ways to do it? There's a way to cut the number of iterations of the loop in half, and then a way to collapse the whole thing into a formula - once you have the first, you should be able to produce the second.

(depending on your teacher, including these might be a cool way to get some extra credit, and it's certainly worth thinking it out in any case)

Mine suggestion will be thats you can use either for loop or while loop for this program.

class CHomework3A

 {
     public static void main(String astrCommandLine[])

{
      int Total=0;


  /* for(int Counter=0; Counter<=1000;Counter+=1)
{
      Total += Counter;
}*/

int Counter=0;
 while(Counter<=1000)
{
      Total += Counter;
      Counter+=1;
}
 System.out.print("The total is " + Total + ".");
 }
}

Total += Counter;


the reason that why i add total with Counter is that when loop starts
counter=0 and total=0 so sum will be store in variable total the next time
counter=1 and total as zero is store in it before so it will be zero and 0+1 will be 1 now
total will became 1.and again when the loop circles then counter will be
2 and as total is one so 1+2=3 so 3 will be store in the total.this how it
will add as many numbers as you add and if you want to declare just the final
result of additions then declare your this statement System.out.print("The total is " + Total + ".");
outside the loop.i had used both loops so that you will get an idea with while loop also.

Counter+=1;

you can either use counter++ or counter+=1 these are known as post increments or ++counter which is
know as pre-increment.In pre-increment counter is incremented before being used and in the
post-increment counter is incremented after being used.

hope this will help you.

Brilliant! Where would we be without you, Captain WhatHeSaid?

sorry what sir are you talking to me man haan

Okay, now that you've got it done that way, can you think of any shorter ways to do it? There's a way to cut the number of iterations of the loop in half, and then a way to collapse the whole thing into a formula - once you have the first, you should be able to produce the second.

(depending on your teacher, including these might be a cool way to get some extra credit, and it's certainly worth thinking it out in any case)

I have no idea how I could make that any shorter. I'm thinking that's as short as I can get it, as I'm still an early beginner at programming.

Do you have any idea how I could go about shortening it?

I'm not thinking shorter in lines of code, I'm thinking of a shorter loop. Your code is actually quite clean, nice work.
But for a shorter loop, think about it this way: is there any way you can add two numbers each time you go through the loop? If you could do that, you wouldn't have to loop 1000 times, you could do it 500, right?
(this is more of a math puzzle than just a java puzzle, so think about it on paper before you try to code it)

Are you talking about using a nested for loop?

for(int i=0;i<=100;i++){
for (int j=0; j<=10; j++){
}
}

The top for loop will do less loops but will do more loops inside it.

Interesting idea, but no, that's not what I have in mind. As you say, it does the same work of work as the other, and more importantly, it doesn't really save you a lot of work in the end.

The way I'm thinking of also does about the same amount of work, but it leads directly to a O(1) solution. I'll let you puzzle over it a little more: think of another way to group the numbers, such that you can have a method

public int sum(int n) {}

which returns the sum from (1..n) for any even n in a loop from 1 to n/2 - you have to think a little about odd numbers, and that's a clue.

I'm not thinking shorter in lines of code, I'm thinking of a shorter loop. Your code is actually quite clean, nice work.
But for a shorter loop, think about it this way: is there any way you can add two numbers each time you go through the loop? If you could do that, you wouldn't have to loop 1000 times, you could do it 500, right?
(this is more of a math puzzle than just a java puzzle, so think about it on paper before you try to code it)

So are you saying add two numbers onto the index at a time, rather than just one. Then I can just loop it 500 times rather than 1000?

I'm thinking the code could be something like this:

int intIndex = 0;
int intTotal = 0;
		
for (intIndex = 1; intIndex <= 500; intIndex += 2)
{
	intTotal += intIndex;
}
		
System.out.println("The total is " + intTotal + ".");

That's still not what I had in mind, but it's worth looking at.
As you've got it, the loop isn't quite right - you can halve the limit or double the step, but if you do both you're only going to go around 250 times. So we'll fix that. We also need to be sure we add in all the numbers - that's also an easy fix. Looks like this:

for (intIndex = 1; intIndex <= 1000; intIndex += 2)
{
	intTotal += intIndex;
    intTotal += intIndex+1;
}

But hang on - that's maybe a bit tidier if we do it like this:

for (intIndex = 1; intIndex <= 500; intIndex += 2)
{
    intTotal += (2*intIndex)+1;
}

Okay, well now we're doing 3 steps 500 times. That would be a step backwards, except the 500 increments of intIndex are just the same increments we skipped over when we went to doing the loop 500 times.
So we're still right about where we started, but seeing new ways of getting at it, that's good.

So we've tried grouping the series like this:

(1+2)+(3+4)+(5+6)+..+(997+998)+(999+1000)


What if we could find a way of grouping the terms of the series so that each pair had a constant value? The iterative solution would still be a loop:

for (intIndex = 1; intIndex <= 500; intIndex += 2)
{
	intTotal += someConstant;
}

We shave off a few instructions, maybe, but still a loop and so still increasing linearly with X - if we want to get the sum of 1 to a million, it's going to take us a thousand times as long, and so forth. But if we can get to this, then we can dispense with the loop entirely, and use multiplication.

intTotal = someConstant*500;

Ah, that's shorter.

So all we need is a way to group these guys so each pair comes to the same amount and you've gone from an algorithm that takes 10 times as long to do 10 times as many numbers to an algorithm that takes exactly the same time for any number you give it.

Have a go at it, if you like.

For present question the teacher of mental arithmetic may tell students count in one's head as follows.
There are 499 expressions.

1 + 999 = 1000
2 + 998 =1000

499 + 501 =1000
(only 500 is missing)
All expressions have the same outcome of 1000. So the outcome of adding all the whole numbers from 1 to 999 is 1000×499 + 500 (499,500).

The above understanding by count in one’s head can be explained by the following for loop

int sum = 0;
for (int i=1; i<=499; i++)
sum += i+ (1000-i) ;  //which is equivalent to  sum += 1000;   
// only the number of 500 is missing

The above loop thus could be simplified by an expression:
sum = 499*1000 // do the accumulation of 1000 499 times

Therefore, the code for the following for loop:

int sum =0;
for (i=1;i<=999;i++)
sum += i;

could be simplified by an expression:
sum = 499*1000+500;
where the final sum (499,500) is the consequence of adding all the whole numbers from 1 to 999

Of course, we have to follow computer professor’s instruction to obtain the result of adding all numbers from 1 to 999 by a loop rather than an expression.

The usual form of that expression is
Sum(n) = n(n+1)/2
but that's not a loop.

How about recursion:

int sum(int n) {
   return (n==1)?1:n+sum(n-1);
}

Does that count as a loop?

This is a simple arithmetic progression...
Well I guess now I know why they teach you maths at school.

The formula to find the sum of an arithmetic progression is
(n/2)*(a+l)
n-no. of terms in the progression
a- first term
l-last term

In our case
n-1001
a-0
l-1000

so the sum would be
(1001/2)*(0+1000) = 500*1001 = 500500

Yes, what I was leading to was the simple formula, though the point was not just that there is a formula, but more to derive the formula from the process, and to start thinking about time complexity.

So, thnking about the way a process is done can lead you to a better way of doing it. Not a very surprising conclusion, but it's always good to have a concrete example of it.

public class WholeNumberSum {
public static void main(String args[]){
    int num,sum=0,i=1;
    while(i<1000)
    {
        sum=sum+i;
        i++;

    }
    System.out.print(sum);
}
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.