プログラミング(Python、Perl、C、Go、JavaScript)、数学、読書…
開発環境
"初めてのC# 第2版"の第5章(実行制御)の5.5(練習問題)を解いてみる。
練習 5-1
whileステートメント
using System; public class Tester { public void Run() { int counter = 1; while (counter <= 10) { Console.WriteLine("カウンター値: " + counter); counter++; } } public static void Main() { Tester t = new Tester(); t.Run(); } }
do. . .whileステートメント
using System; public class Tester { public void Run() { int counter = 1; do { Console.WriteLine("カウンター値: " + counter); counter++; } while (counter <= 10); } public static void Main() { Tester t = new Tester(); t.Run(); } }
forステートメント
using System; public class Tester { public void Run() { for (int counter = 1; counter <= 10; counter++) { Console.WriteLine("カウンター値: " + counter); } } public static void Main() { Tester t = new Tester(); t.Run(); } }
出力結果
カウンター値: 1 カウンター値: 2 カウンター値: 3 カウンター値: 4 カウンター値: 5 カウンター値: 6 カウンター値: 7 カウンター値: 8 カウンター値: 9 カウンター値: 10 続行するには何かキーを押してください . . .
練習 5-2
ifステートメント
using System; public class Tester { public void Run() { Console.Write("数値を入力してください>>"); string s = Console.ReadLine(); int num = Convert.ToInt32(s); Console.Write("{0}は", num); if (num >= 100) { Console.WriteLine("大きすぎる値です"); } else if (num % 10 == 0) { Console.WriteLine("10の倍数です"); } else if (num % 2 == 0) { Console.WriteLine("偶数です"); } else { Console.WriteLine("奇数です"); } } public static void Main() { Tester t = new Tester(); t.Run(); } }
switchステートメント
using System; public class Tester { enum type { even, odd, ten, big, }; public void Run() { Console.Write("数値を入力してください>>"); string s = Console.ReadLine(); int num = Convert.ToInt32(s); type condtion; if (num >= 100) { condtion = type.big; } else if (num % 10 == 0) { condtion = type.ten; } else if (num % 2 == 0) { condtion = type.even; } else { condtion = type.odd; } Console.Write("{0}は", num); switch (condtion) { case type.big: Console.WriteLine("大きすぎる値です"); break; case type.ten: Console.WriteLine("10の倍数です"); break; case type.even: Console.WriteLine("偶数です"); break; case type.odd: Console.WriteLine("奇数です"); break; } } public static void Main() { Tester t = new Tester(); t.Run(); } }
練習 5-3
using System; public class Tester { public void Run() { for (int i = 0, j = 25; i <= j; i++, j--) { Console.WriteLine("i={0} j={1}", i, j); } Console.WriteLine("交差しました!"); } public static void Main() { Tester t = new Tester(); t.Run(); } }
i=0 j=25 i=1 j=24 i=2 j=23 i=3 j=22 i=4 j=21 i=5 j=20 i=6 j=19 i=7 j=18 i=8 j=17 i=9 j=16 i=10 j=15 i=11 j=14 i=12 j=13 交差しました! 続行するには何かキーを押してください . . .
0 コメント:
コメントを投稿