11.1 Looping with the while , do , for , continue and break keywordsThe use of these keywords in looping is identical in Java and C# (with some exceptions with the break and continue keywords). There follows some examples for completeness. Feel free to skip this section if you are already familiar using looping with these keywords in Java. 11.1.1 Use of while in loopsHere is an example of a while loop in C#. 30: public static void PrintNumbersUsingWhile(){ 31: int i=0; 32: while (i<10) 33: Console.WriteLine(i++); 34: } PrintNumbersUsingWhile() prints out the numbers 0 to 9. Here is another example. 30: public static void GetUserInputUsingWhile(){ 31: Console.WriteLine("You must enter Y to return"); 32: string UserInput = Console.ReadLine(); //read keyboard 33: while (true){ 34: if (UserInput.Equals("Y")) 35: break; 36: Console.WriteLine("You must enter Y to return"); 37: UserInput = Console.ReadLine(); 38: } 39: return; 40: } GetUserInputUsingWhile() reads a string from the keyboard (line 32), and goes into a infinite while loop (line 33), breaking out only when the string the user enters is a capital 'Y'. Like Java
Unlike JavaYou cannot use the break and continue keywords together with labels (see section 11.5). 11.1.2 Use of do and while in loopsHere is an example of a do ... while loop in C#. 30: public static void GetUserInputUsingDoWhile(){ 31: string UserInput; 31: do { 35: Console.WriteLine("You must enter Y to return"); 32: UserInput = Console.ReadLine(); 36: } while (!UserInput.Equals("Y")); 38: return; 39: } GetUserInputUsingDoWhile() is functionally identical to GetUserInput UsingWhile() in the previous section, except that the former uses do...while instead of just a while construct. 11.1.3 Use of for in loopsHere is an example of a for loop in C#. 30: public static void PrintNumbersUsingFor(){ 31: for (int i=0; i<10; i++) 32: Console.WriteLine(i++); 33: } PrintNumbersUsingFor() prints out the numbers 0 to 9. Like Java
|