using System;
namespace ConsoleSimpleSuanFa
{
/// <summary>
/// C#简单算法(循环,递归)
/// LDH @ 2021-4-12
/// </summary>
internal class Program
{
private static void Main()
{
Console.Title = "C#中简单循环和递归示例";
var calculator = new Calculator();
Console.WriteLine("【循环实现】从10到1输出如下:");
calculator.PrintXTo1(10);
PrintLine();
Console.WriteLine("【递归实现】从10到1输出如下:");
calculator.PrintXToOne(10);
PrintLine();
Console.WriteLine($"【循环实现】从1-100的和:{calculator.SumFrom1ToX(100)}");
PrintLine();
Console.WriteLine($"【递归实现】从1-100的和:{calculator.SumFromOneToX(100)}");
PrintLine();
Console.ReadKey();
}
/// <summary>
/// 完美分割线
/// </summary>
private static void PrintLine()
{
Console.WriteLine("—————————————————— 我是最完美的分割线 ——————————————————");
}
}
internal class Calculator
{
/// <summary>
/// 从指定数字到1输出【循环实现】
/// </summary>
/// <param name="x">指定数字</param>
public void PrintXTo1(int x)
{
for (var i = x; i > 0; i--) Console.WriteLine(i);
}
/// <summary>
/// 从指定数字到1输出【递归实现】
/// </summary>
/// <param name="x">指定数字</param>
public void PrintXToOne(int x)
{
if (x == 1)
{
Console.WriteLine(x);
}
else
{
Console.WriteLine(x);
PrintXToOne(x - 1);
}
}
/// <summary>
/// 从1指定数字的和【循环实现】
/// </summary>
/// <param name="x">指定数字</param>
public int SumFrom1ToX(int x)
{
var sum = 0;
for (var i = 0; i < x + 1; i++) sum += i;
return sum;
}
/// <summary>
/// 从1指定数字的和【递归实现】
/// </summary>
/// <param name="x">指定数字</param>
public int SumFromOneToX(int x)
{
if (x == 1) return 1;
var sum = x + SumFromOneToX(x - 1);
return sum;
}
}
}