MMGameslogo  MMGames
TwitterSharebutton  FacebookSharebutton   
learn through sufferingC Language
learn through sufferingC Language

How Loops Work

Initialization and Conditions
In the previous section, we explained how repetition (loops) can be achieved with a for loop.
Here, we will explain in detail how the for loop works.
Here's a more specific example of how to use a for loop.

for loop
for (Initialization; 条件式; 更新) {
    繰り返す文;
}

Initialization is a statement used to initialize a counter variable.
The expression written here is executed only once initially.

A conditional statement is a statement used to set the termination condition for a loop.
As long as the expression written here evaluates to true, the loop statements will continue to execute.

Update is a statement that updates a counter variable.
The expressions written here are executed after a loop statement is run.

Based on this, let's examine the behavior of the program created in the previous section.

Source code
#include <stdio.h>

int main(void)
{
    int i;
    
    for (i = 1; i <= 10; i++) {
        printf("メッセージ\n");
    }

    return 0;
}

Here, the initialization expression is i=1.
This expression is executed only once initially, so i is 1 at the start of the loop.

Next, we will perform a conditional comparison.
At this stage, the value of i remains 1, so the result of i <= 10 is true.
As a result, the loop will continue to run.

Next, execute the repeating sentence.Here, the printf statement is executed.

Next, the update expression is executed.
The value of i was 1 previously, but this update uses the expression i++, so the value of i increases by 1 to become 2.
Please refer to section 6 of chapter 5 if you've forgotten the ++ operator.

Repeating this execution of "condition → loop → update" multiple times.
"When i becomes 11, the condition i <= 10 will become false, and the loop will exit."

In this way, by repeatedly changing the value of the counter variable until the condition becomes false,
It ensures a set number of loop iterations.

You can put any expression in the initialization, condition, and update parts of a for loop.
"Decrement by one with each iteration, or use any unrelated expression."
However, formulas like the one in the previous section are the easiest to use for implementing a fixed number of loops.
Forever...
In a for loop, you can put any expression you want, or even omit the expression altogether.
The following program is a for loop without any expressions.
However, we recommend against running this program.

Source code
#include <stdio.h>

int main(void)
{
    for (;;) {
        printf("メッセージ\n");
    }
    
    return 0;
}

The results of this program's execution are as follows:

Execution results
メッセージ
メッセージ
メッセージ
メッセージ
メッセージ


~since省略~

This program will continue to display messages indefinitely.
Unless you force it to quit, it will never end.
As introduced in the preceding paragraph, the process completes precisely after 9999 iterations.
This program truly never seems to end.

This is because the conditional statement was omitted, causing it to be evaluated as always true.
It was because I got stuck in a state of repeatedly looping.
In this way, a loop that runs infinitely is called an infinite loop.

キーワード
【Infinite loop】

A program that repeats the same action infinitely.


In fact, this infinite loop is a very commonly used technique.
In the common apps that everyone uses regularly,
"When there's a key input, mouse input, or touch input, display the corresponding screen."
It will repeat forever until the user exits the app.

"In other words, unlike the programs we've built so far, typical apps don't just end on their own."
Unless the user explicitly chooses to terminate the program,
Infinite loops are used when you want to prevent a program from ending.
Forced evacuation
We explained that using an infinite loop is a way to prevent a program from ending unless the user explicitly chooses to terminate it.
However, the previous program did not provide a way to terminate it based on user input.
If the loop is terminated when the user input matches a specific value, the loop can end based on user input.

Typically, a for loop is designed to terminate when its condition becomes false.
Actually, you can also terminate a for loop prematurely.
You would use a break statement for that.

When a break statement is executed within a for loop, the for loop is terminated prematurely.
The counter variable retains its current value.
The following program demonstrates exiting a loop using a break statement.

Source code

#include <stdio.h>

int main(void)
{
    int i;

    for (i = 1; i <= 10; i++) {
        printf("%d\n", i);
        if (i == 3) break; /* ループを終了する */
    }

    return 0;
}

The results of this program's execution are as follows:

Execution results
1
2
3

Based on the conditional statement, it should run until it displays 10 times, but it's terminating after only 3 displays.

This is because the value of i became 3 for the third time, which caused the break statement following the if statement to be executed.
The break statement can be used in conjunction with a for loop condition.
due to errors during iteration that ended based on user input, etc.
It can be used to terminate before the number of repetitions is complete.


About This Site

Learning C language through suffering (Kushi C) is
This is the definitive introduction to the C language.
It systematically explains the basic functions of the C language.
The quality is equal to or higher than commercially available books.

Part 0: Program Overview
  1. What is a program?
Chapter 3: Displaying on the Screen
  1. String Display
  2. newline character
  3. Practice Problem 3
Chapter 4: Displaying and Calculating Numbers
  1. Display of numbers
  2. Basic calculations
  3. Numeric types
  4. Practice Problem 4
Chapter 6: Input from the Keyboard
  1. input function
  2. The fear of input
  3. Practice Problem 6
Chapter 9: Repeating a Fixed Number of Times
  1. Iterative sentence
  2. How Loops Work
  3. Practice Problem 9
Chapter 10: Repeating Without Knowing the Number of Times
  1. Unspecified loop
  2. Input validation
  3. Practice Problem 10
Chapter 13: Handling Multiple Variables at Once
  1. Handling multiple variables collectively.
  2. Arrays
  3. Practice Problem 13
Chapter 19: Dynamic Arrays
  1. Create arrays freely.
  2. Practice Problem 19