C Programming Cheat Sheet -4
Tags: c
Published: 2021-04-09 10:19:41

###4.The Loop Control Structure

Sometimes we want some part of our code to be executed more than once. We can either repeat the code in our program or use loops instead. It is obvious that if for example we need to execute some part of code for a hundred times it is not practical to repeat the code. Alternatively we can use our repeating code inside a loop.

There are three methods `for`, `while` and `do-while` which we can repeat a part of a program.

####4.1 while loop

`while` loop is constructed of a condition or expression and a single command or a block of commands that must run
in a loop.
```
//for single statement  
while(expression) 
    statement;

//for multiple statement   
while(expression) 
{ 
    block of statement 
} 
```
The statements within the `while` loop would keep on getting executed till the condition being tested remains true. When the condition becomes false, the control passes to the first statement that follows the body of the `while` loop.
The general form of `while` is as shown below:
```
initialise loop counter;  
while (test loopcounter using a condition) 
{ 
    do this; 
    and this; 
    increment loopcounter;
} 
```
####4.2 for loop

`for` loop is something similar to `while` loop but it is more complex. `for` loop is constructed from a control statement that determines how many times the loop will run and a command section. Command section is either a single command or a block of commands.
```
//for single statement  
for(control statement) 
    statement;  

//for multiple statement
for(control statement) 
{ 
    block of statement 
} 
```
Control statement itself has three parts:
```
for ( initialization; test condition; run every time command )
```
    * `Initialization` part is performed only once at `for` loop start. We can initialize a loop variable here.
    * `Test condition` is the most important part of the loop. Loop will continue to run if this condition is valid (true). If the condition becomes invalid (false) then the loop will terminate.
    * `Run every time command` section will be performed in every loop cycle. We use this part to reach the final condition for terminating the loop. **For example** we can increase or decrease loop variable’s value in a way that after specified number of cycles the loop condition becomes invalid and `for` loop can terminate.

####4.3 do-while loop

The `while` and `for` loops test the termination condition at the top. By contrast, the third loop in C, the `do-while`, tests at the bottom after making each pass through the loop body; the body is always executed at least once.
The syntax of the do is
```
do
{
    statements;
}while (expression);
```
The statement is executed, then expression is evaluated. If it is true, statement is evaluated again, and so on. When the expression becomes false, the loop terminates. Experience shows that `do-while` is much less used than while and for. A `do-while` loop is used to ensure that the statements within the loop are executed at least once.

####4.4 Break and Continue statement

We used `break` statement in `switch...case` structures in previously. We can also use "break" statement inside loops to terminate a loop and exit it (with a specific condition).

In above example loop execution continues until either `num>=20` or entered score is negative.
```
while (num<20) 
{ 
    printf("Enter score : "); 
    scanf("%d",&scores[num]); 
    if(scores[num]<0) 
        break; 
} 
```
`Continue` statement can be used in loops. Like break command `continue` changes flow of a program. It does not terminate the loop however. It just skips the rest of current iteration of the loop and returns to starting point of the loop.
```
#include<stdio.h> 
main() 
{ 
    while((ch=getchar())!='\n') 
    { 
        if(ch=='.') 
            continue; 
        putchar(ch); 
    }  
} 
```
In above example, program accepts all input but omits the '.' character from it. The text will be echoed as you enter it but the main output will be printed after you press the enter key (which is equal to inserting a "\n" character) is pressed. As we told earlier this is because `getchar()` function is a buffered input function.

####4.5 Goto and labels

C provides the infinitely-abusable `goto` statement, and `labels` to branch to. Formally, the `goto` statement is never necessary, and in practice it is almost always easy to write code without it. We have not used `goto` in this book.

Nevertheless, there are a few situations where `gotos` may find a place. The most common is to abandon processing in some deeply nested structure, such as breaking out of two or more loops at once. The break statement cannot be used directly since it only exits from the innermost loop. Thus:
```
for ( ... )
{           
    for ( ... ) 
    {               
        ...               
        if (disaster)
        {                   
            goto error;
        }           
    }
}       
...   
error:       
/* clean up the mess */
```

This organization is handy if the error-handling code is non-trivial, and if errors can occur in several places.

A `label` has the same form as a variable name, and is followed by a colon. It can be attached to any statement in the same function as the `goto`. The scope of a label is the entire function.

**Note** - By uses of `goto`, programs become unreliable, unreadable, and hard to debug. And yet many programmers find `goto` seductive.

---------------------------------------------------------
Make sure to follow me here :)