Loops
Tags: c, beginners, loops
Published: 2019-06-16 19:50:56

After you wrote down some code, it's time to continue learning. This post question is: "how do we cause to something to happen as many times as we want?".

As you may remember, we saw an example of using a _switch-case_ block of code in order to make a thing to happen as many times as we choose, but it demanded of us to write a lot of code lines. For each time we have to write a _case_ and what to do when we enter this case. We don't want that. We want it simpler and shorter.

## ___for___
Ok, so simply let's use the ___for___ keyword. The ___for___ format is:
```cpp
for ([initialize_area]; [condition_area]; [step_area]) {
    // The code we want to run a lot of times
}
```
For example:
```cpp
#include <stdio.h>

for (int i = 0; i < 5; i++) {
    printf("Hi %d\n", i);
}
```
Outputs:
```cpp
Hi 0
Hi 1
Hi 2
Hi 3
Hi 4
```
Explanation: in the __initialize_area__ we can create and initialize the loop variable/s __once__ before we start the loop. We usually name the loop variables as 'i', or 'j', or 'k' etc. We can initialize more than one variable by using a comma-separated list of variables. In the next are, the __condition_area__ check the value of our loop variable/s and continue to run the loop only if the condition is met. This check is done __before__ each iteration. After each iteration, we arrive at the __step_area__, where we usually increase (or decrease) the value/s of our loop variable/s.

In our example above, we start by initializing a variable named ___i___ with value 0 and then check if 0 < 5. Because 0 is indeed lower than 5, we execute the code in the ___for___ block and print "Hi 0". At the end of the iteration, the value of ___i___ increases by 1 (because of the "++" operator). And then at the beginning of the next iteration, we check if 1 < 5 and go on and on a few more times - until ___i___'s value is 5, and 5 is not lower than 5, and then the code stops.

The last thing you have to understand is that each "area" is optional. For example:
```cpp
#include <stdio.h>

for (;;) {
    prinf("Hi\n");
}
```
Is completely legal and means an __infinite loop__ (a loop which runs forever), because the empty condition is always met. This empty ___for___ trick appears a lot in job interview questions. You should remember that. 

Let's see another trick:
```cpp
#include <stdio.h>

for (int i = 5; i--; ) {
    printf("Hi %d\n", i);
}
```
Can you guess what this code will print? (Run it on your computer after you put it in a ___main___ function and check. Remember what we learn about ___if___ and when a condition is met.)

## ___while___
Let's talk about another type of loop, a ___while___ loop. A ___while___ loop format is shorter:
```cpp
while ([condition_area]) {
    // loop's code
}
```
For example:
```cpp
#include <stdio.h>

int main() {
    char c;
    printf("Enter a characther. Enter a 'q' in order to stop\n");
    scanf(" %c", &c);
    while (c != 'q') {
        printf("Got the character: %c\n", c);
        printf("Enter a characther. Enter a 'q' in order to stop\n");
        scanf(" %c", &c);
    }
    return 0;
}
```
The code above gets a character from the user in each iteration, and prints it until the user enters the character 'q' (a common shortcut to "quit").

But notice we have 2 duplicated lines: we have the ___prinf___ which informs the user the program is waiting for input and the ___scanf___ which gets the input both before the ___while___ loop and inside the loop. Can we write it in a shorter way? Fortunately, in C we can (in some languages, like Python, we can't). The solution is called: ___do-while___ loop. For example:
```cpp
#include <stdio.h>

int main() {
	char c;
	// Does first, checks later
	do {
		printf("Enter a characther. Enter a 'q' in order to stop\n");
		scanf(" %c", &c);
		printf("Got the character: %c\n", c);
	} while (c != 'q');
    return 0;
}
```
__Notice__ that in both of the examples we put a space before the "%c". That's because sometimes the "Enter" also insert a character '\n' and the ___scanf___ sometimes takes it as input. A space before the "%c" solves this problem.

As you can see, this code is shorter and prettier. Use ___do-while___ in cases like this, just make sure you really don't need to check something before entering the loop.

In conclusion, we will use ___for___ loop when we need to loop over a range of numbers (can be a fixed range but can also be a dynamic range) - in other words, when you need to do something for 'n' times. On the other hand, We will use ___while___ loop (and ___do-while___ loop) when we need to do something __while__ some condition is met (for example: while the option is not "quit").

####__Always remember, it's much C-mpler than you thought!__

Regards,
Gilad