Learn the C Programming Language!
The while loop checks if something is true and does what it’s supposed to. After it has done that, it checks again, and does the same thing.
Here is the generic while loop:
while(some condition is true) {
do something;
}
Let’s put this to the test with a program. Can you write a program that will print out the squares of all numbers from one to twenty? Probably not without manually printing all of them.
#include <stdio.h>
/* squares.c: print all of the squares from one to twenty */
main() {
int i;
i = 1;
while(i <= 20) {
printf("%d\n", i^2);
i++;
}
}
In this piece of code, there were several new things that we haven’t introduced yet.
/* squares.c: print all of the squares from one to twenty */
This is a comment. A comment exists so that you know what you are reading. Comments are contained between /* and */, and are ignored when the code is run.
int i;
i = 1;
int is short for integer. In this case, we are creating an integer, called i. In the second line, we set i to be equal to 1.
while(i <= 20) {
the i ≤ 20 is the check; if it fails, it will “break” from the loop.
Note: the “less-than-or-equal-to symbol” may render as one symbol on your screen, depending on what system you are using. However, the correct way to render it would be <=, which looks like an arrow pointing to the left.
printf("%d\n", i^2);
i++;
We already know what “\n” means. What does %d
mean? Well, it’s a placeholder for an integer. Whenever we have a value that is bound to change, like with i in this code, we use a placeholder. Here are some other placeholders that can be used with printf:
Placeholder | Type |
%d | int |
%c | char |
%s | string |
%f | float |
%l | long |
Note: don’t fret if you don’t know what these are; we’ll cover them later on.
This time, unlike with our hello world code, there are two things inside the brackets. Well, what does the part after the comma mean? Well, like I said, %d is a placeholder for an integer. So, naturally, it follows, that the next thing will be the integer that should replace the %d. We already know what i is, but what does the ^2 mean? i^2 can be read as i to the power of two, or i squared.
After that, we incremented i, to become one more that its earlier value. i++ tells the operator to read the value of i and then increment; ++i will increment the value of i and then read it. In this instance, the two are interchangable, but when we move on to more advanced concepts, the order will become essential to the success of the code.
Note: What do you think would have happened if you didn’t include i++? Try it.