Tutorial by Examples

In order to execute a block of code over an over again, loops comes into the picture. The for loop is to be used when a block of code is to executed a fixed number of times. For example, in order to fill an array of size n with the user inputs, we need to execute scanf() for n times. C99 #include...
A while loop is used to execute a piece of code while a condition is true. The while loop is to be used when a block of code is to be executed a variable number of times. For example the code shown gets the user input, as long as the user inserts numbers which are not 0. If the user inserts 0, the ...
Unlike for and while loops, do-while loops check the truth of the condition at the end of the loop, which means the do block will execute once, and then check the condition of the while at the bottom of the block. Meaning that a do-while loop will always run at least once. For example this do-while...
for ([declaration-or-expression]; [expression2]; [expression3]) { /* body of the loop */ } In a for loop, the loop condition has three expressions, all optional. The first expression, declaration-or-expression, initializes the loop. It is executed exactly once at the beginning of the lo...
A loop is said to be an infinite loop if the control enters but never leaves the body of the loop. This happens when the test condition of the loop never evaluates to false. Example: C99 for (int i = 0; i >= 0; ) { /* body of the loop where i is not changed*/ } In the above example...
Sometimes, the straight forward loop cannot be entirely contained within the loop body. This is because, the loop needs to be primed by some statements B. Then, the iteration begins with some statements A, which are then followed by B again before looping. do_B(); while (condition) { do_A(); ...

Page 1 of 1