Nesting Loops and Ifs

Site: Saylor Academy
Course: CS101: Introduction to Computer Science I
Book: Nesting Loops and Ifs
Printed by: Guest user
Date: Tuesday, 20 May 2025, 8:29 AM

Description

This chapter discusses how control structures such as loops and if statements can be combined together to implement program logic.

1. Nesting Loops and Ifs

This chapter shows how counting loops and if statements are used together to implement the logic of a program.

These examples give you practice in building programs out of fundamental pieces.

Chapter Topics:

      • Adding up even and odd integers
      • Computing N factorial
      • Dropping a brick
      • Making a rectangle of stars

Question 1:

With only paper and pencil, would you like to add up all the integers from one to one thousand?


Source: Bradley Kjell, http://programmedlessons.org/Java9/chap21/ch21_01.html
Creative Commons License This work is licensed under a Creative Commons Attribution-NonCommercial 4.0 License.

2. Adding Up Integers


Answer:

Probably not. Even with a calculator this would be tedious.

Adding Up Integers

sumflowsketchThere is a formula for the sum of integers from 1 to N and similar formulas for the sum of even or of odd integers from 1 to N, but pretend you don't know that. Let us write a program that calculates these three sums by directly adding up the integers:

  • The sum of all integers 1 to N
  • The sum of odd integers 1 to N
  • The sum of even integers 1 to N

The user enters N, and the program counts up from one to N adding each integer to the appropriate sums. The flowchart shows how the program works.

The flowchart shows a loop that increments count from 1 to N. In the loop body, the current value of count is always added to the sum of all integers.

But more work needs to be done. count should be added to the sum of odds only if it is odd and added to the sum of evens only if it is even.

This box: decide which sums should get the number needs more detail.



Question 2:

How can you decide if count should be added to the sum of even or to the sum of odd integers?

3. Nested IF


Answer:

Use an if statement.

Nested IF

sumflowThe flowchart is now a refinement of the first one. It explicitly shows three sums, and how each sum is handled. The loop body shows that the current value of count is always added to sumAll. An if statement determines if count is added to sumEven or sumOdd.

An if statement that is part of a loop body is a nested if. (Another type of nested if is when an if statement is part of another if statement.)

Play with the flowchart and see if it works. Pick some small integer, perhaps N==3, and follow the flowchart by hand. Then try an unexpected value, like N==1 and see if the logic works.


Question 3:

Does the flowchart work for N==1?

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.

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?

6. Nested if Statement


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
//
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 )    
    {
      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.)

7. Complete Program


Answer:

The completed program is given below.

Complete Program

smallsumflow (1)
 Here is the complete program that adds up even and odd integers from zero the limit, N, specified by the user:

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 )    
    {
      sumAll = sumAll + count ;
      
      if ( count % 2 == 0  )
        sumEven = sumEven + count ;

      else
        sumOdd  = sumOdd  + count ;

      count = count + 1 ;
    }

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

It would be odd if you did save this program to a file and run it. An even better idea would be to pretend you had not seen it, and to try to create it from scratch.

Question 7:

Do you need to calculate all three sums sumAllsumOdd, and sumEven?

8. Factorial


Answer:

No. You only need two of them. The final output statements could be:

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

Factorial

Here is the definition of N factorial:

N Factorial == N! == N * (N-1) * (N-2) * (N-3) * . . . 4 * 3 * 2 * 1

N must be a positive integer or zero, and 0! is defined to be 1. For example,

6! == 6 * 5 * 4 * 3 * 2 * 1 == 720

Let us write a program that computes N! . The program checks that N is positive or zero, then computes the factorial.


Question 8:

Say that the user enters a 5. How can the program generate the integers 5, 4, 3, 2, and 1 that are to be multiplied?

9. Flowchart of the Program


Answer:

It will use a counting loop.

Flowchart of the Program

factflowOne way to do this is to use N as the counter, and count it down through the values 5, 4, 3, and 2. These values are multiplied together one by one. There is no need to multiply by 1, so the counting loop's condition is N > 1.

The flowchart shows how the program works. First it tests if N is positive or zero. If so, it calculates N!

N! is calculated by first initializing Fact to 1. Next, a counting loop multiplies Fact by N, then by N-1, then by N-2, and so on down to 2.

If N starts out at 0 or at 1, then the correct value of Fact is its initial value of one. The loop body will not execute even once.

This program uses somewhat trickier logic than previous programs. Study the flowchart until you see how it works. Don't worry about the details of Java right now. The flowchart is a logic design for the program. It would work for any language.


Question 9:

Mentally go though the chart for some values of N. Does it work correctly for :

N == -5 
N ==  0
N ==  1
N ==  4?

10. Starting the Program


Answer:

Yes. It is nice to check these cases out in advance before you start writing the program.

Starting the Program

factflow

Here is a start to the program.

Notice how the program matches the flowchart, especially how the while statement is nested in the true branch of the if statement. The indenting (and the braces {}) show this structure.

Another thing to notice is that the integer variables are of type long. This is because the values are expected to get very large, and long can hold larger integers than int.


import  java.util.Scanner;

// User enters integer N.  
// The program calculates N factorial.
//
public class Factorial
{
  public static void main (String[] args ) 
  {
    Scanner scan = new Scanner( System.in );
    long N, fact = 1; 
 
    System.out.print( "Enter N: " );
    N = scan.nextLong();

    if (  )
    {
      while (   )    
      {
 
         ;

         ;
      }
      
      System.out.println( "factorial is " + fact );
    }
    
    else
    {
      System.out.println("N must be zero or greater");
    }
  }
}

Question 10:

Fill in the four blanks to complete the program. Here are some phrases you might use:

  fact = fact*N 
  N > 1 
  N = N - 1  
  N >= 0 

11. Complete Factorial Program


Answer:

The complete program is given below.

Complete Factorial Program

This program is suitable for copying into a program editor, compiling and running in the usual way. Animal brains, such as those in humans, learn best when they see things happen. Run the program. See things happen.

import  java.util.Scanner;

// User enters integer N.  
// The program calculates N factorial.
//
public class Factorial
{
  public static void main (String[] args ) 
  {
    Scanner scan = new Scanner( System.in );
    long N, fact = 1; 

    System.out.print( "Enter N: " );
    N = scan.nextLong();

    if ( N >= 0 )
    {
      while ( N > 1 )    
      {
        fact = fact * N;
        N    = N - 1;
      }
      System.out.println( "factorial is " + fact );
    }
    else
    {
      System.out.println("N must be zero or greater");
    }
  }
}               
Here are several runs of the program. It is amazing how quickly factorial becomes enormous.

factorialShot

Warning!   Factorial becomes so big, so fast, that 20! is as large as this program can calculate. However, it will give you an answer for N larger than 20. But the answer will be wrong. This is because when a result requires more bits than a variable has, the variable ends up with garbage. This behavior is called overflow and is a frequent problem with computers.


Question 11:

We don't want the user to see the incorrect result that is calculated when N is larger than 20. How can the program be modified to do this?

12. Input Testing


Answer:

Change the condition in the if statement so that only integers in the range 0 to 20 are allowed.

Input Testing

Here is the corrected program:

import  java.util.Scanner;

// User enters integer N.  
// The program calculates N factorial.
//
public class Factorial
{
  public static void main (String[] args ) 
  {
    Scanner scan = new Scanner( System.in );
    long N, fact = 1; 

    System.out.print( "Enter N: " );
    N = scan.nextLong();

    if ( N >= 0 && N <= 20 )
    {
      while ( N > 1 )    
      {
        fact = fact * N;
        N    = N - 1;
      }
      System.out.println( "factorial is " + fact );
    }
    else
    {
      System.out.println("N must be between 0 and 20");
      System.out.println("Factorial for N less than 0 is not defined.");
      System.out.println("Factorial for N greater than 20 causes overflow.");
    }
  }
}

Question 12:

This program calculates N! for a very limited range of N. Recall that variables of type double have a much greater range than integer types. Would using variables of type double solve the problem?

13. Avoid Calculating Factorial


Answer:

Maybe. However, even with type double, overflow is reached at N==170.

Avoid Calculating Factorial

Another problem with double is that the result is only an approximation to the exact value. doubles have the equivalent of about 15 decimal digits of accuracy. This might not be good enough. For example, if you are doing number theory or cryptography, approximations are useless.

Often math formulas use factorial, but explicit calculation of factorial can be avoided by rearranging the operations of the formula. Avoid explicit calculation of factorial. For example, the number of arrangements that can be made of r objects selected from n objects is: n! / (n-r)!

Say that you want to select 5 objects out of 30. It looks like you need to calculate both 30! and 25! both of which would be disasters. But using cancellation, the formula becomes:

30 * 29 * 28 * 27 * 26

which can be calculated without problems. This is one of the programming exercises.


Question 13:

If you drop a brick from a tower, what happens?

14. Falling Bricks


Answer:

The brick falls to the ground.

Falling Bricks

fallingBrickGravity pulls upon the brick, causing it to go faster and faster. The distance between the brick and where it was released after t seconds is:

distance = (1/2)*G*t2
      • t is the number of seconds since the brick was released.
      • G is a constant: 9.80665
      • distance is in meters.

After 0.0 seconds, the brick has dropped

(1/2) * 9.80665 * (0.0)2  =  0.5 * 9.80665 * 0.0 = 0.0 meters.

After 1.0 second, the brick has dropped

(1/2) * 9.80665 * (1.0)2  =  0.5 * 9.80665 * 1.0 = 4.903325 meters.

After 2.0 seconds, the brick has dropped

(1/2)* 9.80665 * (2.0)2  =  0.5 * 9.80665 * 4.0  =  19.6133 meters.

After 3.0 seconds, the brick has dropped

(1/2)* 9.80665 * (3.0)2  =  0.5 * 9.80665 * 9.0  =  44.1299 meters.

This is getting tedious. Let's write a program that does the calculation for many values of t and prints the results as a table.


Question 14:

Let's use a loop.

  • What kind of loop will be used?
  • What is the loop control variable?
  • What does the loop body do?

15. Gravity Program Skeleton


Answer:

  • What kind of loop will be used? A counting loop, since t will increase until it hits a limit.
  • What is the loop control variable? Time, t, since it is increased, second by second.
  • What does the loop body do? It calculates distance for the current value of t , then increases t.

Gravity Program Skeleton

The program looks like this:

import java.util.Scanner;

// User picks ending value for time, t.
// The program calculates and prints 
// the distance the brick has fallen for each t.
//
public class FallingBrick
{
  public static void main (String[] args ) 
  {
    final  double G = 9.80665;  // constant of gravitational acceleration
    int    t, limit;            // time in seconds; ending value of time
    double distance;            // the distance the brick has fallen
    Scanner scan = new Scanner( System.in );

    // Get the number of seconds
    System.out.print( "Enter limit value: " );
    limit = scan.nextInt();

    // Print a table heading
    System.out.println( "seconds\tDistance"  );  // '\t' is tab
    System.out.println( "-------\t--------"  ); 

    t =  ;
    
    // calculate the distance for each second
    while (  )    
    {
      (more statements will go here later.)

      t = 
    }

  }
}        


Question 15:

First get the loop correct. Three things must be coordinated: Time starts at zero, increases by one second each iteration, and when time equals limit the last value is printed out.

16. Filling in the Formula


Answer:

Did you get the condition exactly correct? Check below.

Filling in the Formula

The program so far:

import java.util.Scanner;

// User picks ending value for time, t.
// The program calculates and prints 
// the distance the brick has fallen for each t.
//
public class FallingBrick
{
  public static void main (String[] args )  
  {
    final  double G = 9.80665;  // constant of gravitational acceleration
    int    t, limit;            // time in seconds; ending value of time
    double distance;            // the distance the brick has fallen
    Scanner scan = new Scanner( System.in );

    // Get the number of seconds
    System.out.print( "Enter limit value: " );
    limit = scan.nextInt();

    // Print a table heading
    System.out.println( "seconds\tDistance"  );  // '\t' is tab
    System.out.println( "-------\t--------"  ); 

    t  =  0 ;
    
    // calculate the distance for each second
    while (  t <= limit )    
    {

        // calculate distance

        // output result

      t = t + 1 ;
    }

  }
}

The loop body will execute for t = 0, 1, 2, ..., limit. At the end of the last execution, t is changed to (limit+1). But the conditional expression will not allow execution back into the loop body when t is (limit+1).

Now calculate the distance for each value of t. Here is the formula you might find in a physics textbook:

distance = (1/2)Gt2

Translate the formula into a Java statement to fill the first blank.


Question 16:

Fill in the two blanks. Watch out: there are two traps!

17. Complete Program


Answer:

The finished program is given below.

Complete Program

The complete program can be copied and pasted into an editor, and run in the usual way.

import java.util.Scanner;

// User picks ending value for time, t.
// The program calculates and prints 
// the distance the brick has fallen for each t.
//
public class FallingBrick
{
  public static void main (String[] args )  
  {
    final  double G = 9.80665;  // constant of gravitational acceleration
    int    t, limit;            // time in seconds; ending value of time
    double distance;            // the distance the brick has fallen
    Scanner scan = new Scanner( System.in );

    System.out.print( "Enter limit value: " );
    limit = scan.nextInt();

    // Print a table heading
    System.out.println( "seconds\tDistance"  );  // '\t' is tab
    System.out.println( "-------\t--------"  ); 

    t = 0 ;
    while (  t <= limit )    
    {
      distance = (G * t * t)/2 ;
      System.out.println( t + "\t" + distance );

      t = t + 1 ;
    }
  }
}

You could also write distance = 0.5*G*t*t;

What were the two traps in translating the formula? If you translated it as (1/2)*G*t*t, you fell into the first trap. (1/2) asks for integer division of 1 by 2, resulting in zero.

If you translated the formula as 1/2*G*t*t, you fell into the second trap. To the compiler, this looks like the first wrong formula because / has equal precedence to * and so 1/2 is computed first, resulting in zero.

A third problem is computing the square. Do it as t multiplied by t.


Question 17:

Now say that you want the table to show time increasing in steps of 0.1 seconds. Modify the program so that it does this with maximum accuracy. The user enters the limit in seconds.

18. Rows of Stars


Answer:

Recall that for maximum accuracy, the loop control variable should be an integer type. So the modified loop should look like this:
int tenths = 0 ;
while (  tenths <= limit*10 )    
{
  double t = tenths/10.0 ;        // be sure to include "point zero"
  distance = (G * t * t)/2 ;
  System.out.println( t + "\t" + distance );

  tenths = tenths + 1 ;
}

It is best to leave the formula as it was in the previous program, and to calculate t from tenths in an extra statement. (Sometimes people try to skip the extra statement by modifying the formula, but this saves little or no computer time and costs possible confusion and error.)

Rows of Stars

We want a program that writes out five rows of stars, such as the following:

*******
*******
*******
*******
*******

This could be done with a while loop that iterates five times. Each iteration could execute

 
System.out.println("*******")

But it is more useful to ask the user how many lines to print and how many stars are in each line:

Lines? 3
Stars per line? 13

*************
*************
*************

Now the user might ask for any number of stars per line, and no single println can do that.


Question 18:

Can a counting loop, such as we have been using, be used to count up to the number of lines that the user requested?

19. Counting Loop for Lines


Answer:

Yes — if the user asks for five lines, a loop should count 1, 2, 3, 4, 5.

Counting Loop for Lines

Here is the skeleton program, with the usual blanks. The skeleton focuses on getting the number of lines right and leaves the rest for later.

import java.util.Scanner;
//
public class StarBlock
{
  public static void main (String[] args ) 
  {
    Scanner scan = new Scanner( System.in );
    int numRows;      // the number of Rows
    int numStars;     // the number of stars per row
    int row;          // current row number

    // collect input data from user
    System.out.print( "How many Rows? " );
    numRows = scan.nextInt() ;

    System.out.print( "How many Stars per Row? " );
    numStars = scan.nextInt() ;

    
    
    while (  )    
    {
       System.out.println( "Row " + row );  // temporary software testing
       (more statements go here )

           
    }
  }
}

Some of the information collected from the user is not used yet. First concentrate on looping the correct number of lines.

(As usual, build the program in stages and make sure each stage is correct before building on it.)


Question 19:

Fill in the three blanks. Select from the following:

row > numRows
row <= numRows
row < numRows
row  =  0;
row  =  1;
row  = row + 1;
row  = row - 1;

(Not all choices are used.)

20. Number of Lines Done Correctly


Answer:

The program, with a correct outer loop, is below.

Number of Lines Done Correctly

If ( more stuff goes here ) somehow printed a row of numStars stars, the program would be finished.

import java.util.Scanner;
//
public class StarBlock
{
  public static void main (String[] args ) 
  {
    Scanner scan = new Scanner( System.in );
    int numRows;      // the number of Rows
    int numStars;     // the number of stars per row
    int row;          // current row number

    // collect input data from user
    System.out.print( "How many Rows? " );
    numRows = scan.nextInt() ;

    System.out.print( "How many Stars per Row? " );
    numStars = scan.nextInt() ;

    row  =  1;
    while ( row <= numRows )    
    {

      ( more stuff goes here )

      System.out.println();
      row = row + 1;
    }
  }
}

Now you must perform one of the most important tasks in computer programming: ignoring the big problem and looking at a little problem.

Breaking a big problem into several little problems and solving the little problems is called divide and conquer. It is (perhaps) the most important skill in programming. Often it is not clear how to break a big problem into smaller problems. Unfortunately, all too often programmers proceed without doing this and produce "spaghetti code" — a tangled mess of statements with no clear logic.

Wikipedia on Spaghetti Code


Question 20:

Clear you mind of all thoughts about the big program. Just think about the little problem. How would you print a row of numStars stars, one star at a time?

21. Printing a Row of Stars


Answer:

With a loop that counts 1 to numStars and prints a * for each iteration.

Printing a Row of Stars

Here is the answer to the little problem. The parts of the program that don't affect it have been (temporarily) cleared away.

    // collect input data from user
    System.out.print( "How many Stars per Row? " );
    numStars = scan.nextInt() ;


      int star = ;
      
      while ( star <=  )
      {
        System.out.print("*");
        
        
      }

      System.out.println();

Question 21:

Need I ask? Fill in the blanks so that numStars stars are printed.

22. Fitting the Two Pieces Together


Answer:

The following loop will print numStars stars all one one line.

int star = 1;
while ( star <= numStars  )
{
  System.out.print("*");
  star = star + 1;
}

Fitting the Two Pieces Together

Now you have two pieces: (1) the part that loops for the required number of lines and, (2) the part that prints the required number of stars per line. Here is the complete program with the two parts fitted together:

import java.util.Scanner;
//
public class StarBlock
{
  public static void main (String[] args ) 
  {
    Scanner scan = new Scanner( System.in );
    int numRows;      // the number of Rows
    int numStars;     // the number of stars per row
    int row;          // current row number

    // collect input data from user
    System.out.print( "How many Rows? " );
    numRows = scan.nextInt() ;

    System.out.print( "How many Stars per Row? " );
    numStars = scan.nextInt() ;

    row  =  1;
    while ( row <= numRows )    
    {
      int star = 1;
      while ( star <= numStars )
      {
        System.out.print("*");
        star = star + 1;
      }
      System.out.println();         // do this to end each line

      row = row + 1;
    }
  }
}

The part concerned with printing the right number of stars per line is in blue. Notice how one while loop is in the body of the other loop.

This is an example of nested loops. The loop that is in the body of the other is called the inner loop. The other is called the outer loop.


Question 22:

What would the program do if the user asked for a negative number of stars per line?

23. Live Code!


Answer:

Each line would consist of nothing but the end of line character that System.out.println()prints. The inner loop would not execute even once.

Live Code!

For your amusement and entertainment here is a JavaScript version of the program:

How Many Rows: How Many Stars: 


Of course, it would be good to copy the actual Java (previous page) to a file and to compile and run it.

Question 23:

On a clear evening, out in the country, far from city lights, about 6,000 stars are visible. Enter values so the program prints that many stars.

(If you ask for for than 70 stars per line, the excess stars for each line will print on a second line.)

24. Virtual Reality


Answer:

120 rows of 50 stars will work. (It might be stretching things a bit to call this a Virtual Reality program.)

Virtual Reality

You have reached the end of the chapter. A star student will review the following.

The next chapter discusses more about loops.