Free Essay

Nested Loops

In:

Submitted By mlee96
Words 323
Pages 2
8.1 Nested Loops
So far our loops have been straight forward. We saw examples of individual loops: pre-test, and post-test, pseodocode and C++ code. And we developed some projects that used the techniques illustrated in the examples. Programming in the real world, however, is seldom so simple. There are many situations requiring nested loops, where we find one loop structure embedded inside another. We will also see nested selection structures embedded in an embedded loop, but that comes later. You are now familiar with the three basic structures necessary to write any program: sequential, selection, and repetition. From now on most of our work will examine how to combine these structures into more and more complex structures. This is similar to the way we learn natural languages. We generally start with words, develop simple sentences, then compound and complex sentences. We then learn how to join sentences into paragraphs using key words to add coherence to our text, and so on. We are doing the same when we learn and eventually master a programming language. We now know the necessary structures and must learn to combine them into meaningful code to solve complex problems. We start with nested loops.
Using any of the techniques we have just learned, try to write a multiplication table for the numbers 1 through 10. Your program should create a table similar to the following:
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
... lines 5-9 skipped to save space
10 20 30 40 50 60 70 80 90 100
Here is the code to generate any of the 10 rows based on user input:
Start
Declare: number, counter counter = 1
Write "Enter a number between 1 and 10: "
Read number
While counter

Similar Documents

Premium Essay

Programming Ch3

...and sequence are alternate names for a loop structure.   | a.  | True |   | b.  | False | | | | 4. In a structured program, any structure can be nested within another structure.   | a.  | True |   | b.  | False | | | | 5. A structured program must contain a sequence, selection, and loop structure.   | a.  | True |   | b.  | False | | | | 6. Because you may stack and nest structures while retaining the overall structure, it might be difficult to determine whether a flowchart as a whole is structured.   | a.  | True |   | b.  | False | | | | 7. As a general rule, an eof question should always come immediately after an input statement because the end-of-file condition will be detected at input.   | a.  | True |   | b.  | False | | | | 8. Structured programming is sometimes called goto-less programming.   | a.  | True |   | b.  | False | | | | 9. No matter how complicated it is, any set of steps can always be reduced to combinations of the two basic structures of sequence and loop.   | a.  | True |   | b.  | False | | | | 10. The case structure is a variation of the sequence structure and the do loop is a variation of the while loop.   | a.  | True |   | b.  | False | | | | 11. Programs that use _____ code logic are unstructured programs that do not follow the rules of structured logic.   | a.  | case | b.  | loop |   | c.  | spaghetti | d.  | nested | | | | 12. With a(n) ____...

Words: 1062 - Pages: 5

Free Essay

Chapter 5

...step in a while loop is typically to ____. a. compare the loop control variable to a constant value b. initialize the loop control variable c. increment the loop control variable d. execute the body of the loop ____ 7. The last step in a while loop is usually to ____. a. compare the loop control variable to a constant value b. initialize the loop control variable c. increment the loop control variable d. execute the body of the loop ____ 8. A(n) ____ loop executes a predetermined number of times. a. terminal c. indefinite b. definite d. infinite ____ 9. Once your logic enters the body of a structured loop, ____. a. the entire loop must execute ) the entire loop must execute b. the loop can be terminated with a break statement c. the loop will execute indefinitely d. a decision statement will be evaluated ____ 10. Many loop control variable values are altered by ____, or adding to them. a. incrementing c. accumulating b. decrementing d. deprecating ____ 11. A(n) ____ is any numeric variable you use to count the number of times an event has occurred. a. accumulator c. index b. key d. counter ____ 12. A loop within another loop is known as a(n) ____ loop. a. indefinite c. nested b. infinite d. hidden ____ 13. When one loop appears inside another, the loop that contains the other loop is called the ____ loop. a. indefinite c. inner b. definite d. outer ____ 14. Usually, when you create nested loops, each loop has its own ____...

Words: 647 - Pages: 3

Premium Essay

Intro to Programming Chapter Three Homework

...and sequence are alternate names for a loop structure.   | a.  | True |   | b.  | False | | | | 4. In a structured program, any structure can be nested within another structure.   | a.  | True |   | b.  | False | | | | 5. A structured program must contain a sequence, selection, and loop structure.   | a.  | True |   | b.  | False | | | | 6. Because you may stack and nest structures while retaining the overall structure, it might be difficult to determine whether a flowchart as a whole is structured.   | a.  | True |   | b.  | False | | | | 7. As a general rule, an eof question should always come immediately after an input statement because the end-of-file condition will be detected at input.   | a.  | True |   | b.  | False | | | | 8. Structured programming is sometimes called goto-less programming.   | a.  | True |   | b.  | False | | | | 9. No matter how complicated it is, any set of steps can always be reduced to combinations of the two basic structures of sequence and loop.   | a.  | True |   | b.  | False | | | | 10. The case structure is a variation of the sequence structure and the do loop is a variation of the while loop.   | a.  | True |   | b.  | False | | | | 11. Programs that use __C___ code logic are unstructured programs that do not follow the rules of structured logic.   | a.  | case | b.  | loop |   | c.  | spaghetti | d.  | nested | | | | 12. With a(n) __C__...

Words: 1129 - Pages: 5

Free Essay

Lalalallalala

...structure works;  learn how to write algorithms using program structures; and  evaluate algorithms which contain program structures. 2 DECISION/SELECTION STRUCTURES If-Then Statements A conditional statement used in directing program flow based on multiple decision criteria. It has an equivalent to the English form: “If such-and-such is true, then do so-and-so.” General forms: A. Single Selection 1. Single line If statement 2. If…Then B. Multiple Selection 3. If…Then…Else 4. Nested If…Then.. Else 5. If…Then…ElseIf DECISION/SELECTION STRUCTURES If-Then Statements 1. Single-Line Syntax: 2. If…Then…Syntax: If [Condition] Then [Statement] If [Condition] Then [Statements] End If 3. If...Then...Else Syntax: If [Condition] Then [Statements] Else [Statements] End If DECISION/SELECTION STRUCTURES If-Then Statements 4. Nested If...Then...Else Syntax  Nesting is the process of embedding program statements in other statements  Below is the syntax for Nested If-Then Statements: If [condition1] Then [VB statements] Else If [condition2] Then VB statements If [condition3] Then [VB statements] End If Else [VB Statements] End If End If DECISION/SELECTION STRUCTURES If-Then Statements 5. If-Then-ElseIf Syntax  The ElseIf keyword is used to specify several conditions in one If/Else Statement.  Syntax: If [condition1] Then [VB statements] ElseIf [condition2] Then [VB statements] ElseIf [condition3 Then [VB statements] End If DECISION/SELECTION...

Words: 1412 - Pages: 6

Free Essay

Computer Logic Test

...CHAPTER 1 Programs that make a computer useful for everyday tasks are known as ___. Application Software ****** Which of the following is not an example of operating system software? Microsoft Word ****** What function(s) does an interpreter perform with the instructions in a high-level programming language? Translates and Execute ****** The term used for a set of rules that must be strictly followed when writing a program is: Syntax ****** ____ was the first high-level programming language designed that could perform complex mathematical calculations. FORTRAN ****** Which computer language uses short words known as mnemonics for writing programs? Assembly ****** The process known as the ____ cycle is used by the CPU to execute instructions in a program. Fetch-decode-execute ****** Which of the following is not a microprocessor manufacturing company? Dell ****** The following is an example of an instruction written in which computer language? 10110000 Machine language ****** What is the encoding technique called that is used to store negative numbers in the computer’s memory? Twos complement ****** The ______ coding scheme contains a set of 128 numeric codes that are used to represent characters in a computer's memory. ASCII ****** What is the largest value that can be stored in one byte? 255 ****** The smallest storage location in a computer’s memory is known as a ______. bit ****** The disk drive is a secondary storage device that stores...

Words: 3299 - Pages: 14

Premium Essay

Afdsfdsaf

...decision structure can be nested inside another decision structure. 4. A compound Boolean expression created with the AND operator is true only when both sub-expressions are true. 5. A controlled loop uses a true/false condition to control the number of times that it repeats. 6. A controlled loop repeats a specific number of times. 7. Each repetition of a loop is known as a(n) . 8. The While loop is a type of loop. False False True True condition count iteration pretest 19. This statement causes a function to end and sends a value back to the part of the program that called the function. 20. This is a design tool that describes the input, processing, and output of a function. 21. This type of of function returns either true or false. 22. This is an example of a data type conversion function. 23. This type of error occurs when you try to assign a value of one data type to a variable of another data type. 24. This is a string inside of a another string. Return IPO chart Boolean toReal type mismatch error substring 9. The Do-While loop is a type of loop. posttest 25. accumulator A variable that you use to gather or accumulate values. 10. The For loop is a type of loop. pretest 26. counted loop A loop for which the number of 11. A(n) loop has no way of ending and repeats until the program is interrupted. 12. A loop always executes at least...

Words: 1339 - Pages: 6

Free Essay

Pt1420 Programming Unit 10 Research & Homework

...a computer program. Counter-controlled repetition structure - used when a program needs to repeatedly process one or more instructions until some condition is met, at which time the loop ends. Many programming tasks are repetitive, having little variation from one item to the next.  Condition controlled - Most programming languages have constructions for repeating a loop until some condition changes. Note that some variations place the test at the start of the loop, while others have the test at the end of the loop.  Pre – test loop - the condition gets evaluated at the beginning of the loop cycle. Therefore, the body of the loop will not get executed if the condition does not hold the very first time. Post – Test loop - the loop condition gets evaluated at the end of the loop cycle. Therefore, the body of the loop will get executed at least once, regardless of the condition. This is a major difference between a pretest loop and a posttest loop. You may choose a posttest loop if the problem description justifies the body of the loop be executed at least once. Repetition Sequence/ Set of statements - A repetition structure causes a statement or set of statements to execute repeatedly. Sequence – set of statements that execute in the order that they appear. Condition controlled loop - uses a true/false condition to control the number of times that it repeats. Sentinel value - must be unique enough that it will not be mistaken as a regular value in the list....

Words: 1912 - Pages: 8

Premium Essay

Pt1420 Unit8

...Short Answer Review Questions 6-10 6. What is an infinite loop? Write the code for an infinite loop. An infinite loop (or endless loop) is a sequence of instructions in a computer program which loops endlessly, either due to the loop having no terminating condition, having one that can never be met, or one that causes the loop to start over. while (true) { // do stuff } to break it: while (true) { if (condition) break; } OR Set k = 1 While k < = 5 Display k End While 7. A For loop looks like what other loop in a flowchart? A For loop looks like a count-controlled loop. 8. Why is it critical that accumulator variables are properly initialized? An accumulator is used to keep a running total of numbers. In a loop, a value is usually added to the current value of the accumulator. If it is not properly initialized, it will not contain the correct total. 9. What is the advantage of using a sentinel? The advantage of using a sentinel is that when you are processing a long list of values with a loop a sentinel marks the end of a list of items. There is no limit to how many times a loop can execute 10. Why must the value chosen for use as a sentinel be carefully selected? The value of a sentinel needs to be carefully selected because it can’t be mistaken as a regular value in the list Algorithm Workbench Review Questions 3, 4, 9, 10 3. Design a For loop that displays the following set of numbers: 0, 10, 20, 30, 40...

Words: 665 - Pages: 3

Free Essay

Creating a Program That Blinks the Leds on the Board

... // MSP430 Blink the LED Demo - Software Toggle P1.0 // // Description; Toggle P1.0 by xor'ing P1.0 inside of a software loop. // ACLK = n/a, MCLK = SMCLK = default DCO // // MSP430x5xx // ----------------- // /|\| XIN|- // | | | // --|RST XOUT|- // | | // | P1.0|-->LED // // J. Stevenson // Texas Instruments, Inc // July 2011 // Built with Code Composer Studio v5 //*************************************************************************************** #include <msp430.h> int main(void) { WDTCTL = WDTPW + WDTHOLD; // Stop watchdog timer P1DIR |= 0x01; // Set P1.0 to output direction for (;;) { volatile unsigned int i; // volatile to prevent optimization P1OUT ^= 0x01; // Toggle P1.0 using exclusive-OR i = 10000; // SW Delay do i--; while (i != 0); } } 2- Google the “for” and “while” loops in C++ and describe how they work here. We will use them very often in programming. Answer: * For loop is used like an infinite loop and it helps for doing same blinking task recursively. * While loop is used to implement a very crude delay loop and the actual length of the delay can vary significantly. (Delay between LED toggles) 3- What the line “P1OUT ^= 0x01”...

Words: 803 - Pages: 4

Premium Essay

Nothing

...My age is not within that range c. Nothing d. Syntax error __D_ 4. Which structure causes a statement or set of statements to execute repeatedly? a. Start Over b. Sequence c. Decision d. Repetition _B__ 5. What type of loop uses a Boolean expression to control the number of times that it repeats a statement or set of statements? a. Count-controlled b. Condition-controlled c. Infinite d. User-controlled _A__ 6. Which pair of loops causes a statement or set of statements to repeat as long as a condition is true? a. While and Do-While b. While and Do-Until c. Do-While and Do-Until d. Do-While and For _A__ 7. ___________ represents a special value that marks the end of a list of values. a. Sentinel b. Stop c. End d. Start _C__ 8. Which loop is specifically designed to initialize, test, and increment a counter variable? a. Do-While b. Do-Until c. For d. While _D__9. How many times will the following loop iterate? Set k = 1 While k < = 5 Display k End While a. Three b. Two c. Five d. Infinite _D__ 10. How many times will the following loop iterate? Set k = 1 While k > 5 Display k End While a. One b. Two c. Five d. No iterations __A_ 11. How many times will the following loop iterate? Set k = 1 Do Display k Set k = k + 1 Until k > 1 a. One b. Two c. Three d....

Words: 789 - Pages: 4

Premium Essay

Prg 420 Week 3 Supporting Activity 1

...There are 3 kinds of loops—for loop, while loop, and do while loop. Under which circumstances would each kind of loop be more appropriate? Explain your answers using specific examples. For loop- The for loop is best used when the number of iterations is known. The for loop is best used to repeat the loop a fixed number of times. The Boolean-expression is tested at the beginning of the loop. The for loop has the form: for (initialization; Boolean-expression; increment) {nested statements }. A for loop can be used to show every number divisible by 3 between 1 and 60. For (int num=0; num , 60; num++) { If (num % 3 == 0) { System.out.println( “#: “ + dex); } } While loop- While loops are best used when the exiting condition has nothing to do with the number of loops. The While loop tests the Boolean-expression at the beginning of the loop. It is in the form : While (Boolean-expression) { nested statements} The while loop can be used to prompt the user until the exit variable (any negative number) is entered. while ( input > 0) { System.out.println(“Please enter number. Enter negative number to exit.”) } Do while loop- It is best to use the do while loop when the iteration must be executed at least once. The do while loop tests the Boolean-expression at the end of the loop. It has the form: do { nested statements } while (Boolean-expression); The do while loop can be used to show the same message multiple times. int tries = 3; int count = 1; ...

Words: 273 - Pages: 2

Free Essay

Et 2560 Unit 5 Assignment 1

...Matthew Lopez ET2560 Intro to C Unit 5 assignment 1 Pg. 238 1. Choose an appropriate kind of loop from Table 5.1 for solving each of the following problems. a. Calculate the sum of the test scores of a class of 35 students. ( Hint: Initialize sum to zero before entering loop.) Endfile- controlled loop b. Print weekly paychecks for a list of employees. The following data are to be entered interactively for each employee: ID, hours worked, and hourly pay rate. An ID of zero marks the end of the data. Sentinel- controlled loop c. Process a data file of Celsius temperatures. Count how many are above 100° C. Input validation loop Pg. 241 – 242 1. Predict the output of this program fragment: i = 0; while ( i <= 5) { printf("% 3d % 3d\ n", i, 10 - i); i = i + 1; } It will show the numbers that appear before 5 2. What is displayed by this program fragment for an input of 8? scanf("% d", & n); ev = 0; while ( ev < n) { printf("% 3d", ev); ev = ev + 2; } printf("\ n") Show the numbers from 0 to 8 increasing by 2 each time Pg. 246 – 247 1. What output values are displayed by the following while loop for a data value of 5? Of 6? Of 7? printf(" Enter an integer> "); scanf("% d", & x); product = x; count = 0; while ( count < 4) { printf("% d\ n", product); product *= x; count += 1; } No values are output 3. The following segment needs some revision. Insert braces where they are needed and correct the...

Words: 752 - Pages: 4

Free Essay

Cpu Tech

...Chapter 6 | Question 1 | | 1 / 1 point | A loop controlled by the user is a type of ____ loop. Question options: | indefinite | | definite | | counter-controlled | | incrementing | Question 2 | | 1 / 1 point | You use a unary minus sign preceding a value to make the value ____. Question options: | negative | | positive | | valid | | constant | Question 3 | | 1 / 1 point | Before entering a loop, the first input, or ____, is retrieved. Question options: | empty body | | posttest loop | | loop body | | priming read | Question 4 | | 0 / 1 point | Which is an infinite loop? Question options: | loopCount = 5; while(loopCount > 3); { System.out.println("Hello"); loopCount = loopCount - 1; } | | loopCount = 1; while(loopCount < 3); { System.out.println("Hello"); } | | loopCount = 4; while(loopCount < 3); { System.out.println("Hello"); loopCount = loopCount + 1; } | | loopCount = 1; while(loopCount < 3); { System.out.println("Hello"); loopCount = loopCount + 1; } | Question 5 | | 1 / 1 point | Use a(n) ____ loop to execute a body of statements continually as long as the Boolean expression that controls entry into the loop continues to be true. Question options: | empty | | while | | definite | | control | Question 6 | | 1 / 1 point | Making a comparison to 0 is slower than making a comparison to any other value. Question options: | True | | False | Question...

Words: 873 - Pages: 4

Premium Essay

Chapter 5 Review

...Points Missed | 0.00 | Percentage | 100% | 1. The loop control variable is initialized after entering the loop. B) False Points Earned: | 1.0/1.0 | | 2. In some cases, a loop control variable does not have to be initialized. B) False Points Earned: | 1.0/1.0 | | 3. An indefinite loop is a loop that never stops. B) False Points Earned: | 1.0/1.0 | | 4. You can either increment or decrement the loop control variable. A) True Points Earned: | 1.0/1.0 | | 5. When one loop appears inside another is is called an indented loop. B) False Points Earned: | 1.0/1.0 | | 6. Forgetting to initialize and alter the loop control variable is a common mistake that programmers sometimes make. A) True Points Earned: | 1.0/1.0 | | 7. Every high-level computer programming language contains a while statement. A) True Points Earned: | 1.0/1.0 | | 8. Both the while loop and the for loop are examples of pretest loops. A) True Points Earned: | 1.0/1.0 | | 9. The safest action is to assign the value 1 to accumulators before using them. B) False Points Earned: | 1.0/1.0 | | 10. It is the programmer’s responsibility to initialize all variables that must start with a specific value. A) True Points Earned: | 1.0/1.0 | | 11. The first step in a while loop is typically to ____. B) initialize the loop control variable Points Earned: | 1.0/1.0 | | ...

Words: 869 - Pages: 4

Premium Essay

Cscc 640

...an optional section in a PL/SQL block. ____ 6. The keyword DEFAULT can be used in place of the := symbol to assign initial values to the variables within the declaration statement. ____ 7. Declaring a table of records variable in a package specification allows it to persist for a user session. ____ 8. Implicit cursors are declared automatically for all INSERT, UPDATE, and DELETE statements issued within a PL/SQL block. ____ 9. You can process multiple rows of data from a database by creating explicit cursors. ____ 10. With an implicit cursor, Oracle closes the SQL cursor automatically after executing its associated SQL statement. As a result, %ISOPEN always yields FALSE. ____ 11. The basic loop uses the LOOP and END LOOP markers to begin and end the loop code. ____ 12. Dynamic SQL lets you write schema-management procedures that can be centralized in one schema, and can be called from other schemas and operate on the objects in those schemas. ____ 13. In PL/SQL, if a SELECT ... INTO statement returns no rows, Oracle does not return an error. ____ 14. In PL/SQL, a SELECT ... INTO statement is an example of an explicit cursor. ____ 15. In Oracle 10g, PL/SQL performance is improved across the board. Most improvements are automatic, with no action required from...

Words: 1344 - Pages: 6