C Loops

 Consider a situation in which we execute a single statement or block of statements repeatedly for the required number of times. Such kind of problems can be solved using looping statements in C. For example, if we need to print the first 10 natural numbers then, instead of using the printf statement 10 times, we can print inside a loop which runs up to 10 iterations.The same task can be performed very easily using looping statements.

Loops are used to execute a set of statements repeatedly until a particular condition is satisfied.

How it Works

 


As per the above diagram, if the Test Condition is true, then the loop is executed, and if it is false then the execution breaks out of the loop. After the loop is successfully executed the execution again starts from the Loop entry and again checks for the Test condition, and this keeps on repeating.

The sequence of statements to be executed is kept inside the curly braces { } known as the Loop body. After every execution of the loop body, condition is verified, and if it is found to be true the loop body is executed again. When the condition check returns false, the loop body is not executed, and execution breaks out of the loop.

Advantage of loops in C
  •  It provides code reusability.
  •  Using loops, we do not need to write the same code again and again.
  •  Using loops, we can traverse over the elements of data structures (array or linked lists).
Types of C Loops
 
There are three types of loops in C language.
  • while loop
  • do-while loop
  • for loop
 


 

 



No comments:

Post a Comment