Programming Fundamentals/Loops/C Sharp
loops.cs
edit// 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");
WhileLoop(start, stop, increment);
DoLoop(start, stop, increment);
ForLoop(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 WhileLoop(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 DoLoop(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 ForLoop(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);
}
}
}
Try It
editCopy and paste the code above into one of the following free online development environments or use your own C Sharp compiler / interpreter / IDE.