計算機科学のブログ

dive into C# - Statements, classes, and code - if、else statements, while loop, for 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.68(Sharpen your pencil)の解答を求めてみる。

コード

using System;

namespace MyFirstConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(TryAnIf() == "this line runs no matter what");
            Console.WriteLine(TrySomeLoops() == 5);
            Console.WriteLine(TryAnIfElse() == "x isn't 10");
        }

        private static string TryAnIf()
        {
            string s = "";
            int someValue = 4;
            string name = "Bobbo Jr.";
            if (someValue == 3 && name == "Joe")
            {
                s += "x is ...";
            }
            s += "this line runs no matter what";
            return s;
        }

        private static string TryAnIfElse()
        {
            string s = "";
            int x = 5;
            if (x == 10)
            {
                s += " x must be 10";
            }
            else
            {
                s += "x isn't 10";
            }
            return s;
        }


        private static int TrySomeLoops()
        {
            int count = 0;
            while (count < 10)
            {
                count++;
            }
            for (int i = 0; i < 5; i++)
            {
                count--;
            }
            return count;
        }
        
    }
}

出力結果

True
True
True