While loops in C
Table of contents
Ever wanted to repeat a block of code in C and wondered how? Then a while loop is your friend. There are many types of loops in C e.g for
loop recursion
and even just writing your code as many times as you please :)
While loop syntax
A while loop uses the following syntax:
while(condition)
{
do_something();
and_another_one();
}
While loops are great if your condition is simple and will become false sometimes (loops rely on this). And it is great if you want an infinite loop (true forever).
An example of the while loop
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
/**
* Time displaying code gotten from stack overlow
* https://stackoverflow.com/questions/5141960/get-the-current-time-in-c#5142028
*
* time.h provides the time from the user system.
* You can read more in man time.h or https://pubs.opengroup.org/onlinepubs/7908799/xsh/time.h.html
*/
void greet_user(int loop_count, char *username)
{
time_t rawtime;
struct tm * timeinfo;
time ( &rawtime );
timeinfo = localtime ( &rawtime );
/* Add `1` to make it "human" readable */
printf("[%d]: Hello %s it's %s\n",(loop_count + 1), username, asctime (timeinfo));
}
int main(int argc, char **argv)
{
if (argc != 2)
{
fprintf(stderr, "Please tell us your name\n");
exit(EXIT_FAILURE);
}
/* i should be small but not too small for this task */
u_int16_t i = 0;
while(i < 10)
{
greet_user(i, argv[1]);
i++;
}
}
This loop prints the time, and the user's name ten times. To make it infinite, you can just make the following modifications to the while loop:
while (1)
{
greet_user(i, argv[1]);
i++;
}
This effectively makes the loop true forever unless the user sends a signal to exit. Using 1
as a value for a while
loop is a common practice if you are either creating a command line game or something that the user is expected to use until they exit.
Remember to always initialize the condition in your while loop. Unlike for loops (from C90 onwards at least), you cannot initialize conditions inline. The while loop has O(n) time complexity, where the time complexity is based on the number of iterations in the loop conditions.
Read more:
stackoverflow.com/questions/2950931 - A great discussion about while loops
en.wikipedia.org/wiki/While_loop - A short description of while loops and examples in some popular languages