Completion requirements
This chapter discusses how control structures such as loops and if statements can be combined together to implement program logic.
5. My Three Sums
Answer:
The partially completed program is below.
The last blank could also have been filled by
count++ ;
My Three Sums
import java.util.Scanner; // User enters a value N // Add up odd integers, // even integers, and all integers 1 to N // public class AddUpIntegers { public static void main (String[] args ) { Scanner scan = new Scanner( System.in ); int N, sumAll = 0, sumEven = 0, sumOdd = 0; System.out.print( "Enter limit value: " ); N = scan.nextInt(); int count = 1 ; while ( count <= N ) { System.out.println("count: " + count ); // temporary statement for testing (more statements go here ) count = count + 1 ; } System.out.print ( "Sum of all : " + sumAll ); System.out.print ( "\tSum of even: " + sumEven ); System.out.println( "\tSum of odd : " + sumOdd ); } } |
The program, given above, can be compiled and run. As soon as you have a program that can be run, do so. Correct syntax errors (if any) and look for bugs. Insert some temporary println
statements to help in the bug search. (Or use a debugger.)
The loop counts through the integers we are interested in, but it does not yet do anything with them. This is what we want to happen:
- Each integer added to
sumAll
. - Each odd integer added to
sumOdd
. - Each even integer added to
sumEven
.
Question 5:
How do you decide which sum (sumOdd
or sumEven
) to add an integer to?