Nesting Loops and Ifs

4. Adding Up Even and Odd Integers


Answer:

Yes. Each of the three sums was calculated correctly.

Adding Up Even and Odd Integers

smallsumflow

Here is a skeleton for the program. Compare the skeleton to the flowchart at right.

Fill in the blanks so the program matches the flowchart.

First, get the counting loop correct. If the loop is not correct, there is no hope for the rest of the program. The loop should count from one up to (and including) the limit.

In this program, most of the logic is contained inside the loop body.

It is best to write a program in stages. Write and debug each stage before building on it. This is like building a house. Build the foundation first, then build upon it. In a program with a main loop, the first stage is building the loop.

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 =  ;
    
    while (   )    
    {
      (more statements will go here later.)

       ;
    }

    System.out.print  ( "Sum of all : " + sumAll  );
    System.out.print  ( "\tSum of even: " + sumEven );
    System.out.println( "\tSum of odd : " + sumOdd  );
  }
}

Question 4:

Fill in the three blanks.