C# Tutorial

C# examples, c# while loop.

Loops can execute a block of code as long as a specified condition is reached.

Loops are handy because they save time, reduce errors, and they make code more readable.

The while loop loops through a block of code as long as a specified condition is True :

In the example below, the code in the loop will run, over and over again, as long as a variable (i) is less than 5:

Try it Yourself »

Note: Do not forget to increase the variable used in the condition, otherwise the loop will never end!

The Do/While Loop

The do/while loop is a variant of the while loop. This loop will execute the code block once, before checking if the condition is true, then it will repeat the loop as long as the condition is true.

The example below uses a do/while loop. The loop will always be executed at least once, even if the condition is false, because the code block is executed before the condition is tested:

Do not forget to increase the variable used in the condition, otherwise the loop will never end!

C# Exercises

Test yourself with exercises.

Print i as long as i is less than 6.

Start the Exercise

Get Certified

COLOR PICKER

colorpicker

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: [email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail: [email protected]

Top Tutorials

Top references, top examples, get certified.

This browser is no longer supported.

Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.

Iteration statements - for , foreach , do , and while

  • 3 contributors

The iteration statements repeatedly execute a statement or a block of statements. The for statement executes its body while a specified Boolean expression evaluates to true . The foreach statement enumerates the elements of a collection and executes its body for each element of the collection. The do statement conditionally executes its body one or more times. The while statement conditionally executes its body zero or more times.

At any point within the body of an iteration statement, you can break out of the loop using the break statement . You can step to the next iteration in the loop using the continue statement .

  • The for statement

The for statement executes a statement or a block of statements while a specified Boolean expression evaluates to true . The following example shows the for statement that executes its body while an integer counter is less than three:

The preceding example shows the elements of the for statement:

The initializer section that is executed only once, before entering the loop. Typically, you declare and initialize a local loop variable in that section. The declared variable can't be accessed from outside the for statement.

The initializer section in the preceding example declares and initializes an integer counter variable:

The condition section that determines if the next iteration in the loop should be executed. If it evaluates to true or isn't present, the next iteration is executed; otherwise, the loop is exited. The condition section must be a Boolean expression.

The condition section in the preceding example checks if a counter value is less than three:

The iterator section that defines what happens after each execution of the body of the loop.

The iterator section in the preceding example increments the counter:

The body of the loop, which must be a statement or a block of statements.

The iterator section can contain zero or more of the following statement expressions, separated by commas:

  • prefix or postfix increment expression, such as ++i or i++
  • prefix or postfix decrement expression, such as --i or i--
  • invocation of a method
  • await expression
  • creation of an object by using the new operator

If you don't declare a loop variable in the initializer section, you can use zero or more of the expressions from the preceding list in the initializer section as well. The following example shows several less common usages of the initializer and iterator sections: assigning a value to an external variable in the initializer section, invoking a method in both the initializer and the iterator sections, and changing the values of two variables in the iterator section:

All the sections of the for statement are optional. For example, the following code defines the infinite for loop:

  • The foreach statement

The foreach statement executes a statement or a block of statements for each element in an instance of the type that implements the System.Collections.IEnumerable or System.Collections.Generic.IEnumerable<T> interface, as the following example shows:

The foreach statement isn't limited to those types. You can use it with an instance of any type that satisfies the following conditions:

  • A type has the public parameterless GetEnumerator method. The GetEnumerator method can be a type's extension method .
  • The return type of the GetEnumerator method has the public Current property and the public parameterless MoveNext method whose return type is bool .

The following example uses the foreach statement with an instance of the System.Span<T> type, which doesn't implement any interfaces:

If the enumerator's Current property returns a reference return value ( ref T where T is the type of a collection element), you can declare an iteration variable with the ref or ref readonly modifier, as the following example shows:

If the source collection of the foreach statement is empty, the body of the foreach statement isn't executed and skipped. If the foreach statement is applied to null , a NullReferenceException is thrown.

await foreach

You can use the await foreach statement to consume an asynchronous stream of data, that is, the collection type that implements the IAsyncEnumerable<T> interface. Each iteration of the loop may be suspended while the next element is retrieved asynchronously. The following example shows how to use the await foreach statement:

You can also use the await foreach statement with an instance of any type that satisfies the following conditions:

  • A type has the public parameterless GetAsyncEnumerator method. That method can be a type's extension method .
  • The return type of the GetAsyncEnumerator method has the public Current property and the public parameterless MoveNextAsync method whose return type is Task<bool> , ValueTask<bool> , or any other awaitable type whose awaiter's GetResult method returns a bool value.

By default, stream elements are processed in the captured context. If you want to disable capturing of the context, use the TaskAsyncEnumerableExtensions.ConfigureAwait extension method. For more information about synchronization contexts and capturing the current context, see Consuming the Task-based asynchronous pattern . For more information about asynchronous streams, see the Asynchronous streams tutorial .

Type of an iteration variable

You can use the var keyword to let the compiler infer the type of an iteration variable in the foreach statement, as the following code shows:

Type of var can be inferred by the compiler as a nullable reference type, depending on whether the nullable aware context is enabled and whether the type of an initialization expression is a reference type. For more information see Implicitly-typed local variables .

You can also explicitly specify the type of an iteration variable, as the following code shows:

In the preceding form, type T of a collection element must be implicitly or explicitly convertible to type V of an iteration variable. If an explicit conversion from T to V fails at run time, the foreach statement throws an InvalidCastException . For example, if T is a non-sealed class type, V can be any interface type, even the one that T doesn't implement. At run time, the type of a collection element may be the one that derives from T and actually implements V . If that's not the case, an InvalidCastException is thrown.

  • The do statement

The do statement executes a statement or a block of statements while a specified Boolean expression evaluates to true . Because that expression is evaluated after each execution of the loop, a do loop executes one or more times. The do loop differs from the while loop , which executes zero or more times.

The following example shows the usage of the do statement:

  • The while statement

The while statement executes a statement or a block of statements while a specified Boolean expression evaluates to true . Because that expression is evaluated before each execution of the loop, a while loop executes zero or more times. The while loop differs from the do loop , which executes one or more times.

The following example shows the usage of the while statement:

C# language specification

For more information, see the following sections of the C# language specification :

For more information about these features, see the following feature proposal notes:

  • Async streams
  • Extension GetEnumerator support for foreach loops
  • Declarations

Coming soon: Throughout 2024 we will be phasing out GitHub Issues as the feedback mechanism for content and replacing it with a new feedback system. For more information see: https://aka.ms/ContentUserFeedback .

Submit and view feedback for

Additional resources

assignment in while loop c#

C# - while Loop

C# provides the while loop to repeatedly execute a block of code as long as the specified condition returns true .

The while loop starts with the while keyword, and it must include a boolean conditional expression inside brackets that returns either true or false. It executes the code block until the specified conditional expression returns false.

The for loop contains the initialization and increment/decrement parts. When using the while loop, initialization should be done before the loop starts, and increment or decrement steps should be inside the loop.

Above, a while loop includes an expression i . Inside a while loop, the value of i increased to 1 using i++ . The above while loop will be executed when the value of i equals to 10 and a condition i returns false.

Use the break or return keyword to exit from a while loop on some condition, as shown below.

Ensure that the conditional expression evaluates to false or exit from the while loop on some condition to avoid an infinite loop. The following loop is missing an appropriate condition or break the loop, which makes it an infinite while loop.

Nested while Loop

C# allows while loops inside another while loop, as shown below. However, it is not recommended to use nested while loop because it makes it hard to debug and maintain.

  • Difference between Array and ArrayList
  • Difference between Hashtable and Dictionary
  • How to write file using StreamWriter in C#?
  • How to sort the generic SortedList in the descending order?
  • Difference between delegates and events in C#
  • How to read file using StreamReader in C#?
  • How to calculate the code execution time in C#?
  • Design Principle vs Design Pattern
  • How to convert string to int in C#?
  • Boxing and Unboxing in C#
  • More C# articles

assignment in while loop c#

We are a team of passionate developers, educators, and technology enthusiasts who, with their combined expertise and experience, create in -depth, comprehensive, and easy to understand tutorials.We focus on a blend of theoretical explanations and practical examples to encourages hands - on learning. Visit About Us page for more information.

  • C# Questions & Answers
  • C# Skill Test
  • C# Latest Articles

Popular Articles

  • C# Guid (Dec 08, 2023)
  • C# Factory Pattern (Dec 08, 2023)
  • C# Filestream (Dec 08, 2023)
  • C# Entity Framework (Dec 08, 2023)
  • C# Event Handler (Dec 08, 2023)

C Sharp While Loop

Switch to English

Table of Contents

Introduction

Understanding the while loop, example of a while loop, tips and tricks.

  • The While loop is an important, fundamental concept in C# programming that can greatly simplify and optimize your code. It is used when you want to perform a certain action repeatedly until a certain condition is met. The While loop checks a condition before executing the loop. If the condition is True, the code inside the loop will be executed. This will continue until the condition becomes False.
  • The basic syntax of a While loop is as follows:
  • Here, the 'condition' is evaluated. If it is True, the code within the curly braces {} is executed. After executing the code, it goes back to check the condition again. This loop continues until the condition becomes False. If the condition is False in the beginning itself, the code inside the loop is never executed.
  • Let's illustrate this with an example. Suppose we want to print the numbers from 1 to 5.
  • In this example, the variable 'i' is initialized with the value 1. Then, the condition 'i <= 5' is checked. Since 1 is less than or equal to 5, the code inside the loop is executed. It prints the value of 'i' and then increments 'i' by 1. This process repeats until 'i' becomes 6, at which point the condition 'i <= 5' becomes False, and the loop stops.
  • While working with While loops, it's crucial to ensure that the loop will eventually terminate. This means that the condition must eventually become False. If it doesn't, the loop will continue indefinitely, causing the program to hang or crash. This is known as an 'infinite loop' and is one of the most common errors when using While loops.
  • To avoid infinite loops, always ensure that the code inside the loop somehow influences the condition. In the above example, the line 'i++' increments the value of 'i', which eventually makes the condition False.
  • Another common mistake is to use a single '=' instead of '==' in the condition. Remember, '=' is an assignment operator, while '==' is a comparison operator. Using '=' in the condition will assign a new value to the variable instead of comparing it, which can lead to unintended results and errors.
  • Also, be aware of off-by-one errors. These occur when the loop runs one time too many or one time too few. To avoid this, carefully consider the initial value of the loop variable and the loop condition. In the previous example, 'i' should start from 1 (not 0) and the condition should be 'i <= 5' (not 'i < 5') to correctly print the numbers from 1 to 5.
  • Mastering the While loop is a significant step towards becoming proficient in C# programming. It allows you to write efficient, optimized code and is a key aspect of many algorithms and data structures. However, it's also important to be aware of common pitfalls, such as infinite loops, incorrect use of operators, and off-by-one errors. With careful attention to these details, you can use While loops effectively and confidently in your C# programs.

Learn Python practically and Get Certified .

Popular Tutorials

Popular examples, reference materials, learn python interactively, introduction.

  • Your First C# Program
  • C# Comments
  • C# Variables and (Primitive) Data Types
  • C# Operators
  • C# Basic Input and Output
  • C# Expressions, Statements and Blocks

Flow Control

  • C# if, if...else, if...else if and Nested if Statement
  • C# ternary (? :) Operator

C# for loop

C# while and do...while loop

Nested Loops in C#: for, while, do-while

C# break Statement

  • C# continue Statement
  • C# switch Statement
  • C# Multidimensional Array
  • C# Jagged Array

C# foreach loop

  • C# Class and Object
  • C# Access Modifiers
  • C# Variable Scope
  • C# Constructor
  • C# this Keyword
  • C# Destructor
  • C# static Keyword
  • C# Inheritance
  • C# abstract class and method
  • C# Nested Class
  • C# Partial Class and Partial Method
  • C# sealed class and method
  • C# interface
  • C# Polymorphism
  • C# Method Overloading
  • C# Constructor Overloading

Exception Handling

  • C# Exception and Its Types
  • C# Exception Handling
  • C# Collections
  • C# ArrayList
  • C# SortedList
  • C# Hashtable
  • C# Dictionary
  • C# Recursion
  • C# Lambda Expression
  • C# Anonymous Types
  • C# Generics
  • C# Iterators
  • C# Delegates
  • C# Indexers
  • C# Regular Expressions

Additional Topics

  • C# Keywords and Identifiers
  • C# Type Conversion
  • C# Operator Precedence and Associativity
  • C# Bitwise and Bit Shift Operators
  • C# using Directive
  • C# Preprocessor Directives
  • Namespaces in C# Programming
  • C# Nullable Types
  • C# yield keyword
  • C# Reflection

C# Tutorials

In programming, it is often desired to execute certain block of statements for a specified number of times. A possible solution will be to type those statements for the required number of times. However, the number of repetition may not be known in advance (during compile time) or maybe large enough (say 10000).

The best solution to such problem is loop. Loops are used in programming to repeatedly execute a certain block of statements until some condition is met.

In this article, we'll learn to use while loops in C#.

C# while loop

The while keyword is used to create while loop in C#. The syntax for while loop is:

How while loop works?

  • C# while loop consists of a test-expression .
  • statements inside the while loop are executed.
  • after execution, the test-expression is evaluated again.
  • If the test-expression is evaluated to false , the while loop terminates.
  • while loop Flowchart

C# while loop

  • Example 1: while Loop

When we run the program, the output will be:

Initially the value of i is 1.

When the program reaches the while loop statement,

  • the test expression i <=5 is evaluated. Since i is 1 and 1 <= 5 is true , it executes the body of the while loop. Here, the line is printed on the screen with Iteration 1, and the value of i is increased by 1 to become 2.
  • Now, the test expression ( i <=5 ) is evaluated again. This time too, the expression returns true (2 <= 5), so the line is printed on the screen and the value of i is now incremented to 3..
  • This goes and the while loop executes until i becomes 6. At this point, the test-expression will evaluate to false and hence the loop terminates.

Example 2: while loop to compute sum of first 5 natural numbers

This program computes the sum of first 5 natural numbers.

  • Initially the value of sum is initialized to 0.
  • On each iteration, the value of sum is updated to sum+i and the value of i is incremented by 1.
  • When the value of i reaches 6, the test expression i<=5 will return false and the loop terminates.

Let's see what happens in the given program on each iteration.

Initially, i = 1, sum = 0

So, the final value of sum will be 15.

C# do...while loop

The do and while keyword is used to create a do...while loop. It is similar to a while loop, however there is a major difference between them.

In while loop, the condition is checked before the body is executed. It is the exact opposite in do...while loop, i.e. condition is checked after the body is executed.

This is why, the body of do...while loop will execute at least once irrespective to the test-expression.

The syntax for do...while loop is:

How do...while loop works?

  • The body of do...while loop is executed at first.
  • Then the test-expression is evaluated.
  • If the test-expression is true , the body of loop is executed.
  • When the test-expression is false , do...while loop terminates.

do...while loop Flowchart

Do while loop in c#

Example 3: do...while loop

As we can see, the above program prints the multiplication table of a number (5).

  • Initially, the value of i is 1. The program, then enters the body of do..while loop without checking any condition (as opposed to while loop).
  • Inside the body, product is calculated and printed on the screen. The value of i is then incremented to 2.
  • After the execution of the loop’s body, the test expression i <= 10 is evaluated. In total, the do...while loop will run for 10 times.
  • Finally, when the value of i is 11, the test-expression evaluates to false and hence terminates the loop.

Infinite while and do...while loop

If the test expression in the while and do...while loop never evaluates to false , the body of loop will run forever. Such loops are called infinite loop.

For example:

Infinite while loop

Infinite do...while loop.

The infinite loop is useful when we need a loop to run as long as our program runs.

For example, if your program is an animation, you will need to constantly run it until it is stopped. In such cases, an infinite loop is necessary to keep running the animation repeatedly.

Table of Contents

  • How while Loop Works?
  • Example 2: Natural numbers using while loop
  • How do-while Loop Works?
  • do-while loop Flowchart
  • Example 1: do-while Loop
  • Infinite while and do-while Loop

Sorry about that.

Related Tutorials

C# Tutorial

Home » C# Tutorial » C# while

Summary : in this tutorial, you’ll learn how to use the C# while statement to execute a block while a boolean expression is true .

Introduction to the C# while statement

The while statement evaluates a boolean expression and executes a block repeatedly as long as the expression is true . Here’s the syntax of the while statement:

How it works.

The expression , which follows the while keyword, must be a boolean expression that evaluates to true or false .

The while statement evaluates the expression first. If the expression evaluates to true , it’ll execute the block inside the curly braces.

Once completed executing the block, the while statement checks the expression again. And it’ll execute the block again as long as the expression is true .

If the expression is false , the while statement exits and passes the control to the statement after it.

Therefore, you need to change some variables inside the block to make the expression false at some point. Otherwise, you’ll have an indefinite loop .

Since the expression is checked at the beginning of each iteration, the while statement is often called a pretest loop.

The following flowchart illustrates how the C# while statement works.

C# while statement examples

Let’s take some examples of using the while statement.

1) Simple C# while statement example

The following example uses the while loop statement to output five numbers from 1 to 5 to the console:

First, declare a counter variable and initialize it to zero.

Second, enter the while loop because the following expression is true :

Third, increase the counter by one and print it out to the console; repeat this step as long as the counter is less than 5.

2) Using the C# while statement to calculate the average

The following program prompts users to enter a list of numbers and calculate the average:

First, declare variables and initialize them:

Second, print out the instruction:

Third, prompt users to enter a number until they enter the letter Q or q . In each iteration, calculate the total and count the entered numbers:

Finally, calculate the average if users enter at least one number and output it to the console:

In the following output, we enter three numbers 10, 20, and 30. And the program shows the average as 20:

  • Use the while statement to execute a block as long as a boolean expression is true .

Tutlane Logo

C# While Loop with Examples

In c#, the  While loop is used to execute a block of statements until the specified expression return as  true .

In the previous chapter, we learned about for loop in c# with examples . Generally, the for loop is useful when we are sure about how many times we need to execute the block of statements. If we are unknown about the number of times to execute the block of statements, then a  while loop is the best solution.

Syntax of C# While Loop

Generally, the  while keyword is used to create a while loop in c# applications. Following is the syntax of defining a while loop in c# programming language to execute the block of statements until the defined condition evaluates as false .

If you observe the above syntax, we used a while keyword to define a while loop, and it contains a parameter called boolean_expression.

Here if boolean_expression returns true , then the statements inside of the while loop will be executed. After executing the statements, the boolean_expression will be evaluated to execute the statements within the while loop.

In case the boolean_expression is evaluated to false , then the while loop stops the execution of statements, and the program comes out of the loop.

  • C# While Loop Flow Chart Diagram

Following is the pictorial representation of the while loop process flow in the c# programming language.

C# While Loop Flow Chart Diagram

Now we will see how to use while loop in c# programming language with examples.

  • C# While Loop Example

Following is the example of using a while loop in c# programming language to execute the block of statements based on our requirements.

If you observe the above example, we are executing the statements within the while loop by checking the condition ( i <= 4 ) and increasing the variable i ( i++ ) value to 1 by using the increment operator.

When we execute the above c# program, we will get the result below.

C# While Loop Example Result

If you observe the above result, while loop has been executed until it matches the defined condition ( i <= 4 ) and the program came out of the loop whenever the defined condition returns false .

C# Nested While Loop

In c#, we can use one while loop within another while loop to implement applications based on our requirements.

Following is the example of implementing nested while loop in the c# programming language.

If you observe the above example, we used one while loop within another while loop to achieve nested while loop functionality in our application based on our requirements.

C# Nested While Loop Example Result

If you observe the above example, both while loops got executed and returned the result based on our requirements.

C# While Loop with Break Statement

In c#, we can exit or terminate the execution of a  while loop immediately by using a  break keyword.

Following is the example of using the  break keyword in a  while loop to terminate the loop's execution in the c# programming language.

If you observe the above example, whenever the variable ( i ) value becomes 2 , we terminate the loop using the  break statement.

C# While Loop with Break Statement Example Result

This is how we can use break statements with a while loop to terminate loops' execution based on our requirements.

Table of Contents

  • While Loop in C# with Examples
  • Nested While Loop in C# with Examples
  • C# Use Break Statement in While Loop with Example

While Loops in

About while loops.

To repeatedly execute logic, one can use loops. One of the most common loop types in C# is the while loop, which keeps on looping until a boolean condition evaluates to false .

Learn While Loops

Unlock 6 more exercises to practice while loops.

While Loop in C# With Practical Examples

while loop in C# with examples

The ‘while’ loop in C# is a fundamental control flow statement used to execute a block of code repeatedly as long as a specified conditional expression remains true. It is widely utilized in programming to perform repeated tasks efficiently. The structure of a ‘while’ loop includes the ‘while’ keyword followed by a condition enclosed in parentheses and then the block of statements to repeat, enclosed in curly braces.

In practice, the ‘while’ loop checks the truthfulness of the condition before the execution of the code block. If the condition evaluates to true, the loop’s inner statements are executed. After each iteration, the condition is re-evaluated, and the loop continues until the condition returns false. Careful manipulation of the condition is crucial, as incorrect handling can lead to infinite loops, which can cause a program to become unresponsive.

To illustrate the concept, consider an example where a ‘while’ loop is used to iterate through the numbers one to ten and print them to the console. This demonstrates how the loop facilitates repetitive tasks without the need to write the same code multiple times. As the loop executes, it increments a counter variable, and once the variable surpasses ten, the condition becomes false, terminating the loop.

Table of Contents

Understanding While Loops in C#

The while loop in C# is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. The loop executes as long as the condition remains true.

Syntax of While Loops in C#

The while loop consists of the keyword while followed by a condition inside parentheses () and a block of code inside curly braces {} . Below is the basic syntax:

  • condition : A Boolean expression that is evaluated before each iteration. If true , the loop continues; if false , the loop terminates.
  • Code Block : The series of C# statements that run for each iteration of the loop as long as the condition evaluates to true .

Flow of Execution of C# while loop

When a while loop is encountered, C# starts by evaluating the condition. If the condition evaluates to true , the loop’s code block executes. After finishing the block, the condition is evaluated again. This sequence continues until the condition results in false . Here is a step-by-step breakdown:

  • Condition Check : Before every iteration, the while loop evaluates the condition.
  • Code Execution : If the condition is true , it executes the statements within the loop’s block.
  • Re-evaluation : Upon completing the block’s execution, the loop re-evaluates the condition.
  • Loop Termination : If the condition is false , the loop ends, and execution continues with the subsequent code after the loop.

It’s crucial to ensure the condition eventually becomes false ; otherwise, the loop will create an infinite loop, which can cause the program to become unresponsive or terminate unexpectedly. Appropriate mechanisms, like incrementing a counter or changing a variable within the loop, should be in place to break out of the loop.

Working With While Loops in C#

The while loop in C# is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. Understanding its use is fundamental for tasks that require repeated execution until a certain condition is met.

Basic C# While Loop Example

In a basic while loop, the condition is evaluated before the execution of the loop’s body. If the condition evaluates to true , the code inside the loop is executed. This process repeats until the condition becomes false . Below is a simple example:

Here is the complete code on how to use while loop in C#.

In this code, the while loop continues to execute as long as the counter variable is less than 5. Each iteration increments the counter by 1 and outputs its value.

Using Break and Continue

The break and continue statements modify the flow of a while loop in C#.

  • break : Immediately exits the while loop, regardless of the loop’s condition.
  • continue : Skips the remaining code in the current iteration and proceeds with the next iteration of the loop.

Here’s how they can be used within a while loop:

This example demonstrates the continue statement in a case where the counter is odd, skipping over the Console.WriteLine method, and the break statement to exit the loop when the counter reaches 5.

Common Use-Cases of while loop in C#

While loops in C# are frequently utilized in scenarios where one needs to iterate over collections or wait for specific conditions to be met before proceeding with the code execution.

Iterating Over Collections

When one has a collection of items, such as an array or a list, a while loop can be effectively employed to traverse each element. This is particularly useful when the number of iterations isn’t known before entering the loop or when dealing with streams of data.

Waiting for a Condition

A while loop is also used to halt the code’s execution until a certain condition is met. This can be seen in real-time applications such as games or in situations where the program awaits user input or certain events.

Advanced Topics on C# While loop

When diving into advanced topics regarding while loops in C#, a developer should consider the intricacies of nested loops and be aware of the loop’s performance implications.

Nested While Loops in C#

Nested while loops occur when one loop is situated within the body of another. They are a powerful tool for handling multi-dimensional data structures. However, they quickly increase the complexity of the code. For example:

Takeaway: Each iteration of the outer loop triggers the complete execution of the inner loop, leading to a total of i * j iterations.

Performance Considerations

Performance must be assessed when using while loops, especially in scenarios involving large datasets or time-sensitive operations. Monitoring and optimizing the number of loop iterations is crucial to maintain efficiency and prevent potential performance bottlenecks.

  • CPU Utilization: Keep an eye on the processing time for each while loop iteration.
  • Memory Usage: Consider the memory footprint, especially with large or complex data structures within the loop.
  • Algorithm Complexity: Analyze the time complexity (Big O notation) to predict how the loop will scale.

Code Sample:

Best Practice : Implement performance profiling and testing to identify slow portions of the loop. Being methodical in understanding and optimizing these aspects can significantly improve the overall efficiency of the code.

Best Practices for using While Loop in C#

In utilizing while loops in C#, one must vigilantly manage loop conditions and variables to ensure the code is efficient and free from errors that could cause unintended behavior.

Avoiding Infinite Loops

An infinite loop occurs when the terminating condition of a loop will never evaluate to false. To prevent this:

  • Validation: Always validate the loop’s terminating condition before entering the loop.
  • Incrementation: Ensure there is a clear path of progression towards the loop’s exit. Typically, this involves incrementing a counter.

For example :

Loop Control Variables

Proper management of loop control variables is critical for predictable loop behavior:

  • Initialization : Carefully initialize control variables so their starting values align with the loop’s logic.
  • Modification : Adjust control variables inside the loop to avoid premature exit or excessive iterations.

A practical demonstration :

Troubleshooting

Troubleshooting while loops in C# involves two crucial focuses: proper debugging practices and being aware of common pitfalls. These elements are key to ensuring efficient and error-free loop execution.

Debugging While Loops

Identifying Infinite Loops: A primary issue with while loops is the risk of creating an infinite loop, where the loop continues without end.

  • To debug, one must check that the loop condition will eventually become false.
  • Inserting debugging statements within the loop can help determine if and how the loop variables are changing.

Breakpoints: Setting breakpoints within the loop’s body can significantly aid in observing the behavior of your loop during each iteration.

  • Breakpoints can determine if the loop’s logic is executing as intended.
  • They also help observe the changes in variables that affect the loop’s termination condition.

Common Pitfalls

Initialization before Loop:

  • Ensure variables used in the loop’s condition are initialized before the loop starts.
  • Improper initialization may lead to incorrect loop execution or a crash.

Update of Loop Variables:

  • Loop variables must be updated correctly inside the loop. Failing to modify loop control variables leads to infinite loops.

Logical Errors:

  • Be vigilant about logical errors where the loop’s exit condition is never met, even though the code runs without syntax errors.
  • A typical example is using the wrong comparison operator, resulting in unintended loop behavior.

By focusing on these areas, troubleshooting while loops becomes a more manageable and less error-prone process.

The while loop is a fundamental control structure in C# that enables the execution of a block of code repeatedly as long as a specified condition remains true. Developers use this loop for tasks that require repeated execution, where the number of iterations is not known in advance. Correct implementation of while loops ensures efficient code execution and prevents common pitfalls such as infinite loops, which can occur if the loop’s exit condition is never met.

Best Practices include:

  • Ensuring the loop’s condition is modified within the loop, leading to termination.
  • Avoiding complex conditions that obscure the readability of the code.
  • Initializing variables used in the condition prior to entering the loop.

Example Usage:

In the example, the counter variable is incremented with each iteration, ensuring that the loop terminates after 10 iterations.

In this C# tutorial, I have explained how to use while loop in C# with practical examples.

You may also like:

  • Foreach Loop in C#
  • For Loop in C#
  • Do-While Loop in C#

Bijay

Bijay Kumar is a renowned software engineer, accomplished author, and distinguished Microsoft Most Valuable Professional (MVP) specializing in SharePoint. With a rich professional background spanning over 15 years, Bijay has established himself as an authority in the field of information technology. He possesses unparalleled expertise in multiple programming languages and technologies such as ASP.NET, ASP.NET MVC, C#.NET, and SharePoint, which has enabled him to develop innovative and cutting-edge solutions for clients across the globe. Read more…

  • Trending Now
  • Foundational Courses
  • Data Science
  • Practice Problem
  • Machine Learning
  • System Design
  • DevOps Tutorial

While loop in Programming

  • Do-While loop in Programming
  • Loops in Programming
  • For loop in Programming
  • R - while loop
  • Loops in R (for, while, repeat)
  • Bash Scripting - While Loop
  • While loop in Objective-C
  • PostgreSQL - While Loops
  • Difference between For Loop and While Loop in Programming
  • while loop in Perl
  • Python While Loop
  • Perfect Number Program in Java Using While Loop
  • while loop in C
  • Python Do While Loops
  • while Loop in C#
  • PHP while Loop
  • Kotlin while loop
  • PHP do-while Loop
  • How to begin with Competitive Programming?

While loop is a fundamental control flow structure in programming, enabling the execution of a block of code repeatedly as long as a specified condition remains true. While loop works by repeatedly executing a block of code as long as a specified condition remains true. It evaluates the condition before each iteration, executes the code block if the condition is true, and terminates when the condition becomes false. This mechanism allows for flexible iteration based on changing conditions within a program.

Among all loop types, the while loop stands out as a versatile tool, providing flexibility and control over iteration. In this post, we will explore the while loop, its syntax, functionality, and applications across various programming domains.

While loop in Programming

Table of Content

What is While Loop?

  • While Loop Syntax

How does While Loop work?

  • While Loop in Different Programming Languages
  • While loop in Python
  • While loop in JavaScript
  • While loop in Java
  • While loop in C
  • While loop in C++
  • While loop in PHP
  • While loop in C#
  • Use Cases where While Loop is Used
  • While Loop vs Other Loops

The while loop is a fundamental control flow structure (or loop statement ) in programming, enabling the execution of a block of code repeatedly as long as a specified condition remains true. Unlike the for loop, which is tailored for iterating a fixed number of times, the while loop excels in scenarios where the number of iterations is uncertain or dependent on dynamic conditions.

While Loop Syntax:

The syntax of a while loop is straightforward:

The loop continues to execute the block of code within the loop as long as the condition evaluates to true. Once the condition becomes false, the loop terminates, and program execution proceeds to the subsequent statement.

In this syntax:

  • condition is the expression or condition that is evaluated before each iteration. If the condition is true, the code block inside the loop is executed. If the condition is false initially, the code block is skipped, and the loop terminates immediately.
  • The code block inside the loop is indented and contains the statements to be executed repeatedly while the condition remains true.

While loops are particularly useful when the number of iterations is uncertain or dependent on dynamic conditions. They allow for flexible iteration based on changing circumstances within a program.

The while loop is a fundamental control flow structure in programming that allows a block of code to be executed repeatedly as long as a specified condition remains true. Let’s break down how a while loop works step by step:

  • The while loop begins by evaluating a specified condition.
  • If the condition is true, the code block inside the while loop is executed. If the condition is false initially, the code block is skipped, and the loop terminates immediately without executing any code inside.
  • If the condition evaluates to true, the code block inside the while loop is executed.
  • The statements within the code block are executed sequentially, just like in any other part of the program.
  • After executing the code block inside the loop, the condition is re-evaluated.
  • If the condition remains true, the loop iterates again, and the code block is executed again.
  • This process of evaluating the condition, executing the code block, and re-evaluating the condition continues until the condition becomes false.
  • When the condition eventually evaluates to false, the loop terminates.
  • Once the condition is false, the program flow moves to the next statement immediately following the while loop, skipping any code inside the loop.

While Loop in Different Programming Languages:

While loops are fundamental constructs in programming and are supported by virtually all programming languages. While the syntax and specific details may vary slightly between languages, the general concept remains the same. Here’s how while loops are implemented in different programming languages:

1. While loop in Python:

In Python, a while loop is initiated with the keyword while followed by a condition. The loop continues to execute the indented block of code as long as the condition evaluates to True .

Explanation: This Python code initializes a variable count with the value 0 . The while loop then iterates as long as the value of count is less than 5 . Inside the loop, the current value of count is printed, and then count is incremented by 1 in each iteration using the += operator.

Working: The loop starts with count equal to 0 . It prints the value of count (which is 0 ) and then increments count to 1 . This process repeats until count reaches 5 , at which point the condition count < 5 becomes False , and the loop terminates.

2. While loop in JavaScript:

JavaScript’s while loop syntax is similar to Python’s. It starts with the keyword while , followed by a condition enclosed in parentheses. The loop continues executing as long as the condition evaluates to true .

Explanation: This JavaScript code initializes a variable count with the value 0 . The while loop iterates as long as count is less than 5 . Inside the loop, the current value of count is logged to the console using console.log() , and then count is incremented by 1 using the ++ operator.

Working: Similar to Python, the loop starts with count equal to 0 . It logs the value of count to the console (which is 0 ) and then increments count to 1 . This process repeats until count reaches 5 , at which point the loop terminates.

3. While loop in Java:

In Java, a while loop is initiated with the keyword while , followed by a condition enclosed in parentheses. The loop continues executing as long as the condition evaluates to true .

Explanation: This Java code initializes an integer variable count with the value 0 . The while loop iterates as long as count is less than 5 . Inside the loop, the current value of count is printed to the console using System.out.println() , and then count is incremented by 1 using the ++ operator.

Working: The loop starts with count equal to 0 . It prints the value of count (which is 0 ) to the console and then increments count to 1 . This process repeats until count reaches 5 , at which point the loop terminates.

4. While loop in C:

C language while loop syntax is similar to Java. The loop continues executing as long as the condition evaluates to true .

Explanation: This C code initializes an integer variable count with the value 0 . The while loop iterates as long as count is less than 5 . Inside the loop, the current value of count is printed to the console using printf() , and then count is incremented by 1 using the ++ operator.

5. While loop in C++:

C++ while loop syntax is similar to C and Java. The loop continues executing as long as the condition evaluates to true .

Explanation: This C++ code initializes an integer variable count with the value 0 . The while loop iterates as long as count is less than 5 . Inside the loop, the current value of count is printed to the console using std::cout , and then count is incremented by 1 using the ++ operator.

6. While loop in PHP:

PHP while loop syntax is similar to other languages. The loop continues executing as long as the condition evaluates to true .

Explanation: This PHP code initializes a variable $count with the value 0 . The while loop iterates as long as $count is less than 5 . Inside the loop, the current value of $count is echoed to the output, and then $count is incremented by 1 .

Working: The loop starts with $count equal to 0 . It echoes the value of $count (which is 0 ) to the output and then increments $count to 1 . This process repeats until $count reaches 5 , at which point the loop terminates.

7. While loop in C#:

In C#, a while loop is initiated with the keyword while , followed by a condition enclosed in parentheses. The loop continues executing as long as the condition evaluates to true .

Explanation: This C# code initializes an integer variable count with the value 0 . The while loop iterates as long as count is less than 5 . Inside the loop, the current value of count is printed to the console using Console.WriteLine() , and then count is incremented by 1 using the ++ operator.

Each language provides a while loop construct with similar syntax and functionality, enabling developers to express iterative logic effectively.

Use Cases where While Loop is Used:

While loops are used in various scenarios where you need to execute a block of code repeatedly as long as a certain condition remains true. Here are some common use cases where while loops are particularly useful:

  • While loops are often used for input validation, ensuring that users provide valid input before proceeding with further execution.
  • For example, you might use a while loop to repeatedly prompt the user for input until they enter a valid number within a specified range.
  • While loops can be used to iterate over data structures like lists, arrays, or collections, processing each element until a specific condition is met.
  • For example, you might use a while loop to traverse a list of items and perform certain operations on each item until you find a particular element.
  • While loops are useful for handling events or processes that continue to occur until a certain condition changes.
  • For example, you might use a while loop to continuously monitor sensor data or listen for incoming network connections until a stop signal is received.
  • While loops are often used to implement various algorithms, such as searching, sorting, or mathematical calculations.
  • For example, you might use a while loop to implement the binary search algorithm, repeatedly narrowing down the search range until the desired element is found.
  • While loops are commonly used in state machine implementations, where the program transitions between different states based on certain conditions.
  • For example, you might use a while loop to continuously execute the current state’s logic until a transition condition triggers a state change.
  • While loops are essential for controlling the flow of gameplay in interactive applications like games and simulations.
  • For example, you might use a while loop to simulate the main game loop, continuously updating the game state, processing user input, and rendering the game world until the game is over.
  • While loops are used in batch processing scenarios where you need to perform a series of tasks repeatedly until a certain condition is met.
  • For example, you might use a while loop to process a batch of files or database records, continuing until all items have been processed or a specific criteria is fulfilled.

While Loop vs Other Loops:

While loops offer distinct advantages over other loop constructs, such as:

  • Flexibility: While loops excel in scenarios where the number of iterations is unknown or variable.
  • Dynamic Condition Evaluation: The condition in a while loop is re-evaluated before each iteration, offering dynamic control over loop execution.

In conclusion , the while loop emerges as a potent tool in the arsenal of any programmer, providing unmatched versatility and precision in controlling iteration. Mastering the intricacies of the while loop empowers developers to craft elegant, efficient, and robust solutions to a myriad of programming challenges.

Please Login to comment...

Similar reads.

  • Programming

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

IMAGES

  1. While Loop in C# with Examples

    assignment in while loop c#

  2. C# while loop (With Step-By-Step Video Tutorial)

    assignment in while loop c#

  3. C# While Loop

    assignment in while loop c#

  4. How to use For Loop

    assignment in while loop c#

  5. C# While Loop

    assignment in while loop c#

  6. How to use while Loop in C#

    assignment in while loop c#

VIDEO

  1. C#

  2. While Loop Assignment

  3. While-Loop C# , حلقه وايل جميع الفكر المركزيه

  4. 2D Procedural stylized map generator

  5. loops in c# : for loop

  6. C#.NET program to find the Factorial of given number using for, while and do

COMMENTS

  1. c#

    @Saeed: Still -1, because while all we've been shown is the Category property, in real life I'd expect there to be more data in the object... which gets lost with your current code. As the OP says, he wants to remember the object he's just read , not reconstruct it from the one bit of information he's filtering on.

  2. C# while loop explained (+ several examples) · Kodify

    This works because C# assignment also returns the value being assigned. That second part looks if the new value of x is greater than (>) zero. When this test turns up true, ... We can control a while loop with C#'s break and continue keywords. The first stops a loop early, before its condition tests false. With the second we jump to the next ...

  3. C# While Loop

    Arithmetic Assignment Comparison Logical. C# Math C# Strings. ... C# While Loop. The while loop loops through a block of code as long as a specified condition is True: Syntax ... The do/while loop is a variant of the while loop. This loop will execute the code block once, before checking if the condition is true, then it will repeat the loop as ...

  4. C# while Loop Examples

    Here we assign a variable in a while-loop's expression. We can alias a variable for use in the loop body. ... Do While. This is a less common loop in C#. It is an inverted version of the while-loop. It executes the loop statements unconditionally the first time. do while. using System; class Program { static void Main() ...

  5. Iteration statements -for, foreach, do, and while

    Because that expression is evaluated before each execution of the loop, a while loop executes zero or more times. The while loop differs from the do loop, which executes one or more times. The following example shows the usage of the while statement: int n = 0; while (n < 5) { Console.Write(n); n++; } // Output: // 01234 C# language specification

  6. C# while Loop

    C# - while Loop. C# provides the while loop to repeatedly execute a block of code as long as the specified condition returns true . Syntax: While( condition ) {. //code block. } The while loop starts with the while keyword, and it must include a boolean conditional expression inside brackets that returns either true or false. It executes the ...

  7. While Loop in C# with Examples

    Example to understand While loop in C# Language: In the below example, the variable x is initialized with value 1 and then it has been tested for the condition. If the condition returns true then the statements inside the body of the while loop are executed else control comes out of the loop. The value of x is incremented using the ++ operator ...

  8. Understanding and Mastering the While Loop in C# Programming

    The While loop checks a condition before executing the loop. If the condition is True, the code inside the loop will be executed. This will continue until the condition becomes False. Understanding the While Loop; The basic syntax of a While loop is as follows: while (condition) { // code to be executed } Here, the 'condition' is evaluated.

  9. .net

    while((result = Func(x)) != ERR_D) { /* ... */ } The != operator has a higher priority than the assignment, so you need to force the compiler to perform the assignment first (which evaluates to the assigned value in C#), before comparing the values on both sides of the != operator with each other. That's a pattern you see quite often, for ...

  10. while Loop in C#

    while Loop in C#. Looping in a programming language is a way to execute a statement or a set of statements multiple number of times depending on the result of the condition to be evaluated. while loop is an Entry Controlled Loop in C#. The test condition is given in the beginning of the loop and all statements are executed till the given ...

  11. C# while and do...while loop (With Examples)

    do. {. // body of while loop. } while (true); The infinite loop is useful when we need a loop to run as long as our program runs. For example, if your program is an animation, you will need to constantly run it until it is stopped. In such cases, an infinite loop is necessary to keep running the animation repeatedly.

  12. C# while Statement By Practical Examples

    C# while statement examples. Let's take some examples of using the while statement.. 1) Simple C# while statement example. The following example uses the while loop statement to output five numbers from 1 to 5 to the console:. int counter = 0; while (counter < 5) { counter++; Console.WriteLine(counter); } Code language: C# (cs). Output:

  13. While Loop

    Loops are used to repeat a set of instructions based on a set of conditions. If this makes you think of conditional statements, you're not wrong! The while loop looks very similar to an if statement. Just like an if statement, it executes the code inside of it if the condition, a statement that evaluates to a boolean value, is true. statement;

  14. C# While Loop with Examples

    In c#, the While loop is used to execute a block of statements until the specified expression return as true. In the previous chapter, we learned about for loop in c# with examples.Generally, the for loop is useful when we are sure about how many times we need to execute the block of statements. If we are unknown about the number of times to execute the block of statements, then a while loop ...

  15. While Loops in C# on Exercism

    About While Loops. To repeatedly execute logic, one can use loops. One of the most common loop types in C# is the while loop, which keeps on looping until a boolean condition evaluates to false. while (x > 10 ) // Execute logic if x > 10. x = x - 1 ;

  16. c#

    A quick and easy to read way: string line; while((line = myReader.ReadLine()) != null) {. Console.WriteLine(line); } As for the author's snippet of code you provided, line is initialized to an empty string. Because of this, it always will go into the while loop at least one time. Then it grabs a line from the reader, does stuff with it if it ...

  17. While Loop in C# With Practical Examples

    Understanding While Loops in C#. The while loop in C# is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. The loop executes as long as the condition remains true. Syntax of While Loops in C#. The while loop consists of the keyword while followed by a condition inside parentheses and a block of code inside curly braces {}.

  18. for and while loop in c#

    For example 12.3.3.9 of ECMA 334 (definite assignment) dictates that a for loop: for ( for-initializer ; for-condition ; for-iterator ) embedded-statement is essentially equivalent (from a Definite assignment perspective (not quite the same as saying "the compiler must generate this IL")) as:

  19. Is doing an assignment inside a condition considered a code smell?

    Many times I have to write a loop that requires initialization of a loop condition, and an update every time the loop executes. ... Java or C# that I know of to get rid of the duplication between initializer and incrementer. ... however the problem is that you can't clearly understand Why there is an assignment within the while statement unless ...

  20. Why would you use an assignment in a condition?

    The reason is: Performance improvement (sometimes) Less code (always) Take an example: There is a method someMethod() and in an if condition you want to check whether the return value of the method is null. If not, you are going to use the return value again. If(null != someMethod()){. String s = someMethod();

  21. While loop in Programming

    Explanation: This C# code initializes an integer variable count with the value 0.The while loop iterates as long as count is less than 5.Inside the loop, the current value of count is printed to the console using Console.WriteLine(), and then count is incremented by 1 using the ++ operator.. Working: The loop starts with count equal to 0.It prints the value of count (which is 0) to the console ...