Loops

The versatility of the computer lies in its ability to execute a set of instructions repeatedly this involves repeating some portion of the program either a fixed number of times r until a particular condition is being satisfied. This repetitive operation is done using a loop control structure.

There are three types of loop available in C namely, while, do while and for.

  • • The while loop keeps repeating an action until an associated test returns false. This is useful where the programmer does not know in advance how many times the loop will be traversed.
  • • The do while loops is similar, but the test occurs after the body of the loop is executed. This ensures that the body of the loop is run at least once.
  • • The for loop is frequently used, usually where the loop will be traversed a fixed number of times. It is very flexible.

The while Loop

The while loop repeats a statement until the test at the top returns false. The general form of the statement is

while (expr)
statement;


the expr is evaluated. If it is non – zero, statement is executed and expr is reevaluated. This cycle continues until expr become zero. The control flow of the while loop is shown in figure.


img

The do while Loop

This is very similar to the while loop except that the test occurs at the end of the loop body. This guarantees that the loop is executed at least one before continuing. Such a setup is frequently used where data is to be read. The test then verifies the data, and loop back to read again if it was unacceptable. Figure illustrates this concept of do while loop.

The syntax is

Do
    {
        Statement;
    } while (expr);   
img

The statement is executed, then expr is evaluated. If it is true, statement is evaluated again, and so on. When the expr becomes false, the lop terminates.


The for loop

The for loop works well where the number of iterations of the loop is known before the loop is entered. The head of the loop is entered. The head of three parts separated by semicolons.

  • • The fast is run before the loop is entered. This is usually the initialization of the loop variable.
  • • The second is a test, the loop is excited when this return false.
  • • The third is a statement to be run every time the loop body is completed. This is usually an increment of the loop counter.

The syntax of for statement is
For (expr1; expr2; expr3)

Grammatically, the three components of a for loop expressions. Most commonly, expr1 and expr3 are assignments or functions calls and expr2 is a relational expression.



About the Author



Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.

We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc





 PreviousNext