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:
for ([initialize_area]; [condition_area]; [step_area]) {
// The code we want to run a lot of times
}
For example:
#include <stdio.h>
for (int i = 0; i < 5; i++) {
printf("Hi %d\n", i);
}
Outputs:
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:
#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:
#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:
while ([condition_area]) {
// loop's code
}
For example:
#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:
#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
Top comments (0)