Loops 27.0
7.1Concept of Sentinel in Programming
Sentinel
- Essentially, it is a delimiter that is used to specify the endpoint of a particular type of input data.
- It is a delimiter that is not included in the permissible set of input data.
- It could either be a numeral (e.g. -1, 0, 2, etc.); an alphabet (e.g. A, a, z, Z, etc.); a special character (e.g. $, #, @, etc.); a
String
(e.g. "stop", "end", "halt", etc.); and so on.
Caption: Numeric sentinel (of -1) in an input of numbers
Caption: Alphabetic sentinel (of Z) in an input of alphabets
Caption: Special-Character sentinel (of $) in an input of numbers
Caption: String
sentinel (of "end") in an input of alphabets
Exercise 1: Consider the following code snippet, which employs a numeric sentinel, with respect to (numeric) input requests from a user.
/**
* @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
* @course ProgrammingLessons (proglessons).
* @title Loops 2.
* @author Dr. Bonaventure Chidube Molokwu.
*/
import java.util.Scanner;
public class Loops2 {
public static void main(String[] args) {
Scanner usrInput = new Scanner(System.in);
double sum = 0.0d, salary = 0.0d;
do {
System.out.print("Enter salary amount: ");
salary = usrInput.nextDouble();
if (salary != -1) { //Sentinel = -1
sum = sum + salary;
}
}
while (salary != -1); //Sentinel = -1
System.out.printf("Total salary amounts to: %.2f", sum);
usrInput.close();
}
}
Code Snippet: Exercise 1 - Applying a numeric sentinel with respect to user's inputs
Exercise 2: Consider the code snippet below; this employs a special-character sentinel with respect to input requests from a user.
/**
* @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
* @course ProgrammingLessons (proglessons).
* @title Loops 2.
* @author Dr. Bonaventure Chidube Molokwu.
*/
import java.util.Scanner;
public class Loops2 {
public static void main(String[] args) {
Scanner usrInput = new Scanner(System.in);
char inChar;
do {
System.out.print("Enter an alphabet: ");
inChar = usrInput.next().charAt(0);
if (inChar != '$') { //Sentinel = '$'
System.out.printf("Input character is: %s%n", inChar);
}
}
while (inChar != '$'); //Sentinel = '$'
usrInput.close();
}
}
Code Snippet: Exercise 2 - Applying a special-character sentinel with respect to user's inputs
Exercise 3: The code snippet below employs a
String
sentinel with respect to (textual) input requests from a user.
/**
* @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
* @course ProgrammingLessons (proglessons).
* @title Loops 2.
* @author Dr. Bonaventure Chidube Molokwu.
*/
import java.util.Scanner;
public class Loops2 {
public static void main(String[] args) {
Scanner usrInput = new Scanner(System.in);
int id = 0;
String studName;
do {
System.out.print("Enter student's name: ");
studName = usrInput.nextLine();
if (!studName.equals("end")) { //Sentinel = "end"
System.out.printf("%3d: %s%n", ++id, studName);
}
}
while (studName.equals("end") == false); //Sentinel = "end"
usrInput.close();
}
}
Code Snippet: Exercise 3 - Applying a String
sentinel with respect to user's inputs
Boolean Sentinel
boolean
values can be employed as a sentinels too.
- Essentially, this implies using variables that resolve to either
true
or false
values.
- In this regard, conditional checks are performed during program execution to determine if a variable resolves to either
true
or false
.
- For example,
if (!booleanValue) {...}
is equivalent to this conditional check: if (booleanValue == false) {...}
- Also,
if (booleanValue) {...}
is equivalent to testing or checking: if (booleanValue == true) {...}
/**
* @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
* @course ProgrammingLessons (proglessons).
* @title Loops 2.
* @author Dr. Bonaventure Chidube Molokwu.
*/
import java.util.Scanner;
public class Loops2 {
public static void main(String[] args) {
Scanner usrInput = new Scanner(System.in);
System.out.println("Enter numeric values, or -1 to finish:");
boolean finish = false;
double value;
while (!finish) { //EQUIVALENT TO: while (finish == false)
value = usrInput.nextDouble();
if (value == -1) {
finish = true;
}
else {
System.out.println("Input value is: " + value);
}
}
usrInput.close();
}
}
Code Snippet: Boolean sentinel. (!finish) ≡ (finish == false)
/**
* @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
* @course ProgrammingLessons (proglessons).
* @title Loops 2.
* @author Dr. Bonaventure Chidube Molokwu.
*/
import java.util.Scanner;
public class Loops2 {
public static void main(String[] args) {
Scanner usrInput = new Scanner(System.in);
System.out.println("Enter numeric values, or -1 to finish:");
boolean finish = false;
double value;
while (finish) { //EQUIVALENT TO: while (finish == true)
value = usrInput.nextDouble();
if (value == -1) {
finish = true;
}
else {
System.out.println("Input value is: " + value);
}
}
usrInput.close();
}
}
Code Snippet: Boolean sentinel. (finish) ≡ (finish == true). Also, note that control does not flow into the while {}
loop construct.
Class Work:
Study the following blocks of code snippet with reference to every line of code contained herein. Thus, answer the question(s) stated in the caption of each code snippet.
/**
* @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
* @course ProgrammingLessons (proglessons).
* @title Loops 2.
* @author Dr. Bonaventure Chidube Molokwu.
*/
import java.util.Scanner;
public class Loops2 {
public static void main(String[] args) {
Scanner usrInput = new Scanner(System.in);
String txtIn = "";
do {
System.out.print("\nKindly enter a line of text, or enter -1 to exit: ");
txtIn = usrInput.nextLine().trim();
int cnt = 1;
for (int i=0; i<txtIn.length(); ++i) {
if (txtIn.charAt(i) == ' ') {
cnt++;
}
}
if (txtIn.equals("-1") == false) {
System.out.println("Input text contains: " + cnt + " word(s).");
}
}
while (txtIn.equals("-1") == false);
usrInput.close();
}
}
Algorithm-Interpretation Activity 1: What does this program do; and what is/are the expected output(s) of this program?
/**
* @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
* @course ProgrammingLessons (proglessons).
* @title Loops 2.
* @author Dr. Bonaventure Chidube Molokwu.
*/
import java.util.Scanner;
public class Loops2 {
public static void main(String[] args) {
Scanner usrInput = new Scanner(System.in);
double total = 0.0;
int count = 0;
while (usrInput.hasNextDouble()) {
double input = usrInput.nextDouble();
total = total + input;
++count;
}
double average = 0.0;
if (count > 0) {
average = total / count;
System.out.println("Average is: " + average);
}
usrInput.close();
}
}
Algorithm-Interpretation Activity 2: What does this code snippet do; and when does it terminate?
/**
* @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
* @course ProgrammingLessons (proglessons).
* @title Loops 2.
* @author Dr. Bonaventure Chidube Molokwu.
*/
public class Loops2 {
public static void main(String[] args) {
boolean found = false;
String str = "PROG_LESSONS";
int position = 0;
char ch;
while (!found && position < str.length()) {
ch = str.charAt(position);
if (Character.isLowerCase(ch)) {
found = true;
System.out.println(position + "=>" + ch);
}
else {
position++;
}
}
}
}
Algorithm-Interpretation Activity 3: What does this algorithm do? Also, what will be the values of variables: position
and ch
at the end of its execution?
/**
* @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
* @course ProgrammingLessons (proglessons).
* @title Loops 2.
* @author Dr. Bonaventure Chidube Molokwu.
*/
import java.util.Scanner;
public class Loops2 {
public static void main(String[] args) {
Scanner usrInput = new Scanner(System.in);
double total = 0;
while (usrInput.hasNextDouble()) {
double input = usrInput.nextDouble();
if (input > 0) {
total = total + input;
}
}
System.out.println("total = " + total);
usrInput.close();
}
}
Algorithm-Interpretation Activity 4: What does this program do; and when does the execution of this program terminate?
7.2Nested or Cascaded Loop Constructs in Java Programming
Nested Loop
- Basically, this is a programming structure whereby a loop/repetition construct is encapsulated within another loop/repetition construct.
- In this regard, a Nested-Loop construct can possess several (inner) levels of encapsulated loop/repetition constructs.
- Nested loops can be created either with a
while {}
, a for {}
loop, or a do-while {}
loop construct.
- They are usually employed for traversing as well as managing multidimensional data structures such as arrays (2D, 3D, 4D, etc.), lists, etc.
for (int g = 0; g < 1; g++) { //outermost loop
System.out.println("outermost loop (4)");
for (int h = 0; h < 1; h++) { //outer loop
System.out.println(" outer loop (3)");
for (int i = 0; i < 1; i++) { //inner loop
System.out.println(" inner loop (2)");
for (int j = 0; j < 1; j++) { //innermost loop
System.out.println(" innermost loop (1)");
}
}
}
}
Pseudocode: Algorithm of a 4-level nested for {}
loop construct
Caption: Multidimensional data structures (2-Dimensional and 3-Dimensional arrays)
/**
* @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
* @course ProgrammingLessons (proglessons).
* @title Loops 2.
* @author Dr. Bonaventure Chidube Molokwu.
*/
public class Loops2 {
public static void main(String[] args) {
System.out.println("-----------------------------------------");
for (int g = 1; g <= 5; g++) { //outermost loop
System.out.print("|");
for (int h = 1; h <= 5; h++) { //innermost loop
System.out.print(" (" + g + "," + h + ") |");
}
System.out.println("\n-----------------------------------------");
}
}
}
Code Snippet: A program comprising a 2-level nested for {}
loop construct for populating and displaying a data matrix (2D array)
break
keyword in Nested Loop(s)
- This a command word in Java which is reserved for implementing a termination and break-out with respect to the current ith iteration in a loop construct.
- In this regard, flow of control breaks out of the currently executing loop construct and proceeds to the next line of instruction immediately after the (terminated) loop construct.
- For example: upon encountering the
break
keyword within the innermost loop of a nested loop construct, the flow of control terminates the entire innermost loop and jumps out to the line of code succeeding the terminated loop construct (and within the immediate outer loop).
/**
* @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
* @course ProgrammingLessons (proglessons).
* @title Loops 2.
* @author Dr. Bonaventure Chidube Molokwu.
*/
public class Loops2 {
public static void main(String[] args) {
for (int i = 1; i <= 4; i++) { //outermost loop
for (int j = 1; j <= 6; j++) { //innermost loop
if (i == j) {
System.out.print("break(" + i + "," + j + ")");
break;
}
else {
System.out.print("*");
}
}
//Upon encountering a "break", flow of control jumps out to here
System.out.print("...ending entire innermost loop");
System.out.println(); //New Line
}
}
}
Code Snippet: A program employing the break
keyword within a nested for {}
loop construct
continue
keyword in Loop(s)
- This a command word in Java which is reserved for implementing a skip and jump-over with respect to the current ith iteration in a loop construct.
- In this regard, flow of control only skips the entire current iteration and jumps over to the next iteration with reference to the currently executing loop construct.
- For example: upon encountering the
continue
keyword in the ith iteration of a loop construct, the flow of control simply skips every line and/or block of code thereafter, and proceeds to the next (i+1)th iteration with reference to the currently executing loop construct.
/**
* @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
* @course ProgrammingLessons (proglessons).
* @title Loops 2.
* @author Dr. Bonaventure Chidube Molokwu.
*/
public class Loops2 {
public static void main(String[] args) {
for (int i = 1; i <= 4; i++) { //outermost loop
for (int j = 1; j <= 6; j++) { //innermost loop <-- Upon encountering a "continue", flow of control jumps out to here
if (i == j) {
System.out.println("continue(" + i + "," + j + ")");
continue;
/*
* System.out.println("Flow of control never reaches this line...1");
* System.out.println("Flow of control never reaches this line...2");
*/
}
else {
System.out.print("...continuing innermost loop");
}
System.out.println(" " + j); //Skipped ONLY upon encountering a "continue"
}
System.out.println(); //New Line
}
}
}
Code Snippet: A program employing the continue
keyword within a nested for {}
loop construct
7.3Random-Number Generation in Java Programming
In programming, there may exist scenarios where we do want to randomly generate number(s) and use these for some real-world tasks such as game development, password generation, cryptography, etc. To this end, Java does provide two (2) basic approaches for accomplishing the goal of random number generation.
Thus, this involves using either of the following, viz:
- The
random()
method which is already predefined within the Math {}
class block or segment.
- The
Random {}
class, and with reference to its several methods (nextInt()
, nextFloat()
, nextDouble()
, etc.) already predefined therein.
- With regard to both (1) and (2) above, simplistically and within the base case, each of them generates a random number,
x
, which lies within these boundaries, viz: 0.0 ≤ x < 1.0
.
- Additionally, we can always generate random numbers outside the aforementioned boundaries, stated in (3) above, via arithmetic manipulations with reference to the base-case boundaries (
0.0 ≤ x < 1.0
).
Random-Number generation using the Math.random()
method
/**
* @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
* @course ProgrammingLessons (proglessons).
* @title Loops 2.
* @author Dr. Bonaventure Chidube Molokwu.
*/
public class Loops2 {
public static void main(String[] args) {
for (int i = 1; i <= 6; i++) {
double randNumValue;
randNumValue = Math.random() * 10;
//Math.random() * 10 = (0.0 ≤ x < 1.0) * 10
//Random-Number range = 0.0 ≤ x < 10.0
System.out.println("Random Number generated is: " + randNumValue);
}
}
}
Code Snippet 1: A program on random-number generation via Math.random()
method
/**
* @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
* @course ProgrammingLessons (proglessons).
* @title Loops 2.
* @author Dr. Bonaventure Chidube Molokwu.
*/
public class Loops2 {
public static void main(String[] args) {
for (int i = 1; i <= 6; i++) {
double randNumValue;
randNumValue = (Math.random() * 10) + 2;
//(Math.random() * 10) + 2 = (0.0 ≤ x < 1.0) * 10
// = (0.0 ≤ x < 10.0) + 2
//Random-Number range = 2.0 ≤ x < 12.0
System.out.println("Random Number generated is: " + randNumValue);
}
}
}
Code Snippet 2: A program on random-number generation via Math.random()
method
/**
* @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
* @course ProgrammingLessons (proglessons).
* @title Loops 2.
* @author Dr. Bonaventure Chidube Molokwu.
*/
public class Loops2 {
public static void main(String[] args) {
for (int i = 1; i <= 6; i++) {
double randNumValue;
randNumValue = Math.floor(Math.random() * 10) + 2;
//Math.floor(Math.random() * 10) + 2 = (0.0 ≤ x < 1.0) * 10
// = Math.floor(0.0 ≤ x < 10.0)
// = (0.0 ≤ x ≤ 9.0) + 2
//Random-Number range = 2.0 ≤ x ≤ 11.0
System.out.println("Random Number generated is: " + randNumValue);
}
}
}
Code Snippet 3: A program on random-number generation via Math.random()
method
/**
* @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
* @course ProgrammingLessons (proglessons).
* @title Loops 2.
* @author Dr. Bonaventure Chidube Molokwu.
*/
public class Loops2 {
public static void main(String[] args) {
for (int i = 1; i <= 6; i++) {
double randNumValue;
randNumValue = Math.ceil(Math.random() * 10) + 2;
//Math.ceil(Math.random() * 10) + 2 = (0.0 ≤ x < 1.0) * 10
// = Math.ceil(0.0 ≤ x < 10.0)
// = (1.0 ≤ x ≤ 10.0) + 2
//Random-Number range = 3.0 ≤ x ≤ 12.0
System.out.println("Random Number generated is: " + randNumValue);
}
}
}
Code Snippet 4: A program on random-number generation via Math.random()
method
Random-Number generation using methods of the Random {}
class block
/**
* @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
* @course ProgrammingLessons (proglessons).
* @title Loops 2.
* @author Dr. Bonaventure Chidube Molokwu.
*/
import java.util.Random;
public class Loops2 {
public static void main(String[] args) {
Random randomInstance = new Random();
for (int i = 1; i <= 6; i++) {
double randNumValue;
randNumValue = randomInstance.nextDouble();
//randomInstance.nextDouble() range = 0.0 ≤ x < 1.0
System.out.println("Random Number generated is: " + randNumValue);
}
}
}
Code Snippet 1: A program on random-number generation via methods of the Random {}
class block
/**
* @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
* @course ProgrammingLessons (proglessons).
* @title Loops 2.
* @author Dr. Bonaventure Chidube Molokwu.
*/
import java.util.Random;
public class Loops2 {
public static void main(String[] args) {
Random randomInstance = new Random();
for (int i = 1; i <= 6; i++) {
double randNumValue;
randNumValue = randomInstance.nextDouble(10);
//randomInstance.nextDouble(10) range = 0.0 ≤ x < 10.0
System.out.println("Random Number generated is: " + randNumValue);
}
}
}
Code Snippet 2: A program on random-number generation via methods of the Random {}
class block
/**
* @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
* @course ProgrammingLessons (proglessons).
* @title Loops 2.
* @author Dr. Bonaventure Chidube Molokwu.
*/
import java.util.Random;
public class Loops2 {
public static void main(String[] args) {
Random randomInstance = new Random();
for (int i = 1; i <= 6; i++) {
double randNumValue;
randNumValue = randomInstance.nextInt(2, 8);
//randomInstance.nextInt(2, 8) range = 2 ≤ x < 8
System.out.println("Random Number generated is: " + randNumValue);
}
}
}
Code Snippet 3: A program on random-number generation via methods of the Random {}
class block
7.4Practice Exercise
-
Consider the code snippet below, how many times will the inner loop be executed; and what will be the exact screen outputs. Also, state the final (internal) values for the variables:
g
and h
.
/**
* @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
* @course ProgrammingLessons (proglessons).
* @title Loops 2.
* @author Dr. Bonaventure Chidube Molokwu.
*/
public class Loops2 {
public static void main(String[] args) {
for (int g = 0; g < 6; g++) { //outer loop
for (int h = 1; h <= 3; ++h) { //inner loop
System.out.print("(" + g + "," + h + ")");
}
System.out.println();
}
}
}
-
Dry-run the following block of code, via hand tracing, and determine as well as specify the exact screen output(s).
/**
* @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
* @course ProgrammingLessons (proglessons).
* @title Loops 2.
* @author Dr. Bonaventure Chidube Molokwu.
*/
public class Loops2 {
public static void main(String[] args) {
for (int g = 0, h = 0; g < 6; g++)
{
while (h <= g)
{
System.out.print("(" + g + "," + h + ")");
h++;
}
System.out.println();
}
}
}
-
Dry-run the following block of code, via hand tracing, and determine as well as specify the exact screen output(s).
/**
* @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
* @course ProgrammingLessons (proglessons).
* @title Loops 2.
* @author Dr. Bonaventure Chidube Molokwu.
*/
public class Loops2 {
public static void main(String[] args) {
for (int i = 0, j = 0; i < 6; i++)
{
while (j < i);
{
System.out.print("(" + i + "," + j + ")");
j++;
}
System.out.println();
}
}
}
-
Given the code snippet below; dry-run via hand tracing and specify the exact screen output(s).
/**
* @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
* @course ProgrammingLessons (proglessons).
* @title Loops 2.
* @author Dr. Bonaventure Chidube Molokwu.
*/
public class Loops2 {
public static void main(String[] args) {
for (int i = 5; i < 10; i++) {
for (int j = 0; j < i; j++) {
System.out.print("{" + i + "," + j + "} ");
}
System.out.println();
}
}
}
-
Consider the code snippet below, if the code compiles then what is the expected output; otherwise, state the expected error.
/**
* @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
* @course ProgrammingLessons (proglessons).
* @title Loops 2.
* @author Dr. Bonaventure Chidube Molokwu.
*/
public class Loops2 {
public static void main(String[] args) {
for (int i = 5; i < 10; i++) {
for (int j = 0; j < i; j++) {
System.out.print("{" + i + "," + j + "} ");
}
System.out.println(j * 2);
}
}
}
-
Given the code snippet below with regard to random-number generation, dry-run via hand tracing and specify the boundaries of the random numbers that will be rendered using this block of code.
/**
* @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
* @course ProgrammingLessons (proglessons).
* @title Loops 2.
* @author Dr. Bonaventure Chidube Molokwu.
*/
public class Loops2 {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
double randNumValue;
randNumValue = Math.ceil(Math.random() / 2) + 2;
System.out.println("Random Number generated is: " + randNumValue);
}
}
}
-
Given the code snippet below with regard to random-number generation, dry-run via hand tracing and specify the boundaries of the random numbers that will be rendered using this block of code.
/**
* @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
* @course ProgrammingLessons (proglessons).
* @title Loops 2.
* @author Dr. Bonaventure Chidube Molokwu.
*/
public class Loops2 {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
double randNumValue;
randNumValue = Math.round(Math.random() * 3) - 0.5;
System.out.println("Random Number generated is: " + randNumValue);
}
}
}
-
Consider the code snippet below, dry-run via hand tracing and determine the expected output with reference to every line of code contained herewith.
/**
* @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
* @course ProgrammingLessons (proglessons).
* @title Loops 2.
* @author Dr. Bonaventure Chidube Molokwu.
*/
public class Loops2 {
public static void main(String[] args) {
int i = 1;
boolean flag = false;
while (!flag) {
if (i++ % 3 == 0) {
flag = true;
}
else {
System.out.println("i = " + i);
}
}
}
}
-
Consider the code snippet below, dry-run via hand tracing and determine the expected output with reference to every line of code contained herewith.
/**
* @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
* @course ProgrammingLessons (proglessons).
* @title Loops 2.
* @author Dr. Bonaventure Chidube Molokwu.
*/
public class Loops2 {
public static void main(String[] args) {
int i = 0;
boolean flag = false;
while (flag || (i++ % 2 == 0)) {
System.out.println("i = " + i);
if (i % 3 == 0) {
flag = true;
break;
}
i++;
}
}
}
- TRUE or FALSE: Upon encountering the
break
keyword within the ith iteration of a loop construct, it simply causes flow of control to skip and proceed to the next (i+1)th iteration within the same loop construct?
- TRUE or FALSE: Generally, in programming, a
boolean
variable can be employed as a sentinel?