計算機科学のブログ

dive into C# - Statements, classes, and code - for loop, while loop

Head First C#: A Learner’s Guide to Real-World Programming with C# and .NET Core (Andrew Stellman(著)、Jennifer Greene(著)、O’Reilly Media)のChapter 2(dive into C# - Statements, classes, and code)、p.65(Sharpen your pencil)の解答を求めてみる。

コード

using System;

namespace MyFirstConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            int count = 5;
            while (count > 0)
            {
                count *= 3;
                count *= -1;
            }
            Console.WriteLine(count == -15);

            int j = 2;
            count = 0;
            for (int i = 1; i < 100; i *= 2)
            {
                j--;
                while (j < 25)
                {
                    j += 5;
                    count++;
                }
            }
            Console.WriteLine(count == 6);

            count = 0;
            int p = 2;
            for (int q = 2; q < 32; q *= 2)
            {
                while (p < q)
                {
                    p *= 2;
                }
                q = p - q;
                count++;
            }
            Console.WriteLine(count == 8);
            Console.WriteLine("Loop #4と#5は無限ループ");
        }
    }
}

出力結果

True
True
True
Loop #4と#5は無限ループ