Nested if Statement

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
go to previous page   go to home page   go to next page

Answer:

Sounds like a good place for an if statement.

Nested if Statement

Here is the not-quite finished program:

import  java.util.Scanner;

// User enters a value N
// Add up odd integers,  
// even  integers, and all integers 1 to N
//
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 )    
    {
      sumAll = 
      
      if (  )

        sumEven =  ;

      else
        sumOdd =  ;

      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 loop body in this program contains an if statement. This is fine. An if statement inside of a loop body is called a nested if. There is nothing special about it; it works just as it would outside of the loop body.

QUESTION 6:

Fill in the four blanks to finish the program. (Hint: use the remainder operator, % in the if statement. The remainder of an odd number divided by two is one.)