Title: For Loop Examples
Course: CPS 161: An Intro to Programming with Java - DL MM MASTER

For Loop Examples

1. In the previous video, a student asked if they could have 2 counters in a for loop where the counters are of different types. He posted his best attempt on a discussion board and here it is:


 public class test {
    public static void main(String[] args) {
        double d; int m; //This is the only way to do multiple primitives in a for loop
        for (m=0, d=0.0;m*d<30;m++,d+=.02){
                System.out.printf("m*d=%.2f%n",m*d);
        }
    }
}


2. Nested loops : Convert the While loop version of the Multiplication table to a For loop example.
3. continue,break, System.exit(0) .... For reading in numbers, allow negative numbers to be treated differently. i.e. use break, continue, and exit for negative numbers
4. Do the random number guessing program where you have a limit on the number of guesses.
5. Modify the guessing program where you ask the user if he wants to play again.
6. Note that I have a few of the book's "Self-Test" examples for you to practice on.


// Convert the following While loop example to a For Loop example.

public class Multiplication {


    public static void main(String[] args) {


        int labelCol =1;
        System.out.print( "    ");
        while (labelCol <= 12)
        {
            System.out.printf("%4d", labelCol);
            labelCol +=1;
        }
        System.out.println();
        String separator = "----";
        labelCol =1;
        System.out.print( "    ");
        while(labelCol <= 12)
        {
            System.out.printf("%4s", separator);
            labelCol+= 1;
        }
        System.out.println();

        int row =1;
        int col =1;

        while (row <= 12)
        {
            System.out.printf("%2d |", row);
            while (col <= 12)
            {
                System.out.printf("%4d", row * col);
                col +=1;
            }
            System.out.println();
            col = 1;
            row += 1;
        }

    }

}



 // Converted to use For loops

public class Multiplication {


    public static void main(String[] args) {


        System.out.print( "    ");
        for (int labelCol =1; labelCol <= 12; labelCol++)
        {
            System.out.printf("%4d", labelCol);
        }
        System.out.println();
        String separator = "----";

        System.out.print( "    ");
        for (int labelCol =1; labelCol <= 12; labelCol++)
        {
            System.out.printf("%4s", separator);
        }
        System.out.println();



        for (int row=1; row <= 12; row++)
        {
            System.out.printf("%2d |", row);
            for ( int col =1; col <= 12; col++)
            {
                System.out.printf("%4d", row * col);
            }
            System.out.println();

        }

    }

}



import java.util.Scanner;


public class Miscellaneous {


    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        int count =0;
        int total =0;

        for (int i=1; i <=5; i++)
        {
            System.out.println("Enter a number:");
            int x = keyboard.nextInt();
            if ( x < 0)
            {
                System.out.println("Bad input ... aborting last value");
                continue;
            }
            count +=1;
            total += x;
        }


    /*    Code using a break
        for (int i=1; i <=5; i++)
        {
            System.out.println("Enter a number:");
            int x = keyboard.nextInt();
            if ( x < 0)
            {
                System.out.println("Bad input ... aborting loop");
                break;
            }
            count +=1;
            total += x;
        }
        */



        /*    Code using System.exit(int)
        for (int i=1; i <=5; i++)
        {
            System.out.println("Enter a number:");
            int x = keyboard.nextInt();
            if ( x < 0)
            {
                System.out.println("Bad input ... aborting");
                System.exit(0);
            }
            count +=1;
            total += x;
        }
        */

        if (count >0)
            System.out.println("Average ="+ total/count);

    }

}



// We will change the while loop to a for loop to limit the number of attempts
// We will also wrap this with a while loop to let the user play again.

import java.util.Scanner;


public class GuessingGame {


    public static void main(String[] args) {
        int guessNumber = (int)(1 + 100*Math.random());

        Scanner keyboard = new Scanner(System.in);
        int userGuess;

        do
        {
            System.out.println("Guess the number: ");
            userGuess = keyboard.nextInt();

            if (userGuess > guessNumber)
            {
                System.out.println("Too High");
            }
            else if (userGuess < guessNumber)
                System.out.println("Too Low");

        } while (userGuess != guessNumber);

        System.out.println("Congratulations you guessed the number");

    }

}



// Added a limit of 5 tries and a retry do... while around the whole program

import java.util.Scanner;


public class GuessingGame {


    public static void main(String[] args) {

        int guessLimit = 5;
        char cResponse;
        String response;

        do
        {

            int guessNumber = (int)(1 + 100*Math.random());
            boolean success = false;

            Scanner keyboard = new Scanner(System.in);
            int userGuess;

            for (int i =1; i <= guessLimit; i++)
            {
                System.out.println("Guess the number: ");
                userGuess = keyboard.nextInt();

                if (userGuess > guessNumber)
                {
                    System.out.println("Too High");
                }
                else if (userGuess < guessNumber)
                    System.out.println("Too Low");
                else // Must be equal to guessNumber
                {
                    success = true;
                    break;
                }

            }

            if (success)
                System.out.println("Congratulations you guessed the number");
            else
                System.out.println("Too bad you ran out tries");

            System.out.println("Do you want to play again (y/n)?");
            response = keyboard.next();
        } while (response.equals("y"));   // Approach 2
    //        cResponse = response.charAt(0);   //Approach 1
    //    } while(cResponse == 'y');            //Approach 1

    }

}


Self Test Exercises

1. What is the output of the following;


  for (int count =1; count < 5; count++)
      System.out.println(((2*count) + " ");


2. What is the output of the following:


  for (int =10; n > 0; n = n-2)
      System.out.println("Hello " +n);


3. What is the output of the following:


  for (double sample =2; sample > 0; sample = sample -0.5)
      System.out.println(sample + " ");


4. Rewrite the following for statement as a while loop (and possibly some additional statements):


	int n;
	for (n=10; n > 0; n = n-2)
	    system.out.println("Hello " +n);
	

5. Predict the output of the following nested loops:


  int n,m;
  for (n =1; n <= 10; n++)
      for (m=10; m >=1; m--)
	        System.out.println(n + " times " + m + " = " + n*m);


6. What is the output of the following:


  int number =10;
  while (number > 0)
  {
      number = number -2;
      if (number == 4) break;
      System.out.println(number);
  }
  System.out.println("The end.");


7. What is the output of the following:


  int number =10;
  while (number > 0)
  {
      number = number -2;
      if (number == 4) continue;
      System.out.println(number);
  }
  System.out.println("The end.");


Java Practice(JPHH):

1. (1 points) Create a Program that contains a "for" loop which prints out the numbers 1 through 8. Your output should be:
1
2
3
4
5
6
7
8
2. (2 points) Create a Program that contains a "for" loop that creates the following output :
1
3
5
7

HINT: increment by 2 inside the for loop.
3. (2 points) How many lines of output are created with the following program:


public class ForLoop3 {

    public static void main(String[] args) {
        for (int i=0; i < 8; i++);
            System.out.println("Hi");
    }
}


Why doesn't it work the way you would expect (i.e. 8 lines of output)? Fix it and run it again.
4. (2 points) Create a program that contains a for loop that looks like:
for (int counter=1; counter<=8; counter++)

Create an integer named "total" before the for loop that is initialized to 0.
For each iteration of the "for" loop add the variable "counter" to "total" and print out the new value of "total". Your output should look like:
1
3
6
10
15
21
28
36
5. (3 points) Create a program that generates the following output:
0:0 0:1 0:2 0:3
1:0 1:1 1:2 1:3
2:0 2:1 2:2 2:3

Hint:
Create an outer for loop that has an index named "row" that goes from 0, 1, 2
Create an inner for loop that has an index named "col" that goes from 0, 1, 2, 3
Each time through the inner loop, execute the statement:

System.out.print(row+":"+col +" ");

After the inner loop finishes, execute

System.out.println();

to output a new line

Last Modified: December 23, 2014 3:30 PM