3 Replies - 1423 Views - Last Post: 18 October 2009 - 01:55 PM Rate Topic: -----

#1 pennstatelions  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 13
  • Joined: 05-October 09

Sum of Numbers

Post icon  Posted 18 October 2009 - 01:33 PM

Write a code that will ask the user for a number and then sum the numbers from 1 to the number inputted by the user. Use a while loop in your code.

I'm really not sure how to do the part about adding the numbers from 1 to the number provided. So far I have:
Scanner input= new Scanner (System.in);
System.out.print("Enter an integer");
int x= input.nextInt();
int sum=1;
while (x>=1){
sumt += x;
x++;
}



I feel like I was on the right track until the "sumt" part..

Is This A Good Question/Topic? 0
  • +

Replies To: Sum of Numbers

#2 erik.price  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 485
  • View blog
  • Posts: 2,690
  • Joined: 18-December 08

Re: Sum of Numbers

Posted 18 October 2009 - 01:40 PM

Try a for loop instead. You could use a while loop, but a for would be more convienent.

int sum = 0;
for(int i=1; i <= x; i++)
{
     sum += i;
}



I'm not sure if I read your question right.

Correct me if that's not what you're looking for.

EDIT 2: didn't see the "use a while loop" part. check out Martyr2's post for how to do it that way

This post has been edited by erik.price: 18 October 2009 - 01:44 PM

Was This Post Helpful? 0
  • +
  • -

#4 Martyr2  Icon User is offline

  • Programming Theoretician
  • member icon

Reputation: 4323
  • View blog
  • Posts: 12,106
  • Joined: 18-April 07

Re: Sum of Numbers

Posted 18 October 2009 - 01:41 PM

You are close...

Scanner input= new Scanner (System.in);
System.out.print("Enter an integer");
int x= input.nextInt();

int sum=0;
int count = 1;

// Loop from 1 to the number they entered
while (count <= x){
	// Accumulate in sum
	sum += x;
	count++;
}

System.out.println("Sum is: " + sum);



We setup a counter to go from 1 to the number they entered, each time through the loop adding the value of x onto sum.

:)

This post has been edited by Martyr2: 18 October 2009 - 01:42 PM

Was This Post Helpful? 2
  • +
  • -

#5 macosxnerd101  Icon User is online

  • Self-Trained Economist
  • member icon




Reputation: 10397
  • View blog
  • Posts: 38,479
  • Joined: 27-December 08

Re: Sum of Numbers

Posted 18 October 2009 - 01:55 PM

I may be missing something, but this just sounds like multiplication. Try this:
product = x * n; //x is the number, n is the number of times to add


Was This Post Helpful? 0
  • +
  • -

Page 1 of 1