C for loop

In this article, you’ll learn about C for looping statements to execute blocks of code repeatedly.

Introduces the C for loop statement

Sometimes, you want to repeat a block of code multiple times. To do this, you can use a for loop.

Note that if you want to execute code blocks based on conditions, you can use while or do… While statement.

Here is the syntax for the for loop:

For (initialize; Conditions; Update) {// statement}Copy the code

The for loop has three semicolons (;) Delimited expressions: initialization, condition, and update.

Initialize the

The for statement executes an initialization expression only once at the first start of the loop. Typically, variables are initialized in initialization expressions.

conditions

The for statement evaluates the conditional expression at the beginning of each iteration. If the result is non-zero (or true), the for statement executes the statement enclosed in curly braces {} in its body. However, if the result is zero (or false), the for statement ends.

update

The for statement evaluates the update expression at the end of each iteration. In general, loop counters are increased/decreased in update expressions.

In the for statement, all three expressions are optional. However, the semicolon must be retained. If you skip all the expressions, the for statement looks like this:

for(;;) {}Copy the code

In this case, you get an infinite loop. You need to break out of the loop with a break or return statement.

The following flowchart illustrates how the C for loop statement works:

C For example

Let’s take a few examples using for loops.

1) A simple for loop example

The following example uses a for loop to display numbers from 0 to 4:

#include <stdio.h>

int main()
{
    const int MAX = 5;
    int i;
    for (i = 0; i < MAX; i++)
        printf("%d ", i);

    return 0;
}
Copy the code

Output:

0, 1, 2, 3, 4Copy the code

How does it work?

Step 1. When the loop starts, the for statement assigns 0 to I:

i = 0

The for statement assigns 0 to I only once.

Step 2. The for statement checks if I is less than MAX, which is 5. In the first iteration, since I is zero, the for statement executes in its body, printing the value of I to the screen.

printf("%d ",i);

Step 3. The for statement executes the third expression incrementing I at the end of the iteration:

i++

From the second iteration, the for statement repeats steps 2 and 3 until the expression I < MAX becomes false.

Because MAX is 5, the for statement executes exactly five times in its body. Therefore, you will see five numbers from 0 to 4 in the output.

2) Use a for loop to display even numbers

The following example uses the for statement to display even numbers between 0 and 10:

#include <stdio.h>

int main()
{
    const int MAX = 10;
    int i;
    for (i = 0; i < MAX; i++)
    {
        if (i % 2 == 0)
        {
            printf("%d ", i);
        }
    }
    return 0;
}
Copy the code

Output: 0, 2, 4, 6, 8

How it is executed.

In this example, the for statement executes its body 10 times. In each iteration, the program checks if the current number is even and displays it.

To check if a number is even, you compare the division of a number with the remainder of 2. If the result is zero, the number is even.

3) Use the for loop to calculate the sum of consecutive numbers

The following example uses a for loop statement to calculate the sum of consecutive numbers from 1 to n, where n is an input number:

#include <stdio.h> int main() {// prompt input number int n; Printf (" Input positive integer n:"); scanf("%d", &n); Int I, total = 0; for (i = 1; i <= n; i++) total += i; Printf (" and from 1 to %d is %d\n", n, total); return 0; }Copy the code

How it is executed.

In this example, for is executed n times, where n is the input number. At each iteration, it adds the value of the current number to the total.

Note that if you apply a mathematical formula, you do not need a loop to calculate the sum of consecutive numbers from 1 to n.

#include <stdio.h> int main() {// prompt for input number int n; Printf (" Input positive integer :"); scanf("%d", &n); Int total = n * (n + 1) / 2; Printf (" and from 1 to %d is %d\n", n, total); return 0; }Copy the code

conclusion

  • Execute code blocks repeatedly using C for loop statements.