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

7 Key excerpts on "For Loop in C"

  • Ivor Horton's Beginning Visual C++ 2008
    • Ivor Horton(Author)
    • 2011(Publication Date)
    • Wrox
      (Publisher)
    Figure 3-3 .
    Figure 3-3
    As I have said, the loop statement shown in Figure 3-3 can also be a block of statements. The expressions controlling the for loop are very flexible. You can even write two or more expressions separated by the comma operator for each control expression. This gives you a lot of scope in what you can do with a for loop.
    Variations on the for Loop
    Most of the time, the expressions in a for loop are used in a fairly standard way: the first for initializing one or more loop counters, the second to test if the loop should continue, and the third to increment or decrement one or more loop counters. You are not obliged to use these expressions in this way, however, and quite a few variations are possible.
    The initialization expression in a for loop can also include a declaration for a loop variable. In the previous example you could have written the loop to include the declaration for the loop counter i in the first control expression.
    for(int i = 1; i <= max; i++) // Loop specification sum += i; // Loop statement
    Naturally, the original declaration for i would need to be omitted in the program. If you make this change to the last example, you will find that it now does not compile because the loop variable, i , ceases to exist after the loop so you cannot refer to it in the output statement. A loop has a scope which extends from the for expression to the end of the body of the loop, which of course can be a block of code between braces, as well as just a single statement. The counter i is now declared within the loop scope, so you cannot refer to it in the output statement because this is outside the scope of the loop. By default the C++ compiler enforces the ISO/ANSI C++ standard by insisting that a variable defined within a loop condition cannot be reference outside the loop. If you need to use the value in the counter after the loop has executed, you must declare the counter variable outside the scope of the loop
  • Learn C Programming
    Very often, we need to perform a series of statements repeatedly. We might want to perform a calculation on each member of a set of values, or we might want to perform a calculation using all of the members in a set of values. Given a collection of values, we also might want to iterate over the whole collection to find the desired value, to count all the values, to perform some kind of calculation on them, or to manipulate the set in some way – say, to sort it.
    There are a number of ways to do this. The simplest, yet most restrictive way is the brute-force method . This can be done regardless of the language being used. A more dynamic and flexible method is to iterate or repeatedly loop. C provides three interrelated looping statements – while()… , for()… , and do … while() . Each of them has a control or continuation expression, and a loop body. The most general form of these is the while()… loop. Lastly, there is the archaic goto label method of looping. Unlike other languages, there is no repeat … until() statement; such a statement can easily be constructed from any of the others.
    Each looping statement consists of the following two basic parts:
    • The loop continuation expression
    • The body of the loop
    When the loop continuation expression evaluates to true , the body of the loop is executed. The execution then returns to the continuation expression, evaluates it, and, if true , the body of the loop is again executed. This cycle repeats until the continuation expression evaluates to false ; the loop ends, and the execution commences after the end of the loop body.
    There are two general types of continuation expressions used for looping statements, as follows:
    • Counter-controlled looping , where the number of iterations is dependent upon a count of some kind. The desired number of iterations is known beforehand. The counter may be increasing or decreasing.
    • Condition- or sentinel-controlled looping
  • Learn C Programming
    eBook - ePub

    Learn C Programming

    A beginner's guide to learning C programming the easy and disciplined way

    The simplest, yet most restrictive way is the brute-force method. This can be done regardless of the language being used. A more dynamic and flexible method is to iterate or repeatedly loop. C provides three interrelated looping statements—while()…, for()…, and do…while(). Each of them has a control or continuation expression, and a loop body. The most general form of these is the while()… loop. Lastly, there is the archaic goto label method of looping. Unlike other languages, there is no repeat … until() statement; such a statement can easily be constructed from any of the others. Each looping statement consists of the following two basic parts: The loop continuation expression The body of the loop When the loop continuation expression evaluates to true, the body of the loop is executed. The execution then returns to the continuation expression, evaluates it, and, if true, the body of the loop is again executed. This cycle repeats until the continuation expression evaluates to false; the loop ends, and the execution commences after the end of the loop body. There are two general types of continuation expressions used for looping statements, as follows: Counter-controlled looping, where the number of iterations is dependent upon a count of some kind. The desired number of iterations is known beforehand. The counter may be increasing or decreasing. Condition- or sentinel-controlled looping, where the number of iterations is dependent upon some condition to remain true for the loop to continue. The actual number of iterations is not known
  • Processing
    eBook - ePub

    Processing

    An Introduction to Programming

    6
    Creating Counting Loops Using the  for    Statement 
    In computer programming, we sometimes use a loop to count  . Such a loop is commonly known as a counting loop  .
    Uses of a Counting Loop As we shall see in this chapter, a counting loop enables us to perform two main kinds of tasks.
    First, a counting loop enables us to count through a series of numbers  . For example, suppose we would like to count from 1 to 10 and display these numbers. As we shall see in this chapter, we can use a counting loop for such a task.
    Second, a counting loop enables us to repeat one or more statements a specified number of times.   For example, suppose we would like to display “ Hello!”  to the console 20 times. As we shall see in this chapter, we can use a counting loop for this kind of task as well.
    Thus, there are two main reasons for using a counting loop:
    1)to count through a series   of numbers
    2)torepeat   a certain set of statements a specific number of times  .
    Requirements of a Counting Loop
    When we create a counting loop, we must meet three minimum requirements :
    1)Declare and initialize a counting variable  .
    2)Define a loop condition   that uses this counting variable is specified.
    3)Inside the loop, change the counting variable   in such a way that the loop condition eventually becomes false  , ending the loop.
    Let’ s work through an example of a counting loop that illustrates these three requirements.
    Creating a Counting Loop with a while   Statement
    One of the ways that we can create a counting loop is with a while   statement. Select File >  New   to create a new program. Save this program as WhileCount
  • Beginning C# 3.0
    eBook - ePub

    Beginning C# 3.0

    An Introduction to Object Oriented Programming

    • Jack Purdum(Author)
    • 2011(Publication Date)
    • Wrox
      (Publisher)
    i , you would have an infinite loop. In this case, an infinite loop would not be a good thing.
    After i has been incremented by means of the ++ increment operator, program control is transferred to expression2 . For our for loop, this expression is
         i <= end;
    The second expression, therefore, compares the newly incremented value of i to the variable end to decide whether another pass through the for loop’s statement body is warranted. As long as the current value of i is less than or equal to the value of the variable end , another pass through the loop is made. Eventually, after 101 passes through the loop, expression2 becomes logic False and the for loop statement block is skipped. Program execution then resumes with whatever statement follows the closing curly brace of the for loop. You can see in Listing 7-1 that the next statement is actually the closing brace for the btnCalc click event. Therefore, our table of squares is now complete.
    When to Use a for Loop
    The most common use of for loops is to count something or perform a sequence of instructions a specific number of times. That is, the terminating condition as stated in expression2 of the for loop is usually known when the loop is entered. In the preceding program, for example, you knew that the variable end determines how many passes should be made through the for loop statement block.
    You will discover hundreds of situations in which the for loop offers the perfect way to solve a given problem. Of the various looping structures C# makes available to you, it is probably the one used most often. A bonus feature of the for loop is that all three requirements for a well-behaved loop are specified in the three expressions used in a for
  • Python Fundamentals
    eBook - ePub

    Python Fundamentals

    A practical guide for learning Python, complete with real-world projects for you to explore

    • Ryan Marvin, Mark Ng'ang'a, Amos Omondi(Authors)
    • 2018(Publication Date)
    • Packt Publishing
      (Publisher)
    Loops allow us to deconstruct iterables and perform operations on their constituent members or even convert them into new data structures. The possibilities are endless once you start using loops.

    The for Loop

    The for loop in Python is also referred to as the for…in loop. This is due to its unique syntax that differs a bit from for loops in other languages.
    A for loop is used when you have a block of code that you would like to execute repeatedly a given number of times. For example, multiplying an iterable value, or dividing the value by another if the iterable value is still present in the loop.
    The loop contrasts and differs from a while statement in that in a for loop, the repeated code block is ran a predetermined number of times, while in a while statement, the code is ran an arbitrary number of times as long as a condition is satisfied.
    The basic syntax of a for loop is shown here:
    # Iterable here can be anything that can be looped over e.g. a list # Member here is a single constituent of the iterable e.g. an entry in a list for member in iterable: # Execute this code for each constituent member of the iterable pass
    As shown in the preceding code, the for loop allows you to go through each constituent member of an iterable and run a block of code for each member. This code could be anything from a simple summation of the values to more complex manipulations and analysis. Again, the possibilities are endless, and having the ability to easily access iterables like this will prove invaluable as you start building more complex programs in Python.

    Exercise 17: Using the for Loop

    A practical use of the for loop is shown here:
    1. First, declare a variable called numbers . We initialize numbers to a list of integers from 1 to 10:numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    2. Next, loop through the list we just created.
      Create a new variable called num in the for loop. We will use this variable to represent and access the individual numbers in the list as we loop through it:
      for num in numbers:
    3. Inside the loop, calculate the square of num by multiplying it by itself. Note that there are other ways to calculate the square, but this rudimentary method will suffice for our example here.
      We assign the square of num to the variable square :
      square = num * num
  • C Programming For Dummies
    • Dan Gookin(Author)
    • 2020(Publication Date)
    • For Dummies
      (Publisher)
    break statement. You can break out of any loop. When you do, execution continues with the first statement after the loop’s final curly bracket.

    Adding multiple for loop conditions

    A common mistake in a for loop is to use commas instead of semicolons to separate the parts. But commas are allowed in the for loop’s parentheses, just not to replace the semicolons. Instead, they are used to specify multiple initialization operations as well as multiple looping conditions. Listing 9-10 shows how you can get nutty with commas in a for statement.
    LISTING 9-10 Crowded in Here
    #include <stdio.h> int main(){ int a; char c; for( a=1,c='Z'; a<5; a=a+1,c=c-1 ) printf("%d%c\n",a,c); return(0);}
    Line 8 shows a for statement with two initializations and two expressions that take place each time the loop repeats. Both pairs are separated by a comma. The semicolons still group each of the three parts in a for loop.
    First, variable a is initialized to 1 and variable c is initialized to the letter Z. The loop spins as long as the value of variable a is less than 5. And after each statement repeats, the value of variable a is increased by 1 and the value of variable c is decreased by 1.
    Exercise 9-21: Type the source code from Listing 9-10 into your editor. Build and run.

    Screwing up a loop

    I know of two common ways to mess up a loop. These trouble spots crop up for beginners and pros alike. The only way to avoid these spots is to keep a keen eye so that you can spot 'em quick. The first goof-up is specifying a condition that can never be met; for example: for(x=1;x==10;x=x+1)
    In the preceding line, the exit condition is false before the loop spins once, so the loop is never executed. This error is almost as insidious as using an assignment operator (a single equal sign) instead of the “is equal to” operator (as just shown).
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.