Best guide for Loop Statements in C:Syntax with examples - Programmer's Mind

Loop Statements in C:

     Iterative Conditional Statements or loop statements in C are used when there is a need to execute a block of code for multiple times (to reduce the complexity of the program).
Iterative statements(Loops) mainly consists of three parts.
  • Initialization
  • Condition
  • Updation
There are three Iterative statements (loop statements) in C.They are
  1. while loop
  2. do-while loop
  3. for loop

While loop:

Syntax for while loop:

initialization;
while(condition)
 {
  statements;
  updation;
 }

First loop Variable must be initialized before control enters into the loop statement.While loop first checks the condition before entering into the loop body, if the condition is true then the program control enters into the loop body otherwise it skips the loop body and executes the next statement in the program.

Example Program using while loop:Program to print numbers from 1 to 10

while loop program

In this program while is used to repeat the printf function for printing numbers from 1 to 10,without loop if we want to write  the same program then we need to write 10 printf statements one for each number. Here 'n' is the loop controlled variable.

do-while loop:

Syntax for do-while loop:

initialization;
do
 {
   statements;
   updation;
 }while(condition);

In do-while,block of statements will be executed first and then the condition will be checked,if the condition is true then control reenters into the program. This process repeats until the condition becomes false.

Example Program using do-while loop:Program to print numbers from 1 to 10

do-while loop

What is the difference between while and do-while??

  1. while is an entry control (condition checked when control enters to the loop body) loop and do-while is an exit control loop (condition checked when control exits from the loop body).
  2. Minimum number of iterations for while is 0 where as for do-while is 1.

For loop:

For loop is same as the while loop but only difference is that all the initialization,condition and updation steps will be in a single line

Syntax of for loop:

for(initialization;condition;updation)
 {
  statements;
 }

Example Program using for loop:Program to print numbers from 1 to 10


for loop program

Outputs of all the above three programs are same
Output of loop statement programs

These loop statements can be controlled by the loop control statements or unconditional statements such as go to,break and continue

Previous Topics:

Next Topic

Share on Google Plus
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment