Computer Science

While Loop in C

A while loop in C is a control flow statement that allows a block of code to be executed repeatedly as long as a specified condition is true. It consists of a condition and a block of code, and the code within the block is executed repeatedly until the condition becomes false. This looping structure is commonly used for iterating through a set of instructions until a certain condition is met.

Written by Perlego with AI-assistance

11 Key excerpts on "While Loop in C"

  • Book cover image for: Processing
    eBook - ePub

    Processing

    An Introduction to Programming

    5
    Repetition with a Loop: The  while    Statement    
    We have seen in the programs we have written that the order in which the statements are written makes a difference. This illustrates a key principle of computing known as sequence  .
    In Chapter  4, we saw that statements placed inside an if  or switch  statement are only performed if a certain condition is true. Such conditional programming illustrates a second key principle of computing known as selection  .
    In this chapter and the next, we will see that, sometimes, one or more statements need to be performed repeatedly   in a computer program. This will illustrate a third key principle in computing: repetition  .
    Human beings often find repetitive tasks to be tedious. In contrast, computers can provide an ideal way to perform repetitive tasks.  Repetition as Long as a Certain Condition Is True
    Like the if  statement, each repetition structure in this chapter will make use of a condition  . This condition will determine whether the repetition should continue  .
    Once again, let’ s consider a cooking recipe as an analogy to a computer program. Suppose a certain dough recipe says that you are to mix the ingredients and then repeatedly   add ½  cup of flour as long as   you can still stir the mixture with a spoon. A flowchart of this recipe might look like the following:
    Similarly, in computer programming, there are sometimes sets of statements that we would like to perform repeatedly  , but only as long as   a certain condition is true.
    Repetition with the while   Statement
    Processing provides several programming structures that can be used for creating repetition. One of the more versatile of these repetition structures is the while   statement. The basic form of the while
  • Book cover image for: Microsoft® Visual C# 2015
    eBook - PDF

    Microsoft® Visual C# 2015

    An Introduction to Object-Oriented Programming

    C H A P T E R 5 Looping In this chapter you will:  Learn how to create loops using the while statement  Learn how to create loops using the for statement  Learn how to create loops using the do statement  Use nested loops  Accumulate totals  Understand how to improve loop performance  Learn about looping issues in GUI programs 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. 190 C H A P T E R 5 Looping In the previous chapter, you learned how computers make decisions by evaluating Boolean expressions. Looping allows a program to repeat tasks based on the value of a Boolean expression. For example, programs that produce thousands of paychecks or invoices rely on the ability to loop to repeat instructions. Likewise, programs that repeatedly prompt users for a valid credit card number or for the correct answer to a tutorial question run more efficiently with loop structures. In this chapter, you will learn to create loops in C# programs. Computer programs seem smart due to their ability to make decisions; looping makes programs seem powerful. Creating Loops with the while Statement A loop is a structure that allows repeated execution of a block of statements. Within a looping structure, a Boolean expression is evaluated. If it is true , a block of statements called the loop body executes and the Boolean expression is evaluated again. As long as the expression is true , the statements in the loop body continue to execute and the loop-controlling Boolean expression continues to be reevaluated. When the Boolean evaluation is false , the loop ends.
  • Book cover image for: An Object-Oriented Approach to Programming Logic and Design
    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 . The loop structure in Figure 4-1 is also called a while loop because it fits the following statement: while testCondition continues to be true do someProcess endwhile In pseudocode for the while loop, the endwhile statement clearly shows where the looping structure ends. In Chapter 3, you learned to use endif to perform the same function for a selection structure. All loops can be written as while loops. Most programming languages support an additional loop format called the do-while loop. Appendix D discusses this loop. You encounter examples of looping every day, as in the following example: while you continue to be hungry take another bite of food endwhile or while an unread page remains in the reading assignment read another unread page endwhile In a business application, you might perform tasks like the following: while quantity in inventory remains low continue to order items endwhile or No Yes Figure 4-1 The loop structure 118 C H A P T E R 4 Looping 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.
  • Book cover image for: Microsoft Visual C#: An Introduction to Object-Oriented Programming
    C H A P T E R 5 Looping Upon completion of this chapter, you will be able to: • Create loops using the while statement • Create loops using the for statement • Create loops using the do statement • Use nested loops • Accumulate totals • Understand how to improve loop performance • Appreciate looping issues in GUI programs 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. 186 C H A P T E R 5 Looping In the previous chapter, you learned how computers make decisions by evaluating Boolean expressions. Looping allows a program to repeat tasks based on the value of a Boolean expression. For example, programs that produce thousands of paychecks or invoices rely on the ability to loop to repeat instructions. Likewise, programs that repeatedly prompt users for a valid credit card number or for the correct answer to a tutorial question run more efficiently with loop structures. In this chapter, you will learn to create loops in C# programs. Computer programs seem smart because of their ability to make decisions; looping makes programs seem powerful. Creating Loops with the while Statement A loop is a structure that allows repeated execution of a block of statements. Within a looping structure, a Boolean expression is evaluated. If it is true , a block of statements called the loop body executes and the Boolean expression is evaluated again. As long as the expression is true , the statements in the loop body continue to execute and the loop-controlling Boolean expression continues to be reevaluated. When the Boolean evaluation is false , the loop ends.
  • Book cover image for: C# Programming
    eBook - PDF

    C# Programming

    From Problem Analysis to Program Design

    Using the While Statement Probably the simplest and most frequently used loop structure to write is the while statement. The general form of the while statement is while (conditional expression) statement(s); The conditional expression, sometimes called the loop condition , is a logical condi-tion to be tested. It is enclosed in parentheses and is similar to the expressions you use for selection statements. The conditional expression must return a Boolean result 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. Using the While Statement | 327 6 of true or false . An interpretation of the while statement is “ while condition is true , perform statement(s).” The statement(s) following the conditional expression makes up the body of the loop. The body of the loop is performed as long as the conditional expression evaluates to true . Like the selection construct, the statement following the conditional expres-sion can be a single statement or a series of statements surrounded by curly braces { }. Some programmers use curly braces to surround all loop bodies, even loop bodies consisting of a single statement. Consistently using curly braces increases readability. It also reduces the chance of forgetting to include the curly braces when the body contains multiple statements. You can usually kill an infinite loop by closing the window or pressing the Esc key. If that does not work, try the key combinations Ctrl+C or Ctrl+Break . Press the two keys simultaneously. The easiest way to do this is to hold down the Ctrl key and then press the second key.
  • Book cover image for: Java Programming
    eBook - PDF
    C H A P T E R 6 Looping Upon completion of this chapter, you will be able to: Describe the loop structure Create while loops Use shortcut arithmetic operators Create for loops Create do…while loops Nest loops Improve loop performance Copyright 2019 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. 284 Looping C H A P T E R 6 Learning About the Loop Structure If making decisions is what makes programs seem smart, looping is what makes programs seem powerful. A loop is a structure that allows repeated execution of a block of statements. Within a looping structure, a Boolean expression is evaluated. If it is true, a block of statements called the loop body executes and the Boolean expression is evaluated again. The loop body can be a single statement, or a block of statements between curly braces. As long as the loop-controlling, Boolean expression is true, the statements in the loop body continue to execute. When the Boolean evaluation is false, the loop ends. One execution of any loop is called an iteration. Figure 6-1 shows a diagram of the logic of a loop. In Java, you can use several mechanisms to create loops. In this chapter, you learn to use three types of loops: • A while loop, in which the loop-controlling Boolean expression is the first statement in the loop, evaluated before the loop body ever executes • A for loop, which is usually used as a concise format in which to execute loops • A do…while loop, in which the loop- controlling Boolean expression is the last statement in the loop, evaluated after the loop body executes one time.
  • Book cover image for: C++ Programming
    eBook - PDF

    C++ Programming

    From Problem Analysis to Program 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. 5 while Looping (Repetition) Structure | 269 while Looping (Repetition) Structure In the previous section, you saw that sometimes it is necessary to repeat a set of statements several times. C11 has three repetition, or looping, structures that allow you to repeat a set of statements until certain conditions are met. This section discusses the first looping structure, called a while loop. The general form of the while statement is: while (expression) statement In C11, while is a reserved word. Of course, the statement can be either a simple or compound statement. The expression acts as a decision maker and is usually a logical expression. The statement is called the body of the loop. Note that the paren- theses around the expression are part of the syntax. Figure 5-1 shows the flow of execution of a while loop. FIGURE 5-1 while loop expression statement true false The expression provides an entry condition to the loop. If it initially evaluates to true, the statement executes. The loop condition—the expression—is then reevaluated. If it again evaluates to true, the statement executes again. The statement (body of the loop) continues to execute until the expression is no lon- ger true. A loop that continues to execute endlessly is called an infinite loop. To avoid an infinite loop, make sure that the loop’s body contains statement(s) that assure that the entry condition—the expression in the while statement—will eventually be false. Now that we know how to repeat statements using a while loop, next, we rewrite the program to determine the average number of calories burned in a week.
  • Book cover image for: Programming Logic & Design, Comprehensive
    C H A P T E R 5 Looping Upon completion of this chapter, you will be able to: Appreciate the advantages of looping Use a loop control variable Create nested loops Avoid common loop mistakes Use a for loop Use a posttest loop Recognize the characteristics shared by all structured loops Describe common loop applications Appreciate the similarities and differences between selections and loops Copyright 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-300 Appreciating the Advantages of Looping Although making decisions is what makes computers seem intelligent, looping makes computer programming both efficient and worthwhile. When you use a loop, one set of instructions can operate on multiple, separate sets of data. Using fewer instructions results in less time required for design and coding, fewer errors, and shorter compile time. Recall the loop structure that you learned about in Chapter 3; it looks like Figure 5-1. As long as a Boolean expression remains true, the body of a while loop executes. Quick Reference 5-1 shows the pseudocode standards this book uses for the while statement. Figure 5-1 The loop structure No Yes QUICK REFERENCE 5-1 while Statement Pseudocode Standards while condition statements that execute when condition is true endwhile The while keyword starts the statement and precedes any statements that execute when the tested condition is true. The tested condition is a Boolean expression. It might be a comparison such as x > y , it might be a Boolean variable if the language supports that type, or it might be a call to a method that returns a Boolean value. (Chapter 9 in the comprehensive version of this book describes methods that return values.) The endwhile keyword ends the structure. After endwhile , the condition is tested again. Although many modern languages do not require indentation, the bodies of while loops in this book are indented.
  • Book cover image for: Programming Logic and Design, Introductory
    C H A P T E R 5 Looping Upon completion of this chapter, you will be able to: Appreciate the advantages of looping Use a loop control variable Create nested loops Avoid common loop mistakes Use a for loop Use a posttest loop Recognize the characteristics shared by all structured loops Describe common loop applications Appreciate the similarities and differences between selections and loops Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Appreciating the Advantages of Looping Although making decisions is what makes computers seem intelligent, looping makes computer programming both efficient and worthwhile. When you use a loop, one set of instructions can operate on multiple, separate sets of data. Using fewer instructions results in less time required for design and coding, fewer errors, and shorter compile time. Recall the loop structure that you learned about in Chapter 3; it looks like Figure 5-1. As long as a Boolean expression remains true, the body of a while loop executes. Quick Reference 5-1 shows the pseudocode standards this book uses for the while statement. Figure 5-1 The loop structure No Yes QUICK REFERENCE 5-1 while Statement Pseudocode Standards while condition statements that execute when condition is true endwhile The while keyword starts the statement and precedes any statements that execute when the tested condition is true. The tested condition is a Boolean expression. It might be a comparison such as x > y, it might be a Boolean variable if the language supports that type, or it might be a call to a method that returns a Boolean value. (Chapter 9 in the comprehensive version of this book describes methods that return values.) The endwhile keyword ends the structure. After endwhile, the condition is tested again. Although many modern languages do not require indentation, the bodies of while loops in this book are indented.
  • Book cover image for: C++ Programming
    eBook - PDF

    C++ Programming

    Program Design Including Data Structures

    May not be copied, scanned, or duplicated, in whole or in part. WCN 02-300 5 while Looping (Repetition) Structure | 269 while Looping (Repetition) Structure In the previous section, you saw that sometimes it is necessary to repeat a set of statements several times. C 11 has three repetition, or looping, structures that allow you to repeat a set of statements until certain conditions are met. This section discusses the first looping structure, called a while loop . The general form of the while statement is: while (expression) statement In C 11 , while is a reserved word. Of course, the statement can be either a simple or compound statement. The expression acts as a decision maker and is usually a logical expression. The statement is called the body of the loop. Note that the paren-theses around the expression are part of the syntax. Figure 5-1 shows the flow of execution of a while loop. FIGURE 5-1 while loop expression statement true false The expression provides an entry condition to the loop. If it initially evaluates to true , the statement executes. The loop condition—the expression —is then reevaluated. If it again evaluates to true , the statement executes again. The statement (body of the loop) continues to execute until the expression is no lon-ger true . A loop that continues to execute endlessly is called an infinite loop . To avoid an infinite loop, make sure that the loop’s body contains statement(s) that assure that the entry condition—the expression in the while statement—will eventually be false . Now that we know how to repeat statements using a while loop, next, we rewrite the program to determine the average number of calories burned in a week. Copyright 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-300
  • 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. Using a Definite while Loop with a Counter You can use a while loop to execute a body of statements continuously as long as some condition continues to be true. To make a while loop end correctly, make sure your program performs three separate actions: l Initialize a variable called the loop control variable before the loop ’ s while expression — that is, before the loop begins executing. l Test the loop control variable in the while expression; if the result is true, the loop body begins executing, but if it is false, the loop ends. l Alter the value of the loop control variable so that the while expression eventually evaluates as false within the loop body. For example, the code in Figure 4-2 shows a loop that displays Hello four times. The variable count is the loop control variable. The loop executes as follows: l The loop control variable is initialized to 0. l The while expression compares count to 4. l The value is less than 4, so the loop body executes. The loop body consists of two statements that display Hello and then add 1 to count . l The next time count is evaluated, its value is 1, which is still less than 4, so the loop body executes again. Hello displays a second time and count becomes 2, Hello displays a third time and count becomes 3, then Hello displays a fourth time and count becomes 4. l Now when the expression count < 4? is evaluated, it is false , so the loop ends. start stop No Yes Declarations num count = 0 count = count + 1 start Declarations num count = 0 while count < 4 output Hello count = count + 1 endwhile stop count < 4? output “Hello” Loop control variable is initialized.
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.