Executing Code with the while Statement - CSharp Language Basics

CSharp examples for Language Basics:while

Introduction

The while command is used to repeat a block of code as long as a condition is true.

The format of the while statement is as follows

while ( condition )
{
   Statement(s)
}

Using the while statement to print the average of 10 random numbers that are from 1 to 10.

Demo Code

class average//from   w  w  w . ja  v a  2s  .c o  m
{
   public static void Main()
   {
      int ttl = 0;  // variable to store the running total
      int nbr = 0;  // variable for individual numbers
      int ctr = 0;  // counter
      System.Random rnd = new System.Random();  // random number
      while ( ctr < 10 )
      {
         nbr = (int) rnd.Next(1,11);
         System.Console.WriteLine("Number {0} is {1}", (ctr + 1), nbr);
         ttl += nbr;        //add nbr to total
         ctr++;             //increment counter
      }
      System.Console.WriteLine("\nThe total of the 10 numbers is {0}", ttl);
      System.Console.WriteLine("\nThe average of the numbers is {0}", ttl/10 );
   }
}

Result


Related Tutorials