C# Examples
Dave Braunschweig
Counting
// This program demonstrates While, Do, and For loop counting using // user-designated start, stop, and increment values. // // References: // https://en.wikibooks.org/wiki/C_Sharp_Programming using System; public class Loops { public static void Main(string[] args) { int start = GetValue("starting"); int stop = GetValue("ending"); int increment = GetValue("increment"); DemonstrateWhileLoop(start, stop, increment); DemonstrateDoLoop(start, stop, increment); DemonstrateForLoop(start, stop, increment); } public static int GetValue(string name) { Console.WriteLine("Enter " + name + " value:"); string input = Console.ReadLine(); int value = Convert.ToInt32(input); return value; } public static void DemonstrateWhileLoop(int start, int stop, int increment) { Console.WriteLine("While loop counting from " + start + " to " + stop + " by " + increment + ":"); int count = start; while (count <= stop) { Console.WriteLine(count); count = count + increment; } } public static void DemonstrateDoLoop(int start, int stop, int increment) { Console.WriteLine("Do loop counting from " + start + " to " + stop + " by " + increment + ":"); int count = start; do { Console.WriteLine(count); count = count + increment; } while (count <= stop); } public static void DemonstrateForLoop(int start, int stop, int increment) { Console.WriteLine("For loop counting from " + start + " to " + stop + " by " + increment + ":"); for (int count = start; count <= stop; count += increment) { Console.WriteLine(count); } } }
Output
Enter starting value: 1 Enter ending value: 3 Enter increment value: 1 While loop counting from 1 to 3 by 1: 1 2 3 Do loop counting from 1 to 3 by 1: 1 2 3 For loop counting from 1 to 3 by 1: 1 2 3