Computer Science

For Loop in C

A for loop in C is a control flow statement that allows for repeated execution of a block of code. It consists of three parts: initialization, condition, and increment/decrement. The loop continues to execute as long as the condition is true. This construct is commonly used for iterating through arrays, performing calculations, and implementing other repetitive tasks in C programming.

Written by Perlego with AI-assistance

12 Key excerpts on "For Loop in C"

  • Book cover image for: C
    eBook - ePub

    C

    From Theory to Practice, Second Edition

    • George S. Tselikis, Nikolaos D. Tselikas(Authors)
    • 2017(Publication Date)
    • CRC Press
      (Publisher)
    6 Loops
    Programs often contain blocks of code that must be executed more than once. A statement whose job is to repeatedly execute the same code as long as the value of a controlling expression is true creates an iteration loop . In this chapter, we’ll discuss about C’s iteration statements: for , while , and do-while , which allow us to set up loops, as well as the break , continue , and goto statements, which can be used to transfer control from one point of a program to another.

    The for Statement

    The
    for
    statement is one of C’s three loop statements. The general form of the
    for
    statement is:
    for (exp1; exp2; exp3) { /* a block of statements (loop body), that is repeatedly executed as long as the value of exp2 is true. */ }
    The three expressions exp1 , exp2 , and exp3 can be any valid C expressions. The execution of the
    for
    statement involves the following steps:
    1. exp1 is executed only once. Typically, exp1 initializes a variable used in the other two expressions.
    2. The value of exp2 is evaluated. Typically, it is a relational condition. If it is false, the loop terminates and the execution of the program continues with the statement after the closing brace. If it is true, the loop body is executed.
    3. exp3 is executed. Typically, exp3 changes the value of a variable used in exp2 .
    4. Steps 2 and 3 are repeated until exp2 becomes false.
    As with the
    if
    statement, if the loop body consists of a single statement, the braces can be omitted. The following program uses the
    for
    statement to display the numbers from 0 to 4 .
    #include <stdio.h> int main(void ) { int a; for (a = 0; a < 5; a++) /* The braces can be omitted. */ { printf("%d ", a); } return 0; }
    Let’s see how it works:
    1. The statement a = 0; is executed.
    2. The condition a < 5 is checked. Since it is true, printf() is executed and the program displays 0 .
    3. The a++ statement is executed and a becomes 1 . The condition a < 5 is checked again. Because it is still true, printf() is executed again and the program displays 1 . This process is repeated until a becomes 5 , at which point the condition a < 5 becomes false and the loop terminates. As a result, the program displays: 0 1 2 3 4
  • Book cover image for: Programming Logic and Design, Introductory
    It is easy for others to read, and because the loop control variable’s initialization, testing, and alteration are all performed in one location, you are less likely to leave out one of these crucial elements. Although for loops are commonly used to control execution of a block of statements a fixed number of times, the programmer doesn’t need to know the starting, final, or step value for the loop control variable when the program is written. For example, any of the values might be entered by the user, or might be the result of a calculation. Figure 5-15 Comparable while and for statements that each output Hello four times count = 0 while count <= 3 output "Hello" count = count + 1 endwhile for count = 0 to 3 step 1 output "Hello" endfor The for loop is particularly useful when processing arrays. You will learn about arrays in Chapter 6. In Java, C11, and C#, a for loop that displays 21 values (0 through 20) might look similar to the following: for(count 5 0; count <= 20; count11) { output count; } The three actions (initializing, evaluating, and altering the loop control variable) are separated by semi- colons within a set of parentheses that follow the keyword for. The expression count11 increases count by 1. In each of the three languages, the block of statements that depends on the loop sits between a pair of curly braces, so the endfor keyword is not used. None of the three languages uses the keyword output, but all of them end output statements with a semicolon. 200 C H A P T E R 5 Looping Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Both the while loop and the for loop are examples of pretest loops. In a pretest loop, the loop control variable is tested before each iteration. That means the loop body might never execute because the evaluation controlling the loop might be false the first time it is made.
  • Book cover image for: Programming Logic & Design, Comprehensive
    It is easy for others to read, and because the loop control variable’s initialization, testing, and alteration are all performed in one location, you are less likely to leave out one of these crucial elements. Although for loops are commonly used to control execution of a block of statements a fixed number of times, the programmer doesn’t need to know the starting, final, or step value for the loop control variable when the program is written. For example, any of the values might be entered by the user, or might be the result of a calculation. Figure 5-15 Comparable while and for statements that each output Hello four times count = 0 while count <= 3 output Hello count = count + 1 endwhile for count = 0 to 3 step 1 output Hello endfor The for loop is particularly useful when processing arrays. You will learn about arrays in Chapter 6. In Java, C 11 , and C#, a for loop that displays 21 values (0 through 20) might look similar to the following: for(count 5 0; count <= 20; count 11 ) { output count; } The three actions (initializing, evaluating, and altering the loop control variable) are separated by semi-colons within a set of parentheses that follow the keyword for . The expression count 11 increases count by 1. In each of the three languages, the block of statements that depends on the loop sits between a pair of curly braces, so the endfor keyword is not used. None of the three languages uses the keyword output , but all of them end output statements with a semicolon. 200 C H A P T E R 5 Looping Copyright 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-300 Both the while loop and the for loop are examples of pretest loops. In a pretest loop , the loop control variable is tested before each iteration. That means the loop body might never execute because the evaluation controlling the loop might be false the first time it is made.
  • 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: Microsoft Visual C#: An Introduction to Object-Oriented Programming
    You begin a for statement with the keyword for followed by a set of parentheses. Within the parentheses are three sections separated by exactly two semicolons. The three sections are usually used for: 1. Initializing the loop control variable 2. Testing the loop control variable 3. Updating the loop control variable As with an if or a while statement, you can use a single statement as the body of a for loop, or you can use a block of statements enclosed in curly braces. The while and for statements shown in Figure 5-10 produce the same output—the integers 1 through 10. Figure 5-10 Displaying integers 1 through 10 with while and for loops // Declare loop control variable and limit int x; const int LIMIT = 10; // Using a while loop to display 1 through 10 x = 1; while (x <= LIMIT) { WriteLine(x); ++x; } // Using a for loop to display 1 through 10 for (x = 1; x <= LIMIT; ++x) WriteLine(x); The amount by which a loop control variable increases or decreases on each cycle through the loop is often called the step value . That’s because in the BASIC programming language, and its descendent, the Visual Basic language, the keyword STEP is actually used in for loops. 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. 196 C H A P T E R 5 Looping Within the parentheses of the for statement shown in Figure 5-10, the initialization section prior to the first semicolon sets a variable named x to 1. The program executes this statement once, no matter how many times the body of the for loop eventually executes.
  • Book cover image for: You Can Program in C++
    eBook - PDF

    You Can Program in C++

    A Programmer's Introduction

    • Francis Glassborow(Author)
    • 2006(Publication Date)
    • Wiley
      (Publisher)
    Looping, Repetition, and Iteration These are just three terms with very similar meanings. C++ provides three main mechanisms for looping. 1. while( control-expression ) action . The action statement (usually a compound statement enclosed in braces) is repeated so long as the control expression evaluates as true (or non-zero). The control expression is evaluated before every repetition including the first. If it evaluates to false (or zero) the action statement is not executed and processing resumes with the next statement. Note that this means that the action part of the statement may sometimes not be executed even once. 2. do { actions } while( control-expression ); This variant tests for repetition after each execution of the action block. It is used when the actions must always be executed at least once. Otherwise, it is similar to the while loop.. 3. for( initialization ; test ; termination ) action . This form of looping is largely equivalent to writing: initialization ; while( test ){ action termination ; } We never need to use a for statement (or alternatively we can always write a while statement as a for statement). However, using both constructs allows us to provide idioms that help other programmers follow our intentions. It is generally idiomatic to use a for statement when the number of repeats is determined by some value (e.g. when we want to count through a number of cases). We use a while statement when we expect the end of repetition will result from some other condition such as reaching the end of a file that we are processing. The most common use of do-while is for cases where some form of data must be obtained and processed with an option to get more data depending on the result of the current repetition. C++ provides several ways to terminate processing of a loop. The continue keyword allows the program to abort the current iteration and go directly to the test for the next repetition.
  • Book cover image for: C++ All-in-One For Dummies
    • John Paul Mueller(Author)
    • 2020(Publication Date)
    • For Dummies
      (Publisher)
    Fortunately, the great founders of the computer world recognized that not every programmer is a virtuoso at the piano with flying fingers and that applications often need to do the same thing over and over. Thus, they created a helpful tool: the for loop. A for loop executes the same piece of code repeatedly a certain number of times. And that’s just what you want to do in this example. Looping situations Several types of loops are available, and in this section you see how they work. Which type of loop you use depends on the situation. The preceding section meth-ods one loop type: the for loop. The idea behind a for loop is to have a coun-ter variable that either increases or decreases, and the loop runs as long as the counter variable satisfies a particular condition. For example, the counter variable might start at 0 , and the loop runs as long as the counter is less than 10 . The counter variable increments (has one added to it) each time the loop runs, and after the counter variable is not less than 10 , the loop stops. Another way to loop is to simplify the logic a bit and say, “I want this loop to run as long as a certain condition is true.” This is a while loop , and you simply specify a condition under which the loop continues to run. When the condition is true, the loop keeps running. After the condition is no longer true, the loop stops. Finally, there’s a slight modification to the while loop: the do-while loop. The do-while loop is used to handle one particular situation that can arise. When you have a while loop, if the condition is not true when everything starts, the com-puter skips over the code in the while loop and does not even bother executing Directing the Application Flow CHAPTER 5 Directing the Application Flow 117 it. But sometimes you may have a situation in which you would want the code to always execute at least once. In that case, you can use a do-while loop. Table 5-2 shows the types of loops.
  • Book cover image for: C# Programming
    eBook - PDF

    C# Programming

    From Problem Analysis to Program Design

    Recall that the first programming construct is the simple sequence and that the sec-ond construct is the selection statement. The third construct is called repetition, iter-ation, or looping. In this chapter, you discover why loops are so valuable and how to write loop control structures. You learn about different kinds of loops and determine when one type is more appropriate than another. Why Use a Loop? One of the major strengths of programming languages can be attributed to loops. The programming examples you have seen thus far could have been solved more quickly through manual calculations. Take, for example, calculating your course grade aver-age. With a calculator in hand, you could certainly add together your scores and divide by the number of entries. However, if you were assigned this task for everyone in your class or everyone at your school, you could see the value of being able to write one set of instructions that can be repeated with many different sets of data. C# has a rich set of looping structures. These constructs, sometimes called repetition or iteration structures , enable you to identify and block together one or more state-ments to be repeated based on a predetermined condition. For looping, C# includes the C-style traditional while , do . . . while , and for statements that are found in many other programming languages. New to C-style languages is the foreach loop construct used to process collections of data stored under a common name in structures such as arrays, which you will learn about in Chapter 7. The sections that follow introduce you to the different types of loops and show you how they can be used in your programs. 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.
  • Book cover image for: C++ for Engineers and Scientists
    Last, note that Programs 5.10a, 5.10b, and 5.10c are all inferior to Program 5.10, and although you might encounter them in your programming career, you shouldn’t use them. Adding items other than loop control variables and their updating conditions in the for state-ment tends to make it confusing to read and can result in unwanted effects. Keeping the loop control structure “clean,” as in Program 5.10, is important and a good programming practice. Although the initializing and altering lists can be omitted from a for statement, omitting the tested expression results in an infinite loop. For example, this statement creates an infinite loop: for (count = 2; ; count = count + 1) cout << count; As with the while statement, both break and continue statements can be used in a for loop. A break forces an immediate exit from the for loop, as it does in the while loop. A continue , however, forces control to be passed to the altering list in a for statement, after which the tested expression is reevaluated. This action differs from continue ’s action in a while statement, where control is passed directly to reevaluation of the tested expression. 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. 268 Repetition Statements Figure 5.10 illustrates the internal workings of a for loop. As shown, when the for loop is completed, control is transferred to the first executable statement following the loop. To avoid having to illustrate every step, you can use a simplified set of flowchart symbols to describe for loops.
  • 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: Computer Programming with C++
    What is the output of the below segment: for( ; ; ) { printf(Computer Programming); } (a) It will print “Computer Programming” exactly once on the screen (b) This is a compilation error as the initialization and condition part is mandatory when defining the for loop (c) The block results in an infinite loop (d) This is a runtime error 3. What will be the value of variable counter after the following block is executed? int counter = 100; for( ; ; ) { if(counter-- == 95) break; } (a) This is a compilation error as the initialization and condition part is mandatory when defining the for loop (b) Value of counter will be 95 (c) Value of counter will be 94 (d) Value of counter will be 96 (e) None of the above 4. What is the value of v after the execution of following segment? int v=1; while(v<=10) { if(v>8) { break; printf(%dn,v); } else { Iterative Control Statements: Loops ✦ 213 printf(%dn,v+1); continue; } v++; } (a) 9 (b) 10 (c) 8 (d) None of the above 5. What is the value of i when the following code segment is executed: int i; for(i=10; 0 ; i--) { i--; } (a) Garbage value (b) 10 (c) 9 (d) 8 (e) 7 (f) None of the above 6. Which of the following statements is true? (a) for loop is an entry control loop whereas while loop is a exit control loop (b) for and do-while loops are exit control loops (c) for and while loops are entry control loops (d) for loop is an exit control loop. 7. Given that l1, l2 and l3 are three different loops in the program, such that the loop l3 is written inside l2 and loop l2 is written inside l1. Which of the following statements is true: (a) l1 will be executed maximum number of times (b) l2 will be executed maximum number of times (c) l3 will be executed maximum number of times (d) We cannot comment on the loop that will be executed maximum number of times.
  • Book cover image for: C++ Programming
    eBook - PDF

    C++ Programming

    From Problem Analysis to Program Design

    11. An EOF-controlled while loop uses an end-of-file marker to control the loop. The while loop continues to execute until the program detects the end-of-file marker. 12. In the Windows console environment, the end-of-file marker is entered using Ctrl1z (hold the Ctrl key and press z). 13. A for loop simplifies the writing of a counter-controlled while loop. 14. In C11, for is a reserved word. 15. The syntax of the for loop is: for (initialize statement; loop condition; update statement) statement statement is called the body of the for loop. 16. Putting a semicolon at the end of the for loop (before the body of the for loop) is a semantic error. In this case, the action of the for loop is empty. 17. The syntax of the do. . .while statement is: do statement while (expression); statement is called the body of the do...while loop. 18. Both while and for loops are called pretest loops. A do. . .while loop is called a posttest loop. 19. The while and for loop bodies may not execute at all, but the do. . . while loop body always executes at least once. 20. Executing a break statement in the body of a loop immediately terminates the loop. 21. Executing a continue statement in the body of a loop skips the loop’s remaining statements and proceeds with the next iteration. 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. 326 | Chapter 5: Control Structures II (Repetition) 22. When a continue statement executes in a while or do. . .while loop, the expression update statement in the body of the loop may not execute.
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.