Ask Java Expert


Home >> Java

explored the world of loops we have accepted the three most primary forms of loops: the while loop, the do...while loop (even though Python does not use this loop), and the for loop. The for loop has approximately three primary implementations that will be reviewed in the next class period. To finish the chapter formally we will discuss the sentinel-controlled loop and the nested loop.

The Sentinel-Controlled Loop

Loops by themselves are indeterminate except for counting loops. That simply means that we will not know how many times the loop will execute. Sometimes there will be a programming situation in which we need the user to input as many data entries and then enter a special value to signify the end of the input session. The special value that is used is known as the sentinel. The goal of the loop is to execute the loop until that one particular sentinel value is executed. Our first approach would be to program like this.

print("Welcome to this accumulating program")

SENTINEL = -555

entry = 0
total = 0

while entry != SENTINEL:
entry = int(input("Enter a number (Enter -555 to quit): ")
total += entry

print("The total of the numbers entered: ", total)

If you were to program this and execute this, you would see one small problem. Even though it is syntactically correct (to my knowledge), the total will always be short by 555. Why? The sentinel value will have to be accounted for and added back to the total. In my estimation and that of programming experts everywhere, this is not a great programming practice. This also defeats the purpose of using it effectively.

The best way to use sentinel-controlled loops is to have the sentinel on be concerned with stopping the loop but not being a part of the data. In fact (in type disciplined languages) the sentinel should be of the data type but not a part of the data set. Since, for this course, we use Python, we can get away with even a string for the sentinel [even though that is highly unsafe]. Let's revise the above code to understand what should take place.

print("Welcome to this accumulating program")

SENTINEL = -555

total = 0
entry = int(input("Enter a number (Enter -555 to quit): ")

while entry != SENTINEL:
total += entry

entry = int(input("Enter another number (Enter -555to quit): ")

print ("The total of the numbers entered: ", total)

This programming approach is a much more disciplined approach. First the code requires the user to input the first entry before the loop. This is known as the priming input. If the first entry is the sentinel, the loop will not execute, otherwise, the first entry is processed and then all remaining inputs are required inside the loop. I call this the looping input. In this program the limitation is that -555 (or whatever you set the sentinel to) cannot be processed as data. It ends the loop. It is best when choosing a sentinel to pick a value that is far from the data set.

Your task:

Take this code and keep count of how many entries (inputs the user makes). Without trying to use arrays [since I know that you will search Google], display the average of the entries, the highest value entered and the lowest value entered.

Nested Loops

Loops are conditional structures that test a condition, execute a set of statements and then recheck the condition to see if it still exists. You are to permitted to nest loops like you can nest decisions but you have to be aware that there is a different outcome when you nest loops. Since a loop is inside another loop, the complete execution of the inner has to occur before the iteration of the outer loop. Think about minutes and seconds. We have to count 60 seconds before we can get one minute. We have to count another 60 seconds to get to two minutes. After 60 minute iterations we have accomplished an hour iteration.

for hours in range (24):
for minutes in range (60):
for seconds in range (60):
print (hours, " : ", minutes, " : ", seconds)

Now write this program and watch the execution. You should be impressed at how many executions can occur in just four lines of code. In fact that was 24 * 60 * 60 -> 86,400 executions. WOW! You should also notice how the seconds increase through all its executions before one minute iteration.

Your next task:

When I was younger we used to have composition note books that had multiplication tables that ran from 1 through 12. So you would see:

1
-----------
1 x 1 = 1
1 x 2 = 2
.
.
.
1 x 12 = 12

2
-----------
2 x 1 = 2
2 x 2 = 4
.
.
.
2 x 12 = 24
.
.
.
12
--------------
12 x 1 = 12
12 x 2 = 24
.
.
.

12 x 12 = 144

You are to use two nested loops to output the multiplication like the one printed above from 1 to 12 (both multiplicand and multiplier). Try to get your format to be like the output as well.

 

 

Java, Programming

  • Category:- Java
  • Reference No.:- M9455066

Have any Question?


Related Questions in Java

Chatbotscreate a small networked chat application that is

Chatbots Create a small, networked chat application that is populated by bots. Introduction On an old server park, filled with applications from the early days of the internet, a few servers still run one of the earliest ...

Assignment taskwrite a java console application that allows

Assignment task Write a java console application that allows the user to read, validate, store, display, sort and search data such as flight departure city (String), flight number (integer), flight distance (integer), fl ...

Assignment game prototypeoverviewfor this assessment task

Assignment: Game Prototype Overview For this assessment task you are expected to construct a prototype level/area as a "proof of concept" for the game that you have designed in Assignment 1. The prototype should function ...

Assignment taskwrite a java console application that allows

Assignment task Write a java console application that allows the user to read, validate, store, display, sort and search data such as flight departure city (String), flight number (integer), flight distance (integer), fl ...

In relation to javaa what is constructor the purpose of

(In relation to Java) A. What is constructor? the purpose of default constructor? B. How do you get a copy of the object but not the reference of the object? C. What are static variables and instance variables? D. Compar ...

Project descriptionwrite a java program to traverse a

Project Description: Write a java program to traverse a directory structure (DirWalker.java) of csv files that contain csv files with customer info. A simple sample in provided in with the sample code but you MUST will r ...

Fundamentals of operating systems and java

Fundamentals of Operating Systems and Java Programming Purpose of the assessment (with ULO Mapping) This assignment assesses the following Unit Learning Outcomes; students should be able to demonstrate their achievements ...

Assessment -java program using array of Assessment -JAVA Program using array of objects

Assessment -JAVA Program using array of objects Objectives This assessment item relates to the course learning outcomes as stated in the Unit Profile. Details For this assignment, you are required to develop a Windowed G ...

Applied software engineering assignment 1 -learning

Applied Software Engineering Assignment 1 - Learning outcomes - 1. Understand the notion of software engineering and why it is important. 2. Analyse the risk factors associated with phases of the software development lif ...

Retail price calculatorwrite a java program that asks the

Retail Price Calculator Write a JAVA program that asks the user to enter an item's wholesale cost and its markup percentage. It should then display the item's retail price. For example: (If an item's wholesale cost is 5. ...

  • 4,153,160 Questions Asked
  • 13,132 Experts
  • 2,558,936 Questions Answered

Ask Experts for help!!

Looking for Assignment Help?

Start excelling in your Courses, Get help with Assignment

Write us your full requirement for evaluation and you will receive response within 20 minutes turnaround time.

Ask Now Help with Problems, Get a Best Answer

Why might a bank avoid the use of interest rate swaps even

Why might a bank avoid the use of interest rate swaps, even when the institution is exposed to significant interest rate

Describe the difference between zero coupon bonds and

Describe the difference between zero coupon bonds and coupon bonds. Under what conditions will a coupon bond sell at a p

Compute the present value of an annuity of 880 per year

Compute the present value of an annuity of $ 880 per year for 16 years, given a discount rate of 6 percent per annum. As

Compute the present value of an 1150 payment made in ten

Compute the present value of an $1,150 payment made in ten years when the discount rate is 12 percent. (Do not round int

Compute the present value of an annuity of 699 per year

Compute the present value of an annuity of $ 699 per year for 19 years, given a discount rate of 6 percent per annum. As