Saturday, August 1, 2015

Do...While Loop & Nested Loops

Do...While Loop

 Unlike for and while loops, which test the loop condition at the start of the loop, the do...while loop checks its condition at the end of the loop. A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at least one time.

Syntax

 The syntax of a do...while loop in C#,c,c++ is:

do
{
   statement(s);
}
while( condition );

Example 

using System;  
namespace Loops 
     
    class Program 
{

 static void Main(string[] args) 
        { 
            /* local variable definition */ 
            int a = 10;  
            /* do loop execution */ 
            do 
            { 
               Console.WriteLine("value of a: {0}", a); 
                a = a + 1; 
            } while (a < 20);  
            Console.ReadLine(); 
        } 
    } 
}  



When the above code is compiled and executed, it produces the following result: 
value of a: 10 
value of a: 11 
value of a: 12 
value of a: 13 
value of a: 14 
value of a: 15 
value of a: 16 
value of a: 17 
value of a: 18 
value of a: 19 

Nested Loops

 C# allows to use one loop inside another loop. Following section shows few examples to illustrate the concept. 

Syntax

 The syntax for a nested for loop statement in C# is as follows: 
for ( init; condition; increment ) 
   for ( init; condition; increment ) 
   { 
      statement(s); 
   } 
   statement(s); 

The syntax for a nested while loop statement in C# is as follows: 
while(condition) 
   while(condition) 
   { 
      statement(s); 
   } 
   statement(s); 

The syntax for a nested do...while loop statement in C# is as follows: 
do 
   statement(s); 
   do 
   { 
 statement(s); 
   }
while( condition );  
}
while( condition ); 







No comments:

Post a Comment