Jump to content


Check out our Community Blogs

Register and join over 40,000 other developers!


Recent Status Updates

View All Updates

Photo
- - - - -

while loop (sum of odd integers)

loop

  • Please log in to reply
2 replies to this topic

#1 GTghost

GTghost

    CC Newcomer

  • Just Joined
  • PipPip
  • 12 posts

Posted 26 September 2011 - 04:10 PM

How would I go about getting the sum of the odd numbers between the starting and ending numbers.
I got the easy part, the sum of all numbers between the first integer and second integer, but I need to sum all the odd integers between the first and second.


// ***********************
// *                     *
// * LAB05A.java, CSc 15 *
// *                     *
// ***********************
import java.util.Scanner;
public class Lab05A
{
 public static void main(String[] args)
 {
  // Variables
  int start;
  int end;
  int count;
  int sum;
  
  Scanner keyboard = new Scanner(System.in); //input - java scanner
  
  // PROGRAM START
  System.out.print("What is the beginning number: ");
  start = keyboard.nextInt();
  
  System.out.print("What is the end number: ");
  end = keyboard.nextInt();
  
  sum = 0;
  count = start;  
  
  
  while (count <= end)
  {
   sum = sum + count;
   count++;
  }
  
  System.out.println("The sum of all integers between " + start + " and " + end + " is " + sum + " (inclusively).");
  System.out.println("The count value is " + count + ".");
  
  
  
 
 }
}


  • 0

#2 Vaielab

Vaielab

    Programming God

  • Expert Member
  • PipPipPipPipPipPipPip
  • 1382 posts
  • Location:Quebec City
  • Programming Language:Java, C++, C#, PHP, JavaScript, Visual Basic .NET, Transact-SQL, ActionScript

Posted 26 September 2011 - 04:41 PM

This look like a school homework, so I won't give you the answer directly, but you should take a look at a operation called modulus
  • 0

#3 GTghost

GTghost

    CC Newcomer

  • Just Joined
  • PipPip
  • 12 posts

Posted 26 September 2011 - 04:44 PM

This look like a school homework, so I won't give you the answer directly, but you should take a look at a operation called modulus

I know I can do this with if statements and remainder, but is it possible to do with while loops?
  • 0





Also tagged with one or more of these keywords: loop

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download