C# – Console Input Output

Условия и решения на задачите от лекция “Console Input Output”

Задача 1. Print Sum Of Three Integers

Условие: Write a program that reads 3 integer numbers from the console and prints their sum.

Решение:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace _1.PrintSumOfThreeIntegers
{
    class Program
    {
        static void Main()
        {
            int a, b, c;
            Console.Write("Enter the first number a:");
            bool isaInt = int.TryParse(Console.ReadLine(), out a);
            Console.Write("Enter the second number b:");
            bool isbInt = int.TryParse(Console.ReadLine(), out b);
            Console.Write("Enter the third number c:");
            bool iscInt = int.TryParse(Console.ReadLine(), out c);

            if (isaInt & isbInt & iscInt)
            {
                Console.WriteLine("sum={0}",a+b+c);
            }
            else
            {
                Console.WriteLine("Not a valid entry! Some of the numbers are not integer!");
            }
        }
    }
}

Задача 2. Print Perimeter And Area Of A Circle

Условие: Write a program that reads the radius r of a circle and prints its perimeter and area.

Решение:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace _2.PrintPerimeterAndAreaOfACircle
{
    class Program
    {
        static void Main()
        {
            double r;
            Console.Write("Enter the radius r:");
            bool isrInt = double.TryParse(Console.ReadLine(), out r);

            if (isrInt)
            {
                Console.WriteLine("Perimeter={0}", 2 * Math.PI * r);
                Console.WriteLine("Area={0}", Math.PI * r * r);
            }
            else
            {
                Console.WriteLine("Not a valid entry! r is not integer!");
            }
        }
    }
}

Задача 3. Print Company Info

Условие: A company has name, address, phone number, fax number, web site and manager. The manager has first name, last name, age and a phone number. Write a program that reads the information about a company and its manager and prints them on the console.

Решение:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace _3.PrintCompanyInfo
{
    class Program
    {
        static void Main()
        {
            //has name, address, phone number, fax number, web site and manager. The manager has first name, last name, age and a phone number
            string companyName,address,phoneNumber,faxNumber,webSite,managerFirstName,managerLastName,managerPhoneNumber;
            byte managerAge;
            Console.Write("Enter the name of the company:");
            companyName= Console.ReadLine();
            Console.Write("Enter the address of the company:");
            address = Console.ReadLine();
            Console.Write("Enter the phone number of the company:");
            phoneNumber = Console.ReadLine();
            Console.Write("Enter the fax number of the company:");
            faxNumber = Console.ReadLine();
            Console.Write("Enter the web site of the company:");
            webSite = Console.ReadLine();
            Console.Write("Enter the first name of the manager:");
            managerFirstName = Console.ReadLine();
            Console.Write("Enter the last name of the manager:");
            managerLastName = Console.ReadLine();
            Console.Write("Enter the age of the manager:");
            bool isAgeByte = byte.TryParse(Console.ReadLine(), out managerAge);
            Console.Write("Enter the phone number of the manager:");
            managerPhoneNumber = Console.ReadLine();
            if (isAgeByte)
            {
                Console.WriteLine();
                Console.WriteLine("Company name:".PadRight(23,' ')+"{0,30}".PadRight(30,' '),companyName);
                Console.WriteLine("Address:".PadRight(23, ' ') + "{0,30}".PadRight(30, ' '), address);
                Console.WriteLine("Phone number:".PadRight(23, ' ') + "{0,30}".PadRight(30, ' '), phoneNumber);
                Console.WriteLine("Fax number:".PadRight(23, ' ') + "{0,30}".PadRight(30, ' '), faxNumber);
                Console.WriteLine("Web site:".PadRight(23, ' ') + "{0,30}".PadRight(30, ' '), webSite);
                Console.WriteLine("Manager:".PadRight(23, ' ') + "{0,30}".PadRight(30, ' '), managerFirstName + " " + managerLastName);
                Console.WriteLine("Manager's age:".PadRight(23, ' ') + "{0,30}".PadRight(30, ' '), managerAge);
                Console.WriteLine("Manager's phone number:".PadRight(23, ' ') + "{0,30}".PadRight(30, ' '), managerPhoneNumber);
            }
            else
            {
                Console.WriteLine("Not a valid entry! Manager's age is not a byte number!");
            }

        }
    }
}

Задача 4. Print Number Of Devision By 5 Numbers

Условие: Write a program that reads two positive integer numbers and prints how many numbers p exist between them such that the reminder of the division by 5 is 0 (inclusive). Example: p(17,25) = 2.

Решение:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace _4.PrintNumberOfDevisionBy5Numbers
{
    class Program
    {
        static void Main()
        {
            uint a, b;
            uint p=0;
            Console.Write("Enter the first number a:");
            bool isaUint = uint.TryParse(Console.ReadLine(), out a);
            Console.Write("Enter the second number b:");
            bool isbUint = uint.TryParse(Console.ReadLine(), out b);

            if (isaUint & isbUint)
            {
                if (a < b)
                {
                    for (uint i = a; i <= b; i++)                     {                         if (i % 5 == 0)                         {                             p = p + 1;                         }                     }                 }                 else if (a > b)
                {
                    for (uint i = b; i <= a; i++)
                    {
                        if (i % 5 == 0)
                        {
                            p = p + 1;
                        }
                    }
                }
                else
                {
                    if (a % 5 == 0)
                    {
                        p = p + 1;
                    }
                }
                Console.WriteLine("p({0},{1})={2}",a,b,p);
            }
            else
            {
                Console.WriteLine("Not a valid entry! Some of the numbers are not unsigned integer!");
            }
        }
    }
}

Задача 5. Print The Greater Number

Условие: Write a program that gets two numbers from the console and prints the greater of them. Don’t use if statements.

Решение:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace _5.PrintTheGreaterNumber
{
    class Program
    {
        static void Main()
        {
            double a, b;
            Console.Write("Enter the first number a:");
            bool isaDouble = double.TryParse(Console.ReadLine(), out a);
            Console.Write("Enter the second number b:");
            bool isbDouble = double.TryParse(Console.ReadLine(), out b);
            if (isaDouble & isaDouble)
            {
                Console.WriteLine("The greater number is:{0}", Math.Max(a,b));
            }
            else
            {
                Console.WriteLine("Not a valid entry! Some of the numbers are not double!");
            }
        }
    }
}

Задача 6. Quadratic Equation Solution

Условие: Write a program that reads the coefficients a, b and c of a quadratic equation ax2+bx+c=0 and solves it (prints its real roots).

Решение:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Globalization;

namespace _6.QuadraticEquationSolution
{
    class Program
    {
        static void Main()
        {
            Thread.CurrentThread.CurrentCulture =CultureInfo.InvariantCulture;
            double a, b, c, discriminant,x1,x2;
            Console.Write("Enter the first coefficient a:");
            bool isaDouble = double.TryParse(Console.ReadLine(), out a);
            Console.Write("Enter the second coefficients b:");
            bool isbDouble = double.TryParse(Console.ReadLine(), out b);
            Console.Write("Enter the third coefficients c:");
            bool iscDouble = double.TryParse(Console.ReadLine(), out c);
            if (isaDouble & isbDouble & iscDouble)
            {
                discriminant = (b * b) - (4 * a * c);
                if (discriminant > 0)
                {
                    x1 = (-b + Math.Sqrt(discriminant)) / 2 * a;
                    x2 = (b + Math.Sqrt(discriminant)) / 2 * a;
                    Console.WriteLine("The real roots are:");
                    Console.WriteLine("x1={0}", x1);
                    Console.WriteLine("x2={0}", x2);
                }
                else if (discriminant == 0)
                {
                    x1 = x2 = -b / 2 * a;
                    Console.WriteLine("The real roots are:");
                    Console.WriteLine("x1={0}", x1);
                    Console.WriteLine("x2={0}", x2);
                }
                else
                {
                    Console.WriteLine("There are no real roots!");
                }
            }
            else
            {
                Console.WriteLine("Not a valid entry! Some of the numbers are not double!");
            }

        }
    }
}

Задача 7. Get Number N From Console

Условие: Write a program that gets a number n and after that gets more n numbers and calculates and prints their sum.

Решение:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Globalization;

namespace _7.GetNumberNFromConsole
{
    class Program
    {
        static void Main()
        {
            Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
            uint n;
            double sum=0;
            double inputNumber;
            bool isValidEntry=true;
            Console.Write("Enter the number n:");
            bool isnInt = uint.TryParse(Console.ReadLine(), out n);
            if (isnInt)
            {
                for (int i = 0; i < n; i++)
                {
                    bool isInputNumberDouble = double.TryParse(Console.ReadLine(), out inputNumber);
                    if (isInputNumberDouble)
                    {
                        sum = sum + inputNumber;
                    }
                    else
                    {
                        Console.WriteLine("Not a number entry!");
                        isValidEntry = false;
                        break;
                    }
                }
                if (isValidEntry)
                {
                    Console.WriteLine("sum={0}", sum);
                }
            }
            else
            {
                Console.WriteLine("Not a valid entry! The number n is not integer!");
            }
        }
    }
}

Задача 8. Print N Numbers

Условие: Write a program that reads an integer number n from the console and prints all the numbers in the interval [1..n], each on a single line.

Решение:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace _8.PrintNNumbers
{
    class Program
    {
        static void Main()
        {
            int n;
            Console.Write("Enter the first number n:");
            bool isnInt = int.TryParse(Console.ReadLine(), out n);

            if (isnInt)
            {
                for (int i = 1; i <= n; i++)
                {
                    Console.WriteLine(i);
                }
            }
            else
            {
                Console.WriteLine("Not a valid entry! n is not an integer!");
            }
        }
    }
}

Задача 9. Fibonacci Sequence

Условие: Write a program to print the first 100 members of the sequence of Fibonacci: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, …

Решение:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Numerics;

namespace _9.FibonacciSequence
{
    class Program
    {
        static void Main()
        {
            BigInteger newElement;
            BigInteger[] sequenceMembers = { 0, 1 };
            Console.Write("{0},\n{1},\n", sequenceMembers[0], sequenceMembers[1]);
            for (int i = 0; i < 98; i++)
            {
                newElement = sequenceMembers[0] + sequenceMembers[1];
                Console.WriteLine("{0},",newElement);
                sequenceMembers[0] = sequenceMembers[1];
                sequenceMembers[1] = newElement;
            }
        }
    }
}

Задача 10. Calculate The Sum

Условие: Write a program to calculate the sum (with accuracy of 0.001): 1 + 1/2 – 1/3 + 1/4 – 1/5 + …

Решение:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace _10.CalculateTheSum
{
    class Program
    {
        static void Main()
        {
            float i=2;
            float newMembre;
            float sum=1;
            do
            {
                if (i % 2 == 0)
                {
                    newMembre = 1 / i;
                }
                else
                {
                    newMembre = - 1 / i;
                }
                i++;
                sum = sum + newMembre;
            } while (Math.Abs(newMembre)>0.0001f);
            Console.WriteLine("sum={0:F3}",sum);
        }
    }
}

Задача 11. Falling Rocks

Условие: Implement the „Falling Rocks“ game in the text console. A small dwarf stays at the bottom of the screen and can move left and right (by the arrows keys). A number of rocks of different sizes and forms constantly fall down and you need to avoid a crash.
Exercise 11
Rocks are the symbols ^, @, *, &, +, %, $, #, !, ., ;, – distributed with appropriate density. The dwarf is (O). Ensure a constant game speed by Thread.Sleep(150).
Implement collision detection and scoring system.

Решение:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.IO;
using System.Data;

namespace _11.FallingRocks
{

    class Program
    {
        static void WriteOnPosition(int x, int y, char symbol, ConsoleColor color = ConsoleColor.White)
        {
            Console.SetCursorPosition(x, y);
            Console.ForegroundColor = color;
            Console.Write(symbol);
        }

        static void WriteStringOnPosition(int x, int y, string Message, ConsoleColor color = ConsoleColor.White)
        {
            Console.SetCursorPosition(x, y);
            Console.ForegroundColor = color;
            Console.Write(Message);
        }

        struct Rock
        {
            public int x;
            public int y;
            public ConsoleColor color;
            public char symbol;
        }

        struct Dwarf
        {
            public int x1;
            public int x2;
            public int x3;
            public int y;
            public ConsoleColor color;
            public char firstSymbol;
            public char secondSymbol;
            public char thirdSymbol;
        }

        static void Main(string[] args)
        {
            char[] rockSymbols = { '^', '@', '*', '&', '+', '%', '$', '#', '!', '.', ';', '-' };
            String[] lightColorNames = { "Cyan", "Gray", "Green", "Magenta", "Red", "White", "Yellow" };
            char randomRockSymbol;
            string userName;
            int score = 0;
            Console.BufferHeight = Console.WindowHeight = 30;
            Console.BufferWidth = Console.WindowWidth = 60;
            int playfildWidth = 35;
            Dwarf dwarf = new Dwarf();
            int lives = 3;
            int rockWidth;
            bool lifeTaken = false;
            dwarf.x1 = 23;
            dwarf.x2 = 24;
            dwarf.x3 = 25;
            dwarf.y = Console.WindowHeight - 1;
            dwarf.firstSymbol = '(';
            dwarf.secondSymbol = '0';
            dwarf.thirdSymbol = ')';
            dwarf.color = ConsoleColor.White;
            string[] Names = new string[10];
            int[] gameScores = new int[10];

            Random randomGenerator = new Random();
            List Rocks = new List();
            do
            {
                Console.WriteLine("Please enter your name(maximum 10symbols):");
                userName = Console.ReadLine();
            }
            while (userName.Length > 10);

            while (true)
            {
                Rock newRock = new Rock();
                ConsoleColor consoleColor = new ConsoleColor();

                string randomColorName = lightColorNames[randomGenerator.Next(lightColorNames.Length)];
                consoleColor = (ConsoleColor)Enum.Parse(typeof(ConsoleColor), randomColorName);

                rockWidth = randomGenerator.Next(1, 5);
                randomRockSymbol = rockSymbols[randomGenerator.Next(rockSymbols.Length)];
                newRock.color = consoleColor;
                newRock.x = randomGenerator.Next(0, playfildWidth - 1);
                newRock.y = 0;
                newRock.symbol = randomRockSymbol;

                for (int i = 0; i < rockWidth; i++)
                {
                    Rocks.Add(newRock);
                    if (newRock.x < playfildWidth - 1)                     {                         newRock.x++;                     }                 }                 if (Console.KeyAvailable)                 {                     ConsoleKeyInfo pressedKey = Console.ReadKey(true);                     while (Console.KeyAvailable)                     {                         Console.ReadKey(true);                     }                     if (pressedKey.Key == ConsoleKey.LeftArrow)                     {                         if (dwarf.x1 - 1 >= 0)
                        {
                            dwarf.x1--;
                            dwarf.x2--;
                            dwarf.x3--;
                        }
                    }
                    else if (pressedKey.Key == ConsoleKey.RightArrow)
                    {
                        if (dwarf.x3 + 1 <= playfildWidth - 1)
                        {
                            dwarf.x1++;
                            dwarf.x2++;
                            dwarf.x3++;
                        }
                    }
                }

                List newList = new List();
                for (int i = 0; i < Rocks.Count; i++)
                {
                    Rock oldRock = Rocks[i];
                    Rock rock = new Rock();
                    rock.x = oldRock.x;
                    rock.y = oldRock.y + 1;
                    rock.symbol = oldRock.symbol;
                    rock.color = oldRock.color;
                    if ((rock.x == dwarf.x1 || rock.x == dwarf.x2 || rock.x == dwarf.x3) && rock.y == dwarf.y)
                    {
                        if (lifeTaken == false)
                        {
                            lives--;
                            lifeTaken = true;
                        }
                        rock.symbol = 'x';
                        rock.color = ConsoleColor.Red;

                    }
                    if (rock.y < Console.WindowHeight)
                    {
                        newList.Add(rock);
                    }
                }

                Rocks = newList;
                Console.Clear();

                for (int i = 0; i < Console.WindowHeight; i++)
                {
                    WriteOnPosition(playfildWidth, i, '|', ConsoleColor.Yellow);
                }
                WriteOnPosition(dwarf.x1, dwarf.y, dwarf.firstSymbol, dwarf.color);
                WriteOnPosition(dwarf.x2, dwarf.y, dwarf.secondSymbol, dwarf.color);
                WriteOnPosition(dwarf.x3, dwarf.y, dwarf.thirdSymbol, dwarf.color);

                foreach (Rock rock in Rocks)
                {
                    WriteOnPosition(rock.x, rock.y, rock.symbol, rock.color);
                }

                if (lifeTaken)
                {
                    Rocks.Clear();
                    Thread.Sleep(300);
                }
                WriteStringOnPosition(playfildWidth + 10, Console.WindowHeight - 29, "Lives:");
                WriteStringOnPosition(playfildWidth + 17, Console.WindowHeight - 29, Convert.ToString(lives));
                WriteStringOnPosition(playfildWidth + 2, Console.WindowHeight - 26, userName + ":");
                WriteStringOnPosition(playfildWidth + userName.Length + 3, Console.WindowHeight - 26, Convert.ToString(score));

                if (lives < 1)
                {
                    if (!File.Exists("scoring.txt"))
                    {
                        var scoringFile = File.Create("scoring.txt");
                        scoringFile.Close();
                        TextWriter writeInScoringFile = new StreamWriter("scoring.txt", true);

                        writeInScoringFile.Write("{0}:", userName);
                        writeInScoringFile.Write(Convert.ToString(score, 10).PadLeft(6, '0'));
                        writeInScoringFile.Close();
                    }
                    else
                    {
                        TextWriter writeInScoringFile = new StreamWriter("scoring.txt", true);
                        writeInScoringFile.Write("\n{0}:", userName);
                        writeInScoringFile.Write(Convert.ToString(score, 10).PadLeft(6, '0'));
                        writeInScoringFile.Close();
                    }

                    DataTable NamesScoresTable = new DataTable();
                    NamesScoresTable.Columns.Add("Names");
                    NamesScoresTable.Columns.Add("Scores");

                    string[] scores = System.IO.File.ReadAllLines("scoring.txt");
                    int i;
                    for (i = 0; i < scores.Length; i++)                     {                         string[] nameAndScore = scores[i].Split(':');                         DataRow row = NamesScoresTable.NewRow();                         row["Names"] = nameAndScore[0];                         row["Scores"] = nameAndScore[1];                         NamesScoresTable.Rows.Add(row);                     }                     DataView dataView = NamesScoresTable.DefaultView;                     dataView.Sort = "Scores desc";                     DataTable sortedTable = dataView.ToTable();                     int printPosition = 0;                     DataRow[] rows = sortedTable.Select(string.Empty);                     WriteStringOnPosition(playfildWidth + 2, Console.WindowHeight - 20, "Game over!", ConsoleColor.Red);                     WriteStringOnPosition(playfildWidth + 2, Console.WindowHeight - 13, "Score statistics:", ConsoleColor.Green);                     foreach (DataRow row in rows)                     {                         string scoreInfo;                         if (printPosition > 8)
                        {
                            scoreInfo = String.Format("{0}.{1}{2}", printPosition + 1, row["Names"].ToString().PadRight(9, ' '), Convert.ToString(int.Parse(row["Scores"].ToString())).PadLeft(9, ' '));
                            WriteStringOnPosition(playfildWidth + 2, Console.WindowHeight - 12 + printPosition, scoreInfo);
                        }
                        else
                        {
                            scoreInfo = String.Format("{0}.{1}{2}", printPosition + 1, row["Names"].ToString().PadRight(10, ' '), Convert.ToString(int.Parse(row["Scores"].ToString())).PadLeft(9, ' '));
                            WriteStringOnPosition(playfildWidth + 2, Console.WindowHeight - 12 + printPosition, scoreInfo);
                        }
                        printPosition++;
                        if (printPosition > 9)
                        {
                            break;
                        }
                    }
                    break;
                }

                lifeTaken = false;
                score++;
                Thread.Sleep(150);
            }
            WriteStringOnPosition(playfildWidth + 2, Console.WindowHeight - 19, "Press any key to exit.");
            Console.ReadKey();
        }
    }
}

Оставете коментар

Вашият имейл адрес няма да бъде публикуван. Задължителните полета са отбелязани с *