C# While Loop - c# - c# tutorial - c# net



C# While Loop

C# While Loop

What is While loop in C#?

  • In C#, the while statement executes a statement or a block of statements until a specified expression evaluates to false
   C while loop

Syntax:

while (condition is true) 
{
    code will be executed;
}

C# Sample Code - C# Examples:

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

namespace wikitechy_while_loop
{
classProgram
    {
staticvoid Main(string[] args)
        {
int a = 5;
while (a < 10)
            {
Console.WriteLine("Current value of a is {0}", a);
                a++;
            }
Console.ReadLine();
        }
    }

Code Explanation:

 C while loop structure
  1. In this example, int a = 5is an integer variable.
  2. while(a>10) is the while loop which will continue to run as long as a=5 is less than10. In this example Console.WriteLine,the Main method specifies its behavior with the statement "Current value of a is {0}".WriteLine is a method of the Console class defined in the System namespace. This statement reasons the message"Current value of a is {0}"to be displayed on the screen.
  3. a++; specifies to a =5 will increase by 1 each time the loop runs (a++)variable till 9.
  4. Here Console.ReadLine();specifies to reads input from the console. When the user presses enter, it returns a string.

Sample C# examples - Output :

 C while loop structure output
  1. Here in this output, the while loop will continue to run as long as a=5 is less than 10 which will increase by 1 each time the loop runs (a++)till 9.

Related Searches to C# While Loop