icp/oer/courses/c-newcomers/sections/02-dice/03-multible-rolls/content.md

1.6 KiB

Now, that you can roll two dice at the same time, let's try to do some statistics. For that we need a way do something multiple times. In programming these constructs are called loops.

Knowledge

Loops may seem to have a convoluted syntax, but once you got it, it is straightforward. First comes the keyword for, followed by open and closed parentheses. Then you set up your counter variable, the condition, under which you stay in the loop and the instruction, which gets executed at the end, between the parentheses.

Definition of the for-loop

for(initialization; condition; increment/decrement)
{
    // Looped code
}

Here is an example of a loop with 10 iterations:

for(int i = 0; i < 10; i=i+1)
{
    printf("We are in the %d. iteration", i+1);
}

  • int i = 0 is the initialization and gets executed once at the beginning. It sets the iteration counter to zero.
  • i < 10 is the condition. This gets checked every iteration in the beginning. If it is not true we skip over the loop.
  • i=i+1; is the increment. This gets executed at the end of every iteration. This counts our up the iteration counter by one. You can also write i++ to achieve the same result.

Task

Your task is the average of 100 rolls.