iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🍵

Creating Loops with while and for: Fighting Until HP Hits Zero - Programmer Path #3 (C Language)

に公開

Recap of the Previous Session

https://zenn.dev/mattya3713/articles/fe60827bf725fb

Last time, we learned how programs make "decisions."

  • if statements (if something is true)
  • Comparison operators (comparing values)
  • else / else if (otherwise...)
  • && / || (combining conditions)

We are now able to change behavior based on conditions.

However, in its current state, the program runs once and ends.

To create a game,
we need a mechanism to repeat the same process over and over again.

This time, we will look at how to create "repetitions" using:

  • while statements
  • for statements

We will learn the mechanism of "keeping things running as long as a condition is met."


Please try coding this yourself in this chapter as well.

Rather than just reading,

Type it yourself
 ↓
Run it
 ↓
Fix bugs / Ask someone ← Level up here
 ↓
Understand by seeing the result

This is the fastest way to master it.

Before Learning about while Statements

Let's try running one first.

#include <stdio.h>

int main()
{
    int HP = 100;

    while (HP > 0)
    {
        HP -= 20;
        printf("HP is: %d\n", HP);
    }

    printf("Game Over\n");

    return 0;
}

Copy and paste the code and execute it by pressing the F5 key. If the HP decreases by 20 each time and "Game Over" is displayed at the end, you succeeded.

Once you have confirmed it works, close the black window using the 'x' button in the top right, and let's start learning.

What is a while Statement?

In a nutshell,

"Keep repeating while XX is true."

That is what a while statement is.

Breaking down the code from earlier:

while (HP > 0)
{
    HP -= 20;
    printf("HP is: %d\n", HP);
}
while

→ "Keep doing this while..."

(HP > 0)

→ "As long as HP is greater than 0" (the condition to repeat)

{
    HP -= 20;
    printf("HP is: %d\n", HP);
}

→ "Repeat this process"

To summarize:

"As long as HP is greater than 0, keep taking 20 damage."

It looks very similar to an if statement, doesn't it?

When the condition is met
if Execute only once
while Execute repeatedly as long as it is met

That is the only difference.

Beware of infinite loops!

One thing to be careful about with while statements is the infinite loop.

If the condition remains true forever,
the program will never stop.

// A dangerous example
while (true)
{
    printf("Not ending\n"); // Keeps running forever
}

If the black window won't stop, close the window or stop it with Ctrl + C.

I also made this mistake several times when I started.

What is a for Statement?

It's the same "repetition" as the while statement, but

it is easier to use when the number of times is fixed, such as:

"Attack only 5 times."

for (int i = 0; i < 5; i++)
{
    printf("Attack! %d time(s)\n", i + 1);
}

It's a notation you might not be used to, but it's simple when broken down.

for ( ① ; ② ; ③ )
Position Meaning Example
Executed only once at the beginning int i = 0 (start the counter at 0)
Condition to repeat i < 5 (while i is less than 5)
Executed every iteration i++ (increase i by 1)

Flowing through it:

① Set i = 0
 ↓
② i < 5? → Yes
 ↓
Execute the process
 ↓
③ Increase i by 1 (i = 1)
 ↓
② i < 5? → Yes
 ↓
… (Ends after repeating 5 times)
What is `i++`?

i++ is a shorthand for i = i + 1.

It is in the same family as += from the previous session.

i++;    // Increase i by 1
i--;    // Decrease i by 1

It is frequently used when working with counters.

while vs. for: Which one should I use?

"If it's the same repetition, does it matter which one I use?"

Yes, you can write it with either.
However, there are guidelines for when to use which.

Situation Best Choice
When the count is not fixed (e.g., "until HP reaches 0") while
When the count is fixed (e.g., "attack 5 times") for

Remember this table whenever you are unsure.

Summary

What we covered this time:

Repeat while a condition is met (while)

Repeat a fixed number of times (for)

Choose which to use depending on the situation


Having come this far, you have now mastered:

  • Creating values (Variables)
  • Calculating (Arithmetic operators)
  • Deciding (if)
  • Repeating (while / for)

These four items hold almost all the "operating mechanisms" of a game.

You might think, "Is that really all there is?"
But whether the hero runs, an enemy takes damage,
or a stage is cleared, it's all just these combinations.

You are now capable of reproducing the mechanics of any game in the world.

Next Session

Having said that, it would take too much effort to actually build a AAA title right now. (Conversely, if you have enough time, you can build anything!)

From here, programming enters the concepts of "efficiency" and "organization."

It gets slightly more difficult, but it is an essential step for game development.

In games, there are many scenes where you want to handle the same type of data together, such as:

  • When there are multiple enemies
  • Holding many items
  • Lining up map information

When that happens, we use Arrays.

We will look at that in the next session.

Next Session

https://zenn.dev/mattya3713/articles/e053eb0e8fe75e


All-Rounder Programmer Plan #3

Discussion