Computer Science

Nested Loops in C

Nested loops in C are loops that are placed inside another loop. This allows for the execution of a set of instructions repeatedly until a certain condition is met. The inner loop is executed completely for each iteration of the outer loop.

Written by Perlego with AI-assistance

5 Key excerpts on "Nested Loops in C"

  • Book cover image for: An Object-Oriented Approach to Programming Logic and Design
    C H A P T E R 4 Looping In this chapter, you will learn about: The loop structure Using a loop control variable Nested loops Avoiding common loop mistakes Using a for loop Common loop applications Copyright 2012 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it. Understanding the Loop Structure Although making decisions is what makes computers seem intelligent, looping makes computer programming both efficient and worthwhile. When you use a loop, you can write one set of instructions that operates on multiple data items. For example, a large company might use a single loop to produce thousands of paychecks, or a big-city utility company might use a single loop to process millions of customer bills. Using fewer instructions results in less time needed for design and coding, less compile time, and fewer errors. Recall the loop structure that you learned about in Chapter 2. Along with sequence and selection, it is one of the three basic structures used in structured programming. Figure 4-1 shows a loop structure. This loop starts with a test of a Boolean expression. The statements within a loop constitute the loop body ; the body executes as long as the loop-controlling Boolean expression remains true. The same loop-controlling question is asked following each execution of the loop body; the structure is exited only when the test expression is false. You may hear programmers refer to looping as repetition or iteration .
  • Book cover image for: C# Programming
    eBook - PDF

    C# Programming

    From Problem Analysis to Program Design

    It can also be used to implement a sentinel- or flag-controlled loop. You will see an example of this in the nested loop section. The only difference between this structure and the while structure is in the placement of the conditional expression. For posttest loops, the conditional expression is placed at the end of the loop body. Nested Loops Any statement can be included within the body of a loop, which means another loop can be nested inside an outer loop. When this occurs, the inner nested loop is totally completed before the outside loop is tested a second time. You often need nested loops when working with arrays, especially multidimensional arrays, which are covered in Chapter 8. Example 6-15 illustrates a nested loop using two for statements. FIGURE 6-13 Curly brace required Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it. Nested Loops | 361 6 EXAMPLE 6-15 int inner; for ( int outer = 0; outer < 3; outer++) { for (inner = 10; inner > 5; inner --) { WriteLine(Outer: {0}tInner: {1}, outer, inner); } } The output of this code is Outer: 0 Inner: 10 Outer: 0 Inner: 9 Outer: 0 Inner: 8 Outer: 0 Inner: 7 Outer: 0 Inner: 6 Outer: 1 Inner: 10 Outer: 1 Inner: 9 Outer: 1 Inner: 8 Outer: 1 Inner: 7 Outer: 1 Inner: 6 Outer: 2 Inner: 10 Outer: 2 Inner: 9 Outer: 2 Inner: 8 Outer: 2 Inner: 7 Outer: 2 Inner: 6 In Example 6-15, the WriteLine( ) method is executed 15 times. As shown from the output, after the variable outer is initialized to zero and evaluated to determine whether outer is less than 3, the innermost loop is executed five times.
  • Book cover image for: Programming Logic & Design, Comprehensive
    • Three actions are taken with a loop control variable in every while loop: You must initialize a loop control variable, compare the variable to some value that controls whether the loop continues or stops, and alter the variable that controls the loop. • Nested loops are loops that execute within the confines of other loops. When nesting loops, you maintain two separate loop control variables and alter each at the appropriate time. • Common mistakes that programmers make when writing loops include failing to initialize the loop control variable, neglecting to alter the loop control variable, using the wrong comparison expression with the loop control variable, and including statements inside the loop that belong outside the loop. • Most computer languages support a for statement or for loop that you can use with definite loops when you know how many times a loop will repeat. The for statement uses a loop control variable that it automatically initializes, tests, and alters. • In a posttest loop, the loop body executes at least one time because the loop control variable is not tested until after the first iteration. • In all structured loops, there is exactly one loop-controlling value, and it provides either the only entrance to or the only exit from the loop. • Loops are used in many applications—for example, to accumulate totals in business reports. Loops also are used to ensure that user data entries are valid by repeatedly reprompting the user. • In the selection structure, the two logical paths that emerge from a test join together following their actions. In the loop structure, the paths that emerge from the test do not join together; instead, one of the paths eventually returns to the same test. Key Terms A loop control variable is a variable that determines whether a loop will continue. A definite loop is one for which the number of repetitions is a predetermined value.
  • Book cover image for: Just Enough Programming Logic and Design
    Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it. variable ’ s value is the last step within the loop body. A program can leave a structured loop only at the comparison that tests the loop control variable. Watch the video Looping . Nested Loops Program logic gets more complicated when you must use loops within loops, creating nested loops . When one loop is nested within another, the containing loop is the outer loop , and the loop that is contained is the inner loop . You need to create nested loops when the values of two or more variables repeat to produce combinations of values. For example, suppose you want to write a program that produces a quiz answer sheet like the one shown in Figure 4-6. The quiz has five parts with three questions in each part, and you want a fill-in-the-blank line for each question. You could write a program that uses 21 separate output statements to produce the sheet, but using nested loops is more efficient. Figure 4-7 shows the logic of the program that produces the answer sheet. Two variables named partCounter and questionCounter are declared to keep track of the answer sheet parts and questions, respectively. Four named constants are also declared to hold the number of parts and questions in each, and to hold the text that will be printed — the word Part with each part number, and a period, space, and underscores to form a fill-in line for each question. When the program starts, partCounter is initialized to 1. The partCounter variable is the loop control variable for the outer loop in this program. The outer loop continues while partCounter is less than or equal to PARTS . The last statement in the outer loop adds 1 to partCounter .
  • Book cover image for: Java Concepts
    eBook - PDF
    • Cay S. Horstmann(Author)
    • 2014(Publication Date)
    • Wiley
      (Publisher)
    Use nested loops to implement multiple levels of iteration. • When the body of a loop contains another loop, the loops are nested. A typical use of nested loops is printing a table with rows and columns. Apply loops to the implementation of simulations. • In a simulation, you use the computer to simulate an activity. • You can introduce randomness by calling the random number generator. Use a debugger to analyze your programs. • A debugger is a program that you can use to execute another program and analyze its run-time behavior. • You can make effective use of a debugger by mastering just three concepts: break- points, single-stepping, and inspecting variables. • When a debugger executes a program, the execution is suspended whenever a breakpoint is reached. Review Questions 271 • The single-step command executes the program one line at a time. • Use the divide-and-conquer technique to locate the point of failure of a program. • During debugging, compare the actual contents of variables against the values you know they should have. • R5.1 Write a while loop that prints a. All squares less than n. For example, if n is 100, print 0 1 4 9 16 25 36 49 64 81. b. All positive numbers that are divisible by 10 and less than n. For example, if n is 100, print 10 20 30 40 50 60 70 80 90 c. All powers of two less than n. For example, if n is 100, print 1 2 4 8 16 32 64. •• R5.2 Write a loop that computes a. The sum of all even numbers between 2 and 100 (inclusive). b. The sum of all squares between 1 and 100 (inclusive). c. The sum of all odd numbers between a and b (inclusive). d. The sum of all odd digits of n. (For example, if n is 32677, the sum would be 3 + 7 + 7 = 17.) • R5.3 Provide trace tables for these loops. a. int i = 0; int j = 10; int n = 0; while (i < j) { i++; j--; n++; } b. int i = 0; int j = 0; int n = 0; while (i < 10) { i++; n = n + i + j; j++; } c. int i = 10; int j = 0; int n = 0; while (i > 0) { i--; j++; n = n + i - j; } d.
Index pages curate the most relevant extracts from our library of academic textbooks. They’ve been created using an in-house natural language model (NLM), each adding context and meaning to key research topics.