3 Pages

Lesson%20Set%206

Course: CS 1136, Spring 2008
School: UT Dallas
Rating:
 
 
 
 
 

Word Count: 840

Document Preview

1136 CS Lab 6 While, Do-While and For Loops While Loops If statements allow the program to skip the execution of a statement or choose between one of two statements to be executed based on the value of a Boolean expression. In contrast, the while statement allows a program to continue executing a statement as long as the value of a Boolean expression is true. When the Boolean expression becomes false, the...

Register Now

Unformatted Document Excerpt

Coursehero >> Texas >> UT Dallas >> CS 1136

Course Hero has millions of student submitted documents similar to the one
below including study guides, practice problems, reference materials, practice exams, textbook help and tutor support.

Course Hero has millions of student submitted documents similar to the one below including study guides, practice problems, reference materials, practice exams, textbook help and tutor support.
1136 CS Lab 6 While, Do-While and For Loops While Loops If statements allow the program to skip the execution of a statement or choose between one of two statements to be executed based on the value of a Boolean expression. In contrast, the while statement allows a program to continue executing a statement as long as the value of a Boolean expression is true. When the Boolean expression becomes false, the execution of the program continues with the statement immediately following the while statement. What would happen in this program if value were initialized to 1 instead of 0? Scanner keyboard = new Scanner(System.in()); int value = 0; while (value >= 0) { System.out.println( "Please enter a number."); value = keyboard.nextInt(); } System.out.println("You entered a negative number"); For obvious reasons, the while statement is called a loop. The statements that are being executed within the loop are called the body of the loop. There are three basic steps that must be done for a loop to execute properly. 1. The variables in the expression (value in the above example) must be initialized before the while statement is executed the first time. 2. The variables in the expression must test the status of the expression correctly so that the body of the loop executes when it is supposed to and terminates at the proper time. 3. The variables in the expression must be updated within the loop. If the variables are not updated, the loop never stops executing. This is called an infinite loop. For example, what is the output of the following segment of code? int counter = 0; int sum = 0; while (counter <= 10) { sum = sum + 1; System.out.println("Loop " + counter); } System.out.println("Sum is " + sum); The answer is Loop ... forever. Since counter is never incremented inside the body of the loop, the loop runs forever and the statement following the loop is never executed. You can tell when you're inside an infinite loop because the program never stops running and in this statement because the cout statement inside the loop never prints anything but "Loop 0". If you find yourself in this situation, press <Ctrl> and <Break> (which is at the top right of your keyboard) at the same time. This will "break you out" of your program. Usually, a light blue line will appear somewhere inside your infinite loop after returning to the editor. Other times, the loop will actually crash your computer, so ALWAYS remember to save your program before you run it. Do-While Loops Do-while loops work the same as while loops do-while EXCEPT loops check the Boolean expression after the statements inside the loop are executed for the first time. That means the body of the loop will always be executed at least once. Why is it not necessary to set value equal to zero before the following loop? Scanner keyboard = new Scanner(System.in()); int value; do { System.out.print("Please enter a number: "); value = keyboard.nextInt(); // do you want to print // something for >= 0 // inputs? } while (value >= 0); // this loop continues until a // negative number is entered. System.out.println("You entered a negative number"); For Loops The for loop is designed specifically to allow the loop to run a set number of times. So, if we want to print "Hello World" exactly 10 times, we would use a for loop. For example, for (counter = 1; counter <= 10; counter++) System.out.println("Hello World"); Here, counter, the loop control variable, is initialized to 1. While counter is less than or equal to 10, the block of code is executed, and counter is incremented by 1 (using the post-increment operator). The loop is executed with counter equal to the initial value, the final value and all values in between. Many programmers begin their loop counters at zero (for reasons you will see later). For now, remember that the following loop is equivalent to the previous loop. If you're not sure this is true, count the number of times each loop is executed on paper. for (counter = 0; counter < 10; counter++) System.out.println("Hello World"); Exercise 1: Write a program with the .java file called Lab6_Ex1 that requests the user to enter a positive integer between 1 and 100. The program then should not accept any number outside of the range of 1 to 100 but should issue an error message and reread the number. Display the number accepted by your program on the monitor. Exercise 2: Write a program with the .java file called Lab6_Ex2 that requests the user to enter two integers. The program then should calculate and report the sum of all the integers between and including the two integers. Assume that the smaller integer is entered first. For instance, if the user enters 2 and 9, the program would report that the sum of all the integers from 2 through 9 is 44. Exercise #3 Write a program with the .java called Lab6_Ex3 that asks the user to type in numbers. After each entry, the program reports the cumulative sum of the entries to date. The program terminates when the user enters a zero. Please upload and submit your .java and output files to WEBCT for all exercises.
Find millions of documents on Course Hero - Study Guides, Lecture Notes, Reference Materials, Practice Exams and more. Course Hero has millions of course specific materials providing students with the best way to expand their education.

Below is a small sample set of documents:

UT Dallas - CS - 1136
CS 1136 Lab 7Continuation of loopsCarefully examine the program below and try to work out what occurs in the nested for loops. What do you predict the output will be?public class Lab7_Loops { Public static void main(String [] args) { Scanner keyb
UT Dallas - ECO - 2301
1The Firm and its Objectives: Profit Maximization The optimality (first-order) conditionsWhat is the economic definition of profit? Profit = Total Revenue Total Cost = TR TC What is the fundamental problem for firms? The firm selects its output/
UT Dallas - ECO - 2301
1 WELFARE PROPERTIES OF MARKETS Consumer's Surplus [Money-Metric Utility] The purpose of this handout is to describe how economists measure changes in consumer WELFARE in response to PRICE CHANGES. The problem is: 1. Consumer welfare/satisfaction is
U. Houston - CHEE - 3300
CHAPTER 3THE STRUCTURE OF CRYSTALLINE SOLIDSPROBLEM SOLUTIONS3.1 Atomic structure relates to the number of protons and neutrons in the nucleus of an atom, as well as the number and probability distributions of the constituent electrons. On the
UT Dallas - BIOL - 1318
Exam 3 Review Human Genetics BIOL 1318 March 4, 2008 The exam will consist of 50 multiple choice questions and will cover chapters 10 through 13 of your text Human Genetics. The following topics and points will be addressed on the exam: 1. transcript
UT Dallas - ECO - 2301
Quiz 4 Sample Questions 1. a. b. c. d. Total revenue will increase if price falls and demand is inelastic. falls and demand is elastic. rises and demand is elastic. rises and demand is unitary elastic.P 10 S2. a. b. c. d. e.According to the acco
Arizona - ACCT - 200
ACCT 201 ACCT 201 ACCT 2017Reporting and Analyzing Receivables and InvestmentsChapterUAA ACCT 201 Principles of Financial Accounting Dr. Fred Barbee1ACCT 201Day #1ACCT 201ACCT 201Chapter 7 - Day 1 - AgendaTopicAccounts Receivable
E. Michigan - ENG - 121
Annotated BibliographyIamnext. &quot;College Relationships: Roommate tips for dorm life.&quot;. 2004.Iamnext.30 February 2008. http:/www.iamnext.com/people/rmatedorm.html This source is an overall summary of being a roommate in a dorm. It covers confronting
U. Houston - CHEE - 3300
CHAPTER 6MECHANICAL PROPERTIES OF METALSPROBLEM SOLUTIONS6.1This problem asks that we derive Equations (6.4a) and (6.4b), using mechanics of materials principles. In Figure (a) below is shown a block element of material of cross-sectional are
UCSD - BIBC - 103
Sea Urchin Fertilization How does the sperm penetrate all the way through the egg to get to the nucleus? Signal transduction events occur both outside and inside the plasma membraneStructure of sea urchin egg at fertilizationScanning electron m
U. Houston - CHEE - 3300
CHAPTER 7DISLOCATIONS AND STRENGTHENING MECHANISMSPROBLEM SOLUTIONS7.1 The dislocation density is just the total dislocation length per unit volume of material (in this case per 3 5 -2 cubic millimeters). Thus, the total length in 1000 mm of ma
UCSD - BIBC - 103
Overview of the Central DogmaDNA replication(DNA polymerase)DNATranscription(RNA polymerase)5' UTR 3' UTR ATG stop codonRNARBS(ribosome binding site)Translation(ribosome)Met (first amino acid)proteinFluorescent Protein Lab Experi
U. Houston - CHEE - 3300
CHAPTER 8FAILUREPROBLEM SOLUTIONS8.1 Several situations in which the possibility of failure is part of the design of a component or product are as follows: (1) the pull tab on the top of aluminum beverage cans; (2) aluminum utility/light poles
University of Florida - EAB - 3002
The &quot;Learning Curve&quot;100 80 60 40 20 0 1 2 3 4 5 6 7 8 9 10 11 12S1100 80 60 40 20 0 1 2 3 4 5 6 7 8 9 10 11S212100 80 60 40 20 0 1 2 3 4 5 6 7 8 9 10 11S3100 80 60 40 20 0S412123456789101112100 80 60 40 20
U. Houston - CHEE - 3300
CHAPTER 9PHASE DIAGRAMSPROBLEM SOLUTIONS9.1 Three variables that determine the microstructure of an alloy are 1) the alloying elements present, 2) the concentrations of these alloying elements, and 3) the heat treatment of the alloy.9.2 In or
U. Houston - CHEE - 3300
CHAPTER 10PHASE TRANSFORMATIONS IN METALSPROBLEM SOLUTIONS10.1 The two stages involved in the formation of particles of a new phase are nucleation and growth. The nucleation process involves the formation of normally very small particles of the
SUNY Buffalo - CHE - 101
Chapter 6 TroCounting and weighingExample: Burning Aluminum Five hundred aluminum atoms were burned in oxygen. The resulting aluminum oxide had a total of 1250 atoms. What is the formula of aluminum oxide? Number of oxygen atoms = 1250 500 = 75
U. Houston - CHEE - 3300
CHAPTER 11APPLICATIONS AND PROCESSING OF METAL ALLOYSPROBLEM SOLUTIONS11.1 This question asks that we list four classifications of steels, and, for each, to describe properties and cite typical applications. Low-Carbon Steels Properties: nonres
U. Houston - CHEE - 3300
CHAPTER 12STRUCTURES AND PROPERTIES OF CERAMICSPROBLEM SOLUTIONS12.1The two characteristics of component ions that determine the crystal structure are:1) themagnitude of the electrical charge on each ion; and 2) the relative sizes of the
Western Washington - PSYCH - 101
Phone a phonetic segment Phoneme sound segment that is distinctive, that contrasts or distinguishes words; displayed in between / / Allophone- a predictable phonetic variant of a phoneme [ ]
U. Houston - CHEE - 3300
CHAPTER 13APPLICATIONS AND PROCESSING OF CERAMICSPROBLEM SOLUTIONS13.1 The two desirable characteristics of glasses are optical transparency and ease of fabrication.13.2 (a) Devitrification is the process whereby a glass material is caused to
Western Washington - PSYCH - 101
What is Psychology? Text: &quot;the science of behavior and the mind&quot; (Gray, 2002, p. 3) The scientific study of behavior and mental processes Where did Psychology come from? Philosophy Socrates Plato Arisotle Are People inherently good or evil? Do o
U. Houston - CHEE - 3300
CHAPTER 14POLYMER STRUCTURESPROBLEM SOLUTIONS14.1Polymorphism is when two or more crystal structures are possible for a material of given composition. Isomerism is when two or more polymer molecules or mer units have the same composition, but
Western Washington - PSYCH - 101
Chapter 6 Motivation and Emotion Sleep Sleep is a motivated behavior Why do we sleep? Is it due to changes in light? (day/night cycle) Sleep Regulation Highly regulated behaviour Time Deprivation Studies - Free Running Sleep Regulation Follow a
SUNY Buffalo - CHE - 101
Chapter 7 troChemical equations and reactionsOxyhydrocarbon 1 (from last week) One mole of C3H6O5 is burned in O2. How many moles of CO2 are formed? (3) How many moles of H2O are formed? (3) How many moles of O2 are consumed?(2) Safest approa
Western Washington - PSYCH - 101
Chapter 9 Memory Storage of Information so that it can be used at a later time The Information-Processing Approach to Memory Memory may be thought of as a three-stage process, in which information in each stage lasts longer than in the preceding o
U. Houston - CHEE - 3300
CHAPTER 15CHARACTERISTICS, APPLICATIONS, AND PROCESSING OF POLYMERSPROBLEM SOLUTIONS15.1 From Figure 15.3, the elastic modulus is the slope in the elastic linear region of the 20 C curve, which is(stress) 30 MPa 0 MPa = = 3.3 GPa (strain) 9 x
Western Washington - PSYCH - 101
Chapter 13 Social Perception Social Psychology Social Cognition examines how we process information about the social world, ourselves and others Social Influence examines how people influence other's behaviour, judgments, etc. Social Cognition H
U. Houston - CHEE - 3363
Problem 3.1D = 0.75 m. The gas is at an absolute pressure of 25 MPa and a temperature of 25C. What is the mass in the tank? If the maximum allowable wall stress in the tank is 210 MPa, find the minimum theoretical wall thickness of the tank. Given:
U. Houston - CHEE - 3300
CHAPTER 16COMPOSITESPROBLEM SOLUTIONS16.1The major difference in strengthening mechanism between large-particle and dispersionstrengthened particle-reinforced composites is that for large-particle the particle-matrix interactions are not trea
Michigan - ECON - 340
Econ 340 Fall Term 2004 Page 1 of 15 (16)Alan Deardorff First Midterm (with Answers) NAME: _ Student ID No.: _ Economics 340 International Economics Prof. Alan Deardorff First Midterm ExamAnswersOctober 14, 2004INSTRUCTIONS: READ CAREFULLY!1.
U. Houston - CHEE - 3300
CHAPTER 17CORROSION AND DEGRADATION OF MATERIALSPROBLEM SOLUTIONS17.1 (a) Oxidation is the process by which an atom gives up an electron (or electrons) to become a cation. Reduction is the process by which an atom acquires an extra electron (or
Michigan - ECON - 398
ECON 398 Fall 2006 Midterm 1 Practice Exam 1 Professor OzdenorenINSTRUCTIONS You have 80 minutes to complete the exam. There are 16 questions.1. Consider the following simultaneous game, which has a variable x for two of the payoffs.High High Lo
U. Houston - CHEE - 3300
CHAPTER 18ELECTRICAL PROPERTIESPROBLEM SOLUTIONS18.1 This problem calls for us to compute the electrical conductivity and resistance of a silicon specimen. (a) We use Equations (18.3) and (18.4) for the conductivity, as1 Il = VA Il V d 22=
U. Houston - CHEE - 3300
CHAPTER 19THERMAL PROPERTIESPROBLEM SOLUTIONS19.1 The energy, E, required to raise the temperature of a given mass of material, m, is the product of the specific heat, the mass of material, and the temperature change, T asE = cpm(T)The T is
U. Houston - CHEE - 3300
CHAPTER 20MAGNETIC PROPERTIESPROBLEM SOLUTIONS20.1 (a) We may calculate the magnetic field strength generated by this coil using Equation (20.1) asNI lH ==(200 turns)(10 A) = 10,000 A - turns/m 0.2 m(b) In a vacuum, the flux density is
U. Houston - CHEE - 3300
CHAPTER 21OPTICAL PROPERTIESPROBLEM SOLUTIONS21.1 Similarities between photons and phonons are: 1) Both may be described as being wave-like in nature. 2) The energy for both is quantized. Differences between photons and phonons are: 1) Phonons
SUNY Buffalo - CHE - 101
Chapter 8 troStoichiometry
U. Houston - CHEE - 3300
CHAPTER 22ECONOMIC, ENVIRONMENTAL, AND SOCIETAL ISSUES IN MATERIALS SCIENCE AND ENGINEERINGPROBLEM SOLUTION22.D1W The three materials that are used for beverage containers are glass, aluminum, and the polymer polyethylene terephthalate (designa
UCSC - BIO - 105
Biology 105: Introduction to Genetics PRACTICE FINAL EXAM 2006 Part I: Definitions Homology: Comparison of two or more protein or DNA sequence to ascertain similarities in sequences. If two genes have an almost identical DNA sequence, they are homolo
Michigan - ECON - 398
ECON 398 Fall 2006 Midterm 1 Practice Exam 2 Professor OzdenorenINSTRUCTIONS You have 80 minutes to complete the exam. There are 16 questions.1. Notice that there is a variable x in the payoffs of the following game: Carrie R U 3,4 D 1,3Rhonda
UCSC - CHEM - 108B
CHEMISTRY 108B UC SANTA CRUZ WINTER 2007 EXAM 1KEYCH3 HO OH1 2 3 4 5 6 7 8 9 extra TotalName:_ TA:_ Section:_1. (12 points) Draw structures for the following IUPAC names: a) 2-methyl-1-phenyl-1,4-butanediolb) tert butoxycyclohexane (tert b
Michigan - ECON - 398
ECON 398 Fall 2006 Midterm 1 Practice Exam 3 Professor OzdenorenINSTRUCTIONS You have 80 minutes to complete the exam. There are 16 questions.Wonder Cloak Inc. (C) and Scary Mask Inc. (M) are two shops situated on the opposite side of State Stree
Michigan - ECON - 398
ECON 398 Fall 2006 Midterm 1 Practice Exam 4 Professor OzdenorenINSTRUCTIONS You have 80 minutes to complete the exam. There are 16 questions.Elbonia and Sylvonia are two neighboring countries where Elbonia is much larger in size and it is more i
UCSC - CHEM - 108M
UCSC - PHYS - 7A
PHYSICS 7A FINAL REVIEWCHRIS FRANCEThis is some review material that should help you prepare for the final. I will post solutions to the questions after the review session on Friday. I have no more information than you do as to what Dave will ask
Prairie View A & M - CVEG - 2454
UNC - DRAM - 116
February 14, 200719thImportant Events Charles Darwin Light bulb Social changes Religion testedCentury turns to20thCenturyChanges in Theater True proscenium stage Realism o &quot;The details of the setting, the costuming and the circumstances of
SUNY Buffalo - CHE - 101
Chapter 9 TroElectrons in atomsElectromagnetic Radiation Visible light is but one form of radiation. Wave-particle duality of light. Photons (mirror, photoelectric effect, Newton, Einstein) versus waves (prism, diffraction and interference, Huyg
Prairie View A & M - CVEG - 2454
Baylor - SOC - 1301
Study guide for Test I Textbook preparation Use Online resources Always skip &quot;A Closer view&quot; with a few exceptions (see below) Introduction Ch. 1: Basic definitions of sociology; sociological imagination, industrial revolution, leading historical fig
UNC - DRAM - 116
1.22.07 Chapter One - Play Vocabulary plot - the action of the play exposition - what happened before the play began suspense - used to build tension rising action - the audience wonders what is going to happen - sees the characters set in motion que
UNC - DRAM - 116
Terminology:1. The House: where the audience sits 2. The Voms (vomitorium): entrance way under the audience, through the audience (Paul Green Theater), or beside the audience 3. House Manager: make sure everything is working with the house, manage t
Baylor - SOC - 1301
The Chemistry of Life 2 The Chemistry of Life 2.1 What Are the Chemical Elements That Make Up Living Organisms? 2.2 How Do Atoms Bond to Form Molecules? 2.3 How Do Atoms Change Partners in Chemical Reactions? 2.4 What Properties of Water Make It So I
UNC - DRAM - 116
Drama Exam Review Quotes- 1 quote from a play, some from the text All plays except for &quot;Rising of the Moon&quot; Multiple choice, true/false, and matching One question from &quot;The Illusion&quot; Contemporary Theatre- know terms and subheadings Breakdown of Exam
Baylor - SOC - 1301
Biology 1105 Exam #1Exercise 2: Measurements in Biology Metric system used by scientists throughout the world to make measurements Also used everywhere in everyday life except in the US -where most of the measurements are the antiquated English sys
Baylor - SOC - 1301
Study Strategies (Or, &quot;How Can I Ace This Course&quot;?): So, you did great in high school without any real effort and you think that college is going to be an endless party, and that you'll get As and Bs in all of your courses without reading any textboo
Prairie View A & M - CVEG - 2454
SUNY Buffalo - CHE - 101
Chapter 11Gas LawsThe Effect of Gas Pressure the pressure exerted by a gas can cause some amazing and startling effects whenever there is a pressure difference, a gas will flow from area of high pressure to low pressure the bigger the differenc
Baylor - SOC - 1301
1. Neurotransmitter action may be terminated by e. Both a and b 2. Synapses between neurons can be all of the following except c. glial cells 3. Supportive cells of the nervous system are called d. glial cells 4. The resting membrane potential is cre
SUNY Buffalo - JLS - 133
Daniel Dunbar JLS 133 Case BriefsJohnson v. Davies Supreme Court of Florida, 1985.480 So.2d 625FACTS Plaintiff entered into a contract to purchase Defendant's home, and gave 10% down. Defendant knew the roof leaked, but affirmatively represented