Students will be able to:
Review the important terms.
Repeating a task multiple times is done using loops in Java. There are three different types of loops:
For loops should be used when we know how many times a task is to be repeated. These are also called as counting loops, as they count the number of times the loop runs. It is useful to know that a for loop can be written as a while loop, but vice-versa is not true.
More details about for loop syntax and examples
While loops are used to repeat actions when we do not know how many times a task is to be repeated. In such cases, we should at least know the signal that indicates when the loop should end. For example: Your instructor asks you to clap your hands until (s)he says "STOP". In this case, you won’t know how many times to clap, but you know that the signal to stop clapping is "STOP".
Syntax of the while loop and an example
boolean keepLooping = true; double input; Scanner keyboard = new Scanner(System.in); while ( keepLooping ){ System.out.print("Enter a positive value < 100: "); input = keyboard.nextDouble(); if (0 < input && input < 100){ keepLooping = false; } }
In the above code example, the loop runs as long as the flag (keepLooping) is true and ends when the flag becomes false. The flag becomes false only when the input provided by the user meets the specifications.
int sum = 0; Scanner keyboard = new Scanner(System.in); System.out.print("Enter an integer: "); while (keyboard.hasNextInt()){ int input = keyboard.nextInt(); sum = sum + input; } System.out.println(“Sum of integers is “ + sum);
In the above example, the loop uses the hasNextInt() method to check if the next value provided by the user is int. It is important to note that this method does not actually read the value but instead returns true, if the value is int and false otherwise. If the hasNextInt() method returns true, then the nextInt() method reads the value and updates the sum. The loop ends when the user enters a non-integer value to indicate that they do not want to enter any more numbers.
This code also demonstrates a common algorithm used to calculate the sum of multiple numbers. hasNextLine(), hasNextDouble() and hasNextBoolean() are other methods that can be used in this strategy depending on the type of input expected.
double max = keyboard.nextDouble(); while(keyboard.hasNextDouble()){ double newNumber = keyboard.nextDouble(); if(newNumber > max){ max = newNumber; } } System.out.println(“Maximum number is “ + max);
This example uses the hasNext…() method to control the loop. It starts with the assumption that the first value is max. Then compares each new value to the max and updates max if the new value is greater than the current max.
All of the examples shown in this section are examples of user- controlled loops. The user decides when the loop ends.
Loops can be used to generate a sequence of numbers, such as a sequence of the first 10 prime numbers.
Do-while loops are similar to while loops, with one difference. The condition of a do-while loop is checked on exit. This ensures that a do-while loop will run at least once.
A comparison of different types of loops is discussed on lynda.com videos “Comparing Loops” and “Comparing Different Types of Loops”.
Two keywords, break and continue can be used to change the flow of a loop in between if needed. The keyword break allows to break from a loop and exit it. The keyword continue allows to move on to the next iteration.
When one loop is placed inside the body of another loop, we have a nested loop. In the following example, a nested loop is used to create a table of "*".
for(int row = 1; row <= 4; row++){ for(int col = 1; col <= 5; col++){ System.out.print("*"); } System.out.println(); }
The outer loop runs 4 times and represents 4 rows of the table. For each value of row, the inner loop runs 5 times, generating 5 columns of "*". Such 5 columns are generated 4 times. Result looks as below.
***** ***** ***** *****
As you see in the Step-by-Step Animation, notice both the output and the changing value of variables.
Refer to MathBits for a simple example demonstrating how nested loops work.
This youtube video explains the concept of nested loops.
Write a program that prompts the user for an integer and displays if the provided integer is a prime number or not. A prime number is a number that is divisible only by 1 and itself. First few prime numbers are 2, 3, 5, 7, 11, 13 and so on. Sample run is shown below
Sample output for value of 51:
51 is not a prime numberSample output for value of 83:
83 is a prime number
Write a program that prompts the user for student grades, calculates and displays the average grade in the class. The user should enter a character to stop providing values.
Sample out for student grades [20, 40, 55, 17, 67, c]:
Average student grade is 39.8
Write a program that prompts the user for student grades and displays the highest and lowest grades in the class. The user should enter a character to stop providing values.
Sample out for student grades [20, 40, 55, 17, 67, c]:
Highest student grade is 67 Lowest student grade is 17
Write a program that prints the first 30 values in the Fibonacci series. A Fibonacci series begins with 0 and 1. The next number is then found by adding the previous two numbers. The first few numbers in the Fibonacci series are: 0,1,1,2,3,5,8,13 and so on.
Write a program that prompts the user for an integer value. The program should then calculate and print the factorial of the user provided value. Factorial of a number, n, written as n! is calculated as a product of all integers less than or equal to n. 5! = 5*4*3*2*1 = 120. 0! = 1. 1! = 1.
Write a program that accepts an integer from the user and displays the sum of the digits of the provided integer.
Sample output for value 235:
Sum of digits of 235 is 10
Write a program that prompts the user for two String values. The program should then display if string 1 is greater in length than string 2. The program should also display if string 1 appears after string 2 in the lexicographic order or vice versa or if they are the same. Lastly, the program should display a sentence created by combining both the string values.
Sample output for values "I love" and "GGC":
String "I love" is longer than String "GGC" String "GGC" appears before String "I love" in lexicographic order New sentence created is "I love GGC"
Write a program that accepts a String value from the user and displays the reverse of that value.
Sample output for value "Hello, World!":
Reverse of "Hello, World!" is "!dlroW ,olleH"
For additional challenge, determine if the String and its reverse are equal and display a message explaining the result.
Sample output for value "Hello, World!":
String value "Hello, World!" and its reverse "!dlroW ,olleH" are not equal
Write a program that prompts the user for a String value and a character value. The program should then find the last occurrence of the provided character in the provided String and display the corresponding index. If the character is not found in the String, display -1.
Sample output for values "Hello, World!" and 'l':
Last occurrence of character 'l' in "Hello World" is at index 10Sample output for values "Hello, World!" and 'g':
Last occurrence of character 'g' in "Hello World" is at index -1
Write a program that creates the following pattern.
****** ***** **** *** ** *