Saturday, 25 January 2014

Do-While Loop in C#

Unlike for and while loops, which test the loop condition at the top of the loop, the do...while loop checks its condition at the bottom of the loop.
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# is:
do
{
   statement(s);

}while( condition );
Notice that the conditional expression appears at the end of the loop, so the statement(s) in the loop execute once before the condition is tested.
If the condition is true, the flow of control jumps back up to do, and the statement(s) in the loop execute again. This process repeats until the given condition becomes false.

Flow Diagram:

do...while loop in C#

Example:

using System;
namespace do_while
{  
class Program   
{      
static void Main(string[] args)       
{  
 int table,i,res;        
 table=12;        
 i=1;        
 do          
{           
 res = table * i;          
 Console.WriteLine("{0} x {1} = {2}", table, i, res);           
 i++;          
}  // must put semi-colon(;) at the end of while               condition in do...while loop.        
 while (i <= 10);          
 Console.ReadLine();       
}   
 }
}
When the above code is compiled and executed, it produces the following result:
12 x 1 = 12
12 x 2 = 24
12 x 3 = 36
12 x 4 = 48
12 x 5 = 60
12 x 6 = 72
12 x 7 = 84
12 x 8 = 92
12 x 9 = 108
12 x 10 = 120 

No comments:

Post a Comment

C# program Selection Sorting

Selection sort is a straightforward sorting algorithm. This algorithm search for the smallest number in the elements array and then swap i...