EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login

C# While Loop

By Priya PedamkarPriya Pedamkar

Home » Software Development » Software Development Tutorials » C# Tutorial » C# While Loop

C# While Loop

Introduction to C# while loop

C# while loop can always run until the break keyword, is utilized or it can condition can be false. The while declaration executes an argument or a block of statements while a particular Boolean expression examines to true. Since that expression is examined prior to every execution with the loop, a while loop executes zero or even more occasions. This kind of differs through the do loop, which usually executes more than one occasion. At any time inside the while declaration block, you may break out of that loop utilizing the break declaration. It is easy to step straight to the analysis with the while expression utilizing the continue declaration. In case the expression examines true, execution proceeds with the first declaration in the loop. Or else, performance proceeds with the first declaration following the loop.

The syntax for the C# while loop

While (Boolean expression like true or false)
{
//execute program so long as state returns true
}

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Example

C# While Loop

The while loop which is equally pretty straightforward. A while loop, just imagines what it is like an if statement except when you reach the bottom brace, you go back to the top. So we are going to Int x = 10, while x is less than 15, Console.WriteLine(x), and then we will increment x. So that’s just adding one to the value of x. So this will enter here, check initially, check the condition, and 10 < 15 so we say yes, write it out, and enter the body of the while loop above increment x to 11, and when we hit while loop brace { } we go up to the top again. That will evaluate x less than 15 (x < 15 ), and on we go until we have evaluated, until we have incremented to x to the point where it is 15, at which point, when we get to the bottom here, go back up, reevaluate, we will say okay, it is not anymore. So we will come out. And then we put a “Final value of x” and write that. So I would expect this to print 10, 11, 12, 13, 14, Final value of x: 15.

Output:

while loop

Example of the break keyword

static void Main (string[] args)
{
….
var repeat = true; // A new variable repeat to be used within our while loop’s condition
while(repeat)
{
//This will run forever until loop is false or the break keyword is used
}
}
Note: Be careful applying loops, the above example has no way to exit the loop creating
what’s referred to as an infinite loop
The break keyword goes out the loop at the stage it’s called.
…
while(repeat)
{
Console.WriteLine(“Add”, Announce, or Quit”);
…
else if(action == “Quit”)
{
break; // The loop can exit at this time skipping any kind of remaining code in the loop
}
…
}
…

Break keyword

So there are two things that you often want to do almost always conditionally. They are basically a way of either coming out of a loop early. So even if we know that x < 15 conditions are still going to hold, we want to come out because our time’s up or whatever it is. So if x % 3 == 0, break . And this will break out of the nearest enclosing loop. Which can be a while loop and any other kind of loops that we have forgotten. So we put if condition after the Console.WriteLine(x), so what we are going to do int x = 10, check that number, we don’t need to break, So x++, increment to 11, print 11, next increment to 12, write out 12, decide to break at this point and this does not go for the increment. So we are going to end up printing out “Final value of x is 12”. So when we run this we should see 10, 11, 12, final value 12.

Output:

while loop

Now let’s try doing this slightly differently. Now, we could end up in problems if we just did this as continue.

Popular Course in this category
C# Training Program (6 Courses, 17 Projects)6 Online Courses | 17 Hands-on Project | 89+ Hours | Verifiable Certificate of Completion | Lifetime Access
4.6 (8,847 ratings)
Course Price

View Course

Related Courses
ASP.NET Training (8 Courses, 19 Projects).NET Training Program (4 Courses, 19 Projects)

C# While Loop

At this moment this would be an infinite loop. But let’s just change something to say x += 2;

syntax C#

So this is now a ContinueInWhile(). This time we will start off with 10. Print it out, see whether x % 3, if it is we are going to add 2 to it means x + = 2, and then continue, which means skipping this x++

Syntax

So let’s even write this out. Console.WriteLine(“Skipping”). So this time we would expect to see it will print 10, then test this and 10 is not a multiple of three means if(x % 3 == 0) condition. So we go on to 11, print 11, 11 is not a multiple of 3, go on to 12, print out 12, 12 is a multiple of 3. So we are going to print “Skipping”, then increment x += 2, which means x to 14. Continue, so go to this closing brace which then goes up, check for the x < 15, yes it is, prints out 14, not a multiple of 3, increment it to 15 and now when we check the condition it’s false. So we will print the final value of x is 15. So we should see 10, 11, 12, Skipping, 14, Final value of x

 Output:

  Syntax 

Flowchart of C# While Loop

  1. In the while loop, the condition could show up prior to the body of the loop.
  2. Should the condition can be FALSE at first, while loop will never be executed.
  3. While it can be an entry-controlled loop.
  4. While initially view the condition, after that enter the body.

C# While Loop 

Conclusion

  • C# features a rich group of statements used to manage the flow of execution within your code. Although in while loop just initialization as well as, condition reaches the top of the body of the loop as well as, iteration might be created anywhere in the body of that loop. Iteration statements (for, for each, while, and do) Utilized to put in place loops. All these loops offer different features which make it pretty much useful in particular circumstances.
  • The for loop is quite beneficial once statements should be executed a particular quantity of occasions; the for-each loop is utilized to iterate more than every item within a collection. The while loop executes statements provided a managing expression examines as true; the do loop is just like the while loop but ensures the fact that managed statements execute at least one time.

 Recommended Article

This has been a guide to C# while loop. Here we discuss introduction, Flowchart of while loop along with Syntax and Example. You can also go through our other suggested articles to learn more –

  1. Loops in C
  2. Loops in C++
  3. While Loop in C
  4. While Loop in JavaScript

C# Training Program (6 Courses, 17 Projects)

6 Online Courses

17 Hands-on Project

89+ Hours

Verifiable Certificate of Completion

Lifetime Access

Learn More

3 Shares
Share
Tweet
Share
Primary Sidebar
C sharp Tutorial
  • Loops
    • C# For Loop
    • C# While Loop
    • C# do-while loop
    • C# foreach Loop
  • Basic
    • Uses Of C#
    • C# Versions
    • C# Data Types
    • Variables in C#
    • Namespaces in C#
    • C# Compilers
    • C# Keywords
    • Iterators in C#
    • Objects in C#
    • C# Object Dispose
    • C# object to XML
    • C# check object type
    • C# Object Serialization
    • Pointers in C#
    • C# Literals
    • C# Commands
    • C# Custom Attribute
    • Type Casting in C#
    • String vs String C#
    • C# Struct vs Class
  • Operators
    • Logical Operators in C#
    • Conditional Operators in C#
    • Bitwise Operators in C#
    • C# OR Operator
    • C# Ternary Operators
    • Operator Precedence in C#
  • Control Statement
    • C# if Statement
    • Else If in C#
    • Continue in C#
    • Break in C#
    • Switch Statement in C#
    • Goto Statement in C#
  • Arrays
    • Arrays in C#
    • 2D Arrays in C#
    • C# Jagged Arrays
    • String Array in C#
    • C# Multidimensional Arrays
  • Constructor and Destructor
    • Constructor in C#
    • Copy Constructor in C#
    • Static Constructor in C#
    • Destructor in C#
  • overloading and overrideing
    • Overloading and Overriding in C#
    • Overloading in C#
    • Overriding in C#
    • Method Overloading in C#
    • Method Overriding in C#
    • Operator Overloading in C#
  • Functions
    • C# Functions
    • C# String Functions
    • Math Functions in C#
    • Recursive Function in C#
    • C# Anonymous Functions
    • C# Local Functions
    • Enum in C#
    • Trim() in C#
    • clone() in C#
    • C# random
    • C# String Format()
    • C# String Interpolation
    • C# StartsWith()
    • C# String IndexOf()
    • DateTime in C#
    • C# Nullable
    • C# nameof
    • C# checked
    • C# String PadLeft
    • Convert String to Double in C#
    • Convert int to String C#
    • String to Date C#
    • C# intern()
    • C# Stopwatch
    • C# DirectoryInfo
    • C# Compare()
    • C# Base
    • C# SOAP
    • Lock in C#
  • Advanced
    • Inheritance in C#
    • Exception Handling in C#
    • Types of Exception in C#
    • C# FileNotFoundException
    • C# NullReferenceException
    • C# OutOfMemoryException
    • C# StackOverflowException
    • Custom Exception in C#
    • What is Multithreading in C#
    • C# finally
    • C# System.IO
    • What is StringBuilder in C#
    • DataReader C#
    • BinaryWriter in C#
    • C# BinaryReader
    • TextWriter in C#
    • TextReader in C#
    • C# StringReader
    • C# StringWriter
    • C# StreamReader
    • C# StreamWriter
    • C# FileInfo
    • What is Design Pattern in C#?
    • Multithreading in C#
    • Sorting in C#
    • Bubble Sort in C#
    • C# SortedList
    • C# SortedSet
    • C# SortedDictionary
    • Abstract Class in C#
    • Access Modifiers in C#
    • C# Generics
    • Deserialization in C#
    • C# Thread
    • C# Thread Join
    • C# Thread Sleep
    • C# Thread Synchronization
    • C# Class
    • Sealed in C#
    • Sealed Class in C#
    • Polymorphism in C#
    • C# Call By Reference
    • Virtual Keyword in C# 
    • Yield Keyword in C#
    • Regular Expression in C#
    • C# Lambda Expression
    • C# Predicate
    • Convert Object to JSON C#
    • Checkbox in C#
    • C# MessageBox
    • Collections in C#
    • List in C#
    • C# LinkedList
    • Listbox in C#
    • Protected in C#
    • C# EventHandler
    • Private in C#
    • this Keyword in C#
    • Static Keyword in C#
    • C# Out Parameter
    • Assert in C#
    • C# Delegates
    • C# Interface
    • Generics in C#
    • Timer in C#
    • C# Serialization
    • Metadata in C#
    • C# Stack
    • C# Using Static
    • Queue in C#
    • C# File.Exists
    • C# Tuples
    • C# Create JSON Object
    • Partial in C#
    • C# readonly
    • C# Action Delegate
    • C# Await Async
    • C# Dictionary
    • IEnumerable C#
    • C# Data Grid View
    • C# Dynamic
    • Web Services in C#
    • C# Pattern Matching
    • C# Extension Methods
    • C# XmlSerializer
  • Programs
    • Patterns in C#
    • Swapping in C#
    • Palindrome in C#
    • Factorial in C#
    • Fibonacci Series in C#
    • Random Number Generator in C#
    • Prime Numbers in C#
    • Armstrong Number in C#
    • Reverse String in C#
  • Interview questions
    • C# Interview Questions and Answers
    • C# OOP Interview Questions
    • C# Design Pattern Interview Questions

Related Courses

C# Certification Training

ASP.NET Course

.NET Course

Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

© 2020 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA Login

Forgot Password?

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you
Book Your One Instructor : One Learner Free Class

Let’s Get Started

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

Special Offer - C# Training Program (6 Courses, 17 Projects) Learn More