DevAcademia
C++C#CPythonJava
  • C# Basics

  • C# Introduction
  • C# Get Started
  • C# Syntax
  • C# Output
  • C# Comments
  • C# Variables
  • C# Data Types
  • C# Type Casting
  • C# User Input
  • C# Operators
  • C# Math
  • C# Strings
  • C# Booleans
  • C# If...Else
  • C# Switch Statement
  • C# While Loop
  • C# For Loop
  • C# Break and Continue
  • C# Arrays
  • C# Files
  • C# OOP

  • C# OOP Introduction
  • C# Classes and Objects
  • C# Class Members
  • C# Constructors
  • C# Destructors
  • C# Access Modifiers
  • C# Properties
  • C# Inheritance
  • C# Polymorphism
  • C# Abstraction
  • C# Interfaces
  • C# Enums
  • C# Exceptions
  • C# Quizzes

  • C# Quiz Introduction
  • C# Basics

  • C# Introduction
  • C# Get Started
  • C# Syntax
  • C# Output
  • C# Comments
  • C# Variables
  • C# Data Types
  • C# Type Casting
  • C# User Input
  • C# Operators
  • C# Math
  • C# Strings
  • C# Booleans
  • C# If...Else
  • C# Switch Statement
  • C# While Loop
  • C# For Loop
  • C# Break and Continue
  • C# Arrays
  • C# Files
  • C# OOP

  • C# OOP Introduction
  • C# Classes and Objects
  • C# Class Members
  • C# Constructors
  • C# Destructors
  • C# Access Modifiers
  • C# Properties
  • C# Inheritance
  • C# Polymorphism
  • C# Abstraction
  • C# Interfaces
  • C# Enums
  • C# Exceptions
  • C# Quizzes

  • C# Quiz Introduction

Loading Cs tutorial…

Loading content
C# BasicsTopic 30 of 55
←PreviousPrevNextNext→

C# While Loop

Introduction to While Loop

A while loop in C# repeats a block of code as long as a given condition is true.

It is useful when the number of iterations is not known in advance.

Syntax of While Loop

The condition is checked before each iteration.

If the condition evaluates to false initially, the loop body will not run at all.

Example
using System;

namespace WhileLoopExample
{
    class Program
    {
        static void Main(string[] args)
        {
            int i = 0;

            while (i < 5)
            {
                Console.WriteLine($"i = {i}");
                i++;
            }
        }
    }
}
Output
i = 0
i = 1
i = 2
i = 3
i = 4

Infinite While Loop

If the condition in a while loop never becomes false, the loop will run infinitely.

Be careful to include logic that eventually ends the loop.

Example
using System;

namespace InfiniteWhile
{
    class Program
    {
        static void Main(string[] args)
        {
            int count = 0;

            while (true)
            {
                Console.WriteLine($"Count = {count}");
                count++;
                if (count >= 3)
                {
                    break;
                }
            }
        }
    }
}
Output
Count = 0
Count = 1
Count = 2
Test your knowledge: C# While Loop
Quiz Configuration
4 of 8 questions
Sequential
Previous allowed
Review enabled
Early close allowed
Estimated time: 5 min
C# BasicsTopic 30 of 55
←PreviousPrevNextNext→