C# do While Loop

In this chapter you will learn:
  • What is do while loop in C#?
  • How it different from while loop?
  • How to use do while loop in C#?

do while loop treats same as while loop but only differences between them is that, do while executes at least one time. The code executes first then check for specified loop condition. But in while loop, the specified loop condition evaluated first then executes the code. A simple demonstration will help you to figure out do while loop more clearly.

  do while-loop flow chart
Example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

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();
        }
    }
}

Note: You must put semi-colon(;) at the end of while condition in do…while loop.

Output

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 = 96
12 x 9 = 108
12 x 10 = 120
__

Summary

In this chapter you learned what is do while loop and how to use it in C# programming. In next chapter you will learn about for loop in C#.

More Articles

 

Share your thought



PLEASE DISABLE ADBLOCKER AND SUPPORT US!

Please support us by enabling ads on this page. Refresh

YOU DON'T LIKE ADS, WE ALSO DON'T LIKE ADS!
 
But we have to show ads on our site to keep it free and updated. We have to pay huge server costs, domain costs, CDN Costs, Developer Costs, Electricity and Internet Bill. Your little contribution will encourage us to regularly update this site.