Advertisement
n4wn4w

C# metodi

Apr 15th, 2015
322
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 34.80 KB | None | 0 0
  1.  metodi ///////////////////////////////////
  2.  
  3. class Program
  4.     {
  5.         static void Main(string[] args)
  6.         {
  7.            
  8.         for (int i = 1; i <= 10; i+=2)
  9.         {
  10.             PrintHyphens(count :i + 3, ch: '#');
  11.         }
  12.     }
  13.  
  14.     static void PrintHyphens(int count = 6, char ch = '-')
  15.     {
  16.         for (int i = 0; i < count; i++)
  17.         {
  18.             Console.Write('%');
  19.         }
  20.         Console.WriteLine();
  21.        
  22.     }
  23.  
  24. //// metodhs/////////////
  25.  
  26.  
  27.             Console.Write("Enter triangle width: ");
  28.             double w = double.Parse(Console.ReadLine());
  29.             Console.Write("Enter triangle height: ");
  30.             double h = double.Parse(Console.ReadLine());
  31.             Console.Write("Enter triangle height: ");
  32.             double hui = double.Parse(Console.ReadLine());
  33.  
  34.             Console.WriteLine(CalcTriangleArea(w, h, hui));
  35.         }
  36.  
  37.  
  38.          static double CalcTriangleArea(double width, double height, double hui)
  39.         {
  40.             double area = ((width * height) + hui) / 2;
  41.             return area;
  42.         }
  43.  
  44.  
  45. //////////  print logo //////////
  46.  
  47. {
  48.             PrintLogo();
  49.         }
  50.  
  51.  
  52.       static void PrintLogo()
  53.          {
  54.         Console.WriteLine("Telerik Corp.");
  55.         Console.WriteLine("www.telerik.com");
  56.         }
  57.  
  58.  
  59. //////////////// metodi s if else  max ////
  60.  
  61. static void PrintSign(int number)
  62.         {
  63.             if (number > 0)
  64.             {
  65.                 Console.WriteLine("The number {0} is positive.", number);
  66.             }
  67.             else if (number < 0)
  68.             {
  69.                 Console.WriteLine("The number {0} is negative.", number);
  70.             }
  71.             else
  72.             {
  73.                 Console.WriteLine("The number {0} is zero.", number);
  74.             }
  75.         }
  76.  
  77.         static float PrintMax(float number1, float number2)
  78.         {
  79.             float max = number1;
  80.             if (number2 > number1)
  81.                 max = number2;
  82.            // Console.WriteLine("Maximal number: {0}", max);
  83.             return max;
  84.         }
  85.  
  86.  
  87.         static void Main()
  88.         {
  89.             Console.Write("n = ");
  90.             int n = int.Parse(Console.ReadLine());
  91.  
  92.             Console.Write("m = ");
  93.             int m = int.Parse(Console.ReadLine());
  94.  
  95.             PrintSign(n);
  96.             PrintSign(m);
  97.             Console.WriteLine(PrintMax(n, m));
  98.         }
  99.  
  100.  
  101. /////////////////////////////////////    moi metod :D //////////////////////////////////////
  102.  
  103.  
  104.         static void Main()
  105.         {
  106.             string[] STRnumbers = Console.ReadLine().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
  107.  
  108.             int[] nums = new int[STRnumbers.Length];
  109.             nums = Array.ConvertAll<string, int>(STRnumbers, int.Parse);
  110.             int[] kur = new int[0];
  111.             kur = PrintMax(nums);
  112.        
  113.             for (int i = 0; i < 1; i++)
  114.             {
  115.                 Console.WriteLine(kur[i] + " ");
  116.             }
  117.         }
  118.          
  119.         public static int[] PrintMax(int[] number1)
  120.         {
  121.             int max = 0;
  122.             for (int i =0; i < number1.Length; i++)
  123.             {
  124.                int num = number1[i];
  125.                 if(max < num)
  126.                 {
  127.                     max = num;
  128.                 }            
  129.             }
  130.             int[] result = max.ToString().Select(m => Convert.ToInt32(max)).ToArray();
  131.             return result;            
  132.         }
  133.  
  134. //////////////////  MONTH demo  /////////
  135.  
  136.  class Program
  137.     {
  138.         static void SayMonth(int month)
  139.     {
  140.         string[] monthNames = new string[]
  141.         {
  142.             "January", "February", "March", "April", "May", "June",
  143.             "July", "August", "September", "October", "November", "December"
  144.         };
  145.         string monthName = monthNames[month - 1];
  146.         Console.Write(monthName);
  147.     }
  148.  
  149.     static void SayPeriod(int startMonth, int endMonth)
  150.     {
  151.         int period = endMonth - startMonth;
  152.         period = period < 0 ? period = period + 12 : period = period;// moje i ternaren operator moje i string if/else
  153.         //if (period < 0)
  154.         //{
  155.     //      period = period + 12;
  156.             // From December to January the
  157.             // period is 1 month, not -11 !
  158.     //  }
  159.  
  160.         Console.Write("There are {0} months from ", period);
  161.         SayMonth(startMonth);
  162.         Console.Write(" to ");
  163.         SayMonth(endMonth);
  164.         Console.WriteLine(".");
  165.     }
  166.  
  167.     static void Main()
  168.     {
  169.         Console.Write("First month (1-12): ");
  170.         int firstMonth = int.Parse(Console.ReadLine());
  171.  
  172.         Console.Write("Second month (1-12): ");
  173.         int secondMonth = int.Parse(Console.ReadLine());
  174.  
  175.         SayPeriod(firstMonth, secondMonth);
  176.     }
  177.  
  178.  
  179. /////////////// print triangle DEMO
  180.  
  181. static void Main()
  182.         {
  183.             Console.Write("n = ");
  184.             int n = int.Parse(Console.ReadLine());
  185.             Console.WriteLine();
  186.  
  187.             PrintTriangle(n);
  188.            
  189.         }
  190.  
  191.         private static void PrintLine(int start, int end)
  192.         {
  193.             for (int i = start; i <= end; i++)
  194.             {
  195.                 Console.Write(" {0}", i);
  196.             }
  197.             Console.WriteLine();
  198.         }
  199.  
  200.          static void PrintTriangle(int start)
  201.         {
  202.  
  203.             for (int line = 1; line <= start; line++)
  204.             {
  205.                 PrintLine(1, line);
  206.             }
  207.             for (int line = start - 1; line >= 1; line--)
  208.             {
  209.                 PrintLine(1, line);
  210.             }
  211.         }
  212.  
  213. ///////////////////   optimal parameter ////////////////////
  214.  
  215. static void PrintNumbers(int start = 0, int end = 20)
  216.     {
  217.         for (int i = start; i <= end; i++)
  218.         {
  219.             Console.Write("{0} ", i);
  220.         }
  221.         Console.WriteLine();
  222.     }
  223.  
  224.     static void Main()
  225.     {
  226.         PrintNumbers(5, 10);
  227.         PrintNumbers(15);
  228.         PrintNumbers();
  229.         PrintNumbers(end: 40, start: 35);
  230.     }
  231. }
  232.  
  233.  
  234. //////////////  return demo
  235.  
  236.  static double FahrenheitToCelsius(double degrees)
  237.         {
  238.             double celsius = (degrees - 32) * 5 / 9;
  239.             return celsius;
  240.         }
  241.  
  242.         static void Main()
  243.         {
  244.             Console.WriteLine("Enter your body temperature in Fahrenheit degrees: ");
  245.             double temperature = Double.Parse(Console.ReadLine());
  246.  
  247.             temperature = FahrenheitToCelsius(temperature);
  248.  
  249.             Console.WriteLine("Your body temperature in Celsius degrees is {0}.", temperature);
  250.  
  251.             if (temperature >= 37)
  252.             {
  253.                 Console.WriteLine("You are ill!");
  254.             }
  255.         }
  256.  
  257.  
  258. ///////////////////// bool return  ////////////////
  259.  
  260.  
  261.   static bool AreAllPositive(int[] sequence)
  262.         {
  263.  
  264.             for (int i = 0; i < sequence.Length; i++)
  265.             {
  266.                 if (sequence[i] <= 0)
  267.                 {
  268.                     return false;
  269.                 }
  270.                
  271.             }
  272.            
  273.             return true;
  274.         }
  275.  
  276.         static void Main()
  277.         {
  278.             Console.Write("Number of elements = ");
  279.  
  280.             string[] STRnumbers = Console.ReadLine().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
  281.  
  282.             int[] nums = new int[STRnumbers.Length];
  283.             nums = Array.ConvertAll<string, int>(STRnumbers, int.Parse);
  284.  
  285.             bool allPositive = AreAllPositive(nums);
  286.             if (allPositive == true)
  287.             {
  288.                 Console.WriteLine("All array elements are positive.");
  289.             }
  290.             else
  291.             {
  292.                 Console.WriteLine("Not all array elements are positive.");
  293.             }
  294.         }
  295.  
  296. ///////////////// HOMEWORKS   //////////////////////////
  297.  
  298.  
  299. Problem 1. Say Hello  ////////////////////////////////////////////////////////////////
  300.  
  301. static void SayHello(string name)
  302.         {
  303.             Console.WriteLine("Hello {0}", name);
  304.         }
  305.  
  306.         static void Main(string[] args)
  307.         {
  308.             Console.WriteLine("Pleas enter your name");
  309.             SayHello(Console.ReadLine());
  310.         }
  311.  
  312.  
  313. Problem 2. Get largest number ////////////////////////////////////////////////
  314.  
  315.  
  316.  static int GetMax(int a, int b)
  317.         {
  318.             return a > b ? a : b;
  319.         }
  320.  
  321.         static void Main(string[] args)
  322.         {
  323.             Console.WriteLine("Insert 3 numbers to compare them:");
  324.  
  325.             int a = int.Parse(Console.ReadLine());
  326.             int b = int.Parse(Console.ReadLine());
  327.             int c = int.Parse(Console.ReadLine());
  328.  
  329.             Console.Write("The bigest of three is: ");
  330.             Console.WriteLine(GetMax(GetMax(a, b), c));
  331.         }
  332.  
  333.  
  334.  
  335. Problem 3. English digit //////////////////////////////////////////////////////////////////
  336.  
  337. static void Main(string[] args)
  338.         {
  339.             Console.WriteLine("enter a number");
  340.             int number = int.Parse(Console.ReadLine());
  341.             string word = ReturnAsWord(number);
  342.             Console.WriteLine(word);
  343.         }
  344.         static string ReturnAsWord(int number)
  345.         {
  346.             int lastDigit = number % 10;
  347.             string word = "";
  348.             switch (lastDigit)
  349.             {
  350.                 case 0: word = "zero"; break;
  351.                 case 1: word = "one"; break;
  352.                 case 2: word = "two"; break;
  353.                 case 3: word = "three"; break;
  354.                 case 4: word = "four"; break;
  355.                 case 5: word = "five"; break;
  356.                 case 6: word = "six"; break;
  357.                 case 7: word = "seven"; break;
  358.                 case 8: word = "eight"; break;
  359.                 case 9: word = "nine"; break;
  360.                 case 10: word = "ten"; break;
  361.                 default:
  362.                     break;
  363.             }
  364.             return word;
  365.         }
  366.  
  367. //ОБЯСНЕНИЕ: За създаването на този метод, реших да използвам един класически switch-case. Делим числото, така че да му вземем остатъка и го
  368. //сравняваме по switch-овете, докато не намерим случая, който ни трябва. ReturnAsWord методът ни връща стрига, който ни е необходим и го засилва към
  369. //Main метода, където ни чака един Console.WriteLine,за да го изпечата на конзолата.
  370.  
  371.  
  372.  
  373.  
  374. Problem 4. Appearance count ////////////////////////////////////////////////////////
  375.  
  376. public static int CountAppearances(int[] array, int searchedNumber)
  377.         {
  378.             int counter = 0;
  379.             for (int i = 0; i < array.Length; i++)
  380.             {
  381.                 if (array[i] == searchedNumber)
  382.                 {
  383.                     counter++;
  384.                 }
  385.             }
  386.             return counter;
  387.         }
  388.  
  389.         static void Main(string[] args)
  390.         {
  391.             Console.WriteLine("Enter the length of the array");
  392.             int n = int.Parse(Console.ReadLine());
  393.             int[] array = new int[n];
  394.  
  395.             Console.WriteLine("Enter the Array indexes:");
  396.             for (int i = 0; i < n; i++)
  397.             {
  398.                 Console.Write("Array[{0}] ", i);
  399.                 array[i] = int.Parse(Console.ReadLine());
  400.             }
  401.  
  402.             Console.WriteLine("Enter the number to check it's appearances in the array");
  403.             int searchedNumber = int.Parse(Console.ReadLine());
  404.          
  405.             CountAppearances(array, searchedNumber);
  406.             Console.WriteLine("The number {0} appears {1} times in the array", searchedNumber, CountAppearances(array, searchedNumber));
  407.  
  408.         }
  409.     }
  410. }
  411.  
  412. //ОБЯСНЕНИЕ: Методът, който трябва да създадем за тази задача трябва да провери колко пъти един елемент се съдържа в даден масив от числа.
  413. //Декларираме си един CountAppearances метод, в чието условие body кодът е много прост - for цикъл, който обхожда цикъла
  414. //и сравнява елемент по елемент, дали числото което търсим се съдържа в него. В променливата counter отброяваме броя на съвпаденията, ако такива има.
  415.  
  416.  
  417. Problem 5. Larger than neighbours //////////////////////////////////////////////////////
  418.  
  419.  
  420. private static void CheckByIndexNeighbors(int n, int[] array, int position)
  421.         {
  422.             if (position == 0 || position == array.Length - 1)
  423.             {
  424.                 Console.WriteLine("Number {0} on index {1} has only one neighbor!", array[position], position);
  425.             }
  426.             else if (array[position] > array[position - 1] && array[position] > array[position + 1])
  427.             {
  428.                 Console.WriteLine("Number {0} on index {1} is bigger than its two neighbors", array[position], position);
  429.             }
  430.             else if (array[position] < array[position - 1] || array[position] < array[position + 1])
  431.             {
  432.                 Console.WriteLine("Number {0} on index {1} is smaller than at least one of its two neighbors", array[position], position);
  433.             }
  434.             else
  435.             {
  436.                 Console.WriteLine("Number {0} on index {1} is equal to its two neighbors", array[position], position);
  437.             }
  438.         }
  439.  
  440.         static void Main(string[] args)
  441.         {
  442.             Console.WriteLine("Enter the length of the array");
  443.             int n = int.Parse(Console.ReadLine());
  444.             int[] array = new int[n];
  445.  
  446.             Console.WriteLine("Enter the Array indexes:");
  447.             for (int i = 0; i < n; i++)
  448.             {
  449.                 Console.Write("Array[{0}] ", i);
  450.                 array[i] = int.Parse(Console.ReadLine());
  451.             }
  452.  
  453.             Console.WriteLine("Enter the postion of element in the array to check");
  454.             int position = int.Parse(Console.ReadLine());
  455.  
  456.             CheckByIndexNeighbors(n, array, position);
  457.         }
  458.  
  459. //ОБЯСНЕНИЕ: Целта на задачата е да по избран индекс от масива да сравним числото, което се намира на тази позиция дали е по-голямо от съседните числа, намиращи се на съседните индекси.
  460. //Правим си един метод, в който изнасяме всички условия. Едни от най-важните са да проверим дали въведения индекс не е първия или последния индекс от масива, защото ако това е така, това означа, че
  461. //просто няма елемнти, които до га обграждат и дефакто няма как да проверим условието на задачата.
  462.  
  463. Problem 6. First larger than neighbours /////////////////////////////////////////////
  464.  
  465.  
  466.  public static bool CheckBiggerThanNeighbors(int[] array, int index)
  467.         {
  468.             if (array[index - 1] < array[index] && array[index] > array[index + 1])
  469.             {
  470.                 return true;
  471.             }
  472.             else
  473.             {
  474.                 return false;
  475.             }
  476.         }
  477.  
  478.         public static int ReturnIndexOfFirstBiggest(int[] numbers)
  479.         {
  480.             for (int i = 1; i < numbers.Length - 2; i++)
  481.             {
  482.                 if (CheckBiggerThanNeighbors(numbers, i) == true)
  483.                 {
  484.                     return i;
  485.                 }
  486.             }
  487.             return -1;
  488.         }
  489.  
  490.         static void Main(string[] args)
  491.         {
  492.             Console.WriteLine("Enter the length of the array");
  493.             int n = int.Parse(Console.ReadLine());
  494.             int[] array = new int[n];
  495.  
  496.             Console.WriteLine("Enter the Array indexes:");
  497.             for (int i = 0; i < n; i++)
  498.             {
  499.                 Console.Write("Array[{0}] ", i);
  500.                 array[i] = int.Parse(Console.ReadLine());
  501.             }
  502.             Console.WriteLine("The first element in array that is bigger than its neighbors is: {0}", ReturnIndexOfFirstBiggest(array));
  503.         }
  504.     }
  505. }
  506. //ОБЯСНЕНИЕ: Тук задачате е почти аналогична на предходната с единсвената разлика, че трябва да намерим първия индекс в масива, чийто елемент е по-голям от обграждащите го. Ако няма такъв елемент, то програмата
  507. //трябва да върне "-1". Естествено ще си използваме метода от предишната задача, като за по интересно реших да си го изнеса даже в отделен клас.
  508.  
  509.  
  510.  
  511. Problem 7. Reverse number
  512.  
  513.  class MethodReversesDigits
  514.     {
  515.         public static int ReverseNumber(int number)
  516.         {
  517.             int tempNumber = 0;
  518.             while (number > 0)
  519.             {
  520.                 tempNumber = (tempNumber * 10) + (number % 10);
  521.                 number /= 10;
  522.             }
  523.             return tempNumber;
  524.         }
  525.  
  526.         static void Main(string[] args)
  527.         {
  528.             Console.WriteLine("Enter the number to reverse");
  529.             int number = int.Parse(Console.ReadLine());
  530.             Console.WriteLine(ReverseNumber(number));
  531.         }
  532.     }
  533. }
  534.  
  535. //ОБЯСНЕНИЕ: доста лесна задача на нивото от C# part 1. Четем число от конзолата, на което да обърнем числата.
  536. //В ReverseNumber метода използваме просто while условие, в което изпълняваме просто условие, чиято същина са особеностите на оператора
  537. //"%" (т.нар. делиение с остатък, при което като разделим остава числото след запетаята) и "/" (т.нар. целочислено деление, при което след разделянето остава числото преди запетаята).
  538. //След изпълнението на while цикъла, променливата tempNumber съдържа вече обърнатото число и след това го печатаме на конзолата.
  539.  
  540.  
  541.  
  542.  
  543. Problem 8. Number as array /////////////////////////////////////////////////////////////
  544.  
  545.  
  546.             byte[] firstArray = { 5, 2, 1, 7 };
  547.             byte[] secondArray = { 1, 3, 5, 2, 9, 7, 6 };
  548.  
  549.             string total = SumArrays(firstArray, secondArray);
  550.             Console.WriteLine(total);
  551.  
  552.         }
  553.         public static string SumArrays(byte[] firstArray, byte[] secondArray)
  554.         {
  555.             List<byte> maxArray = new List<byte>();
  556.             List<byte> minArray = new List<byte>();
  557.             if (firstArray.Length > secondArray.Length)
  558.             {
  559.                 maxArray.AddRange(firstArray);
  560.                 minArray.AddRange(secondArray);
  561.             }
  562.             else
  563.             {
  564.                 maxArray.AddRange(secondArray);
  565.                 minArray.AddRange(firstArray);
  566.             }
  567.             int minLength = minArray.Count;
  568.             int maxLength = maxArray.Count;
  569.             int addition = 0;
  570.             int sum;
  571.             StringBuilder result = new StringBuilder();
  572.             for (int i = 0; i < minLength; i++)
  573.             {
  574.                 sum = minArray[i] + maxArray[i] + addition;
  575.                 if (sum >= 10)
  576.                 {
  577.                     addition = 1;
  578.                     sum = sum % 10;
  579.                     result.Append(sum);
  580.                 }
  581.                 else
  582.                 {
  583.                     result.Append(sum);
  584.                     addition = 0;
  585.                 }
  586.             }
  587.             for (int j = minLength; j < maxLength; j++)
  588.             {
  589.                 sum = maxArray[j] + addition;
  590.                 if (sum >= 10)
  591.                 {
  592.                     addition = 1;
  593.                     sum = sum % 10;
  594.                     result.Append(sum);
  595.                 }
  596.                 else
  597.                 {
  598.                     result.Append(sum);
  599.                     addition = 0;
  600.                 }
  601.             }
  602.             if (addition == 1)
  603.             {
  604.                 result.Append(1);
  605.             }
  606.             char[] reversed = (result.ToString()).ToCharArray();
  607.             result.Clear();
  608.             for (int i = reversed.Length - 1; i >= 0; i--)
  609.             {
  610.                 result = result.Append(reversed[i]);
  611.             }
  612.             return result.ToString();
  613.         }
  614.  
  615.  
  616. Problem 9. Sorting array ////////////////////////////////////////////////////////////////////////
  617.  
  618.  
  619. static int MaxElementInArrPortion(int[] array, int givenIndex)
  620.     {
  621.         int biggestIndex = givenIndex;
  622.         for (int i = givenIndex; i < array.Length; i++)
  623.         {
  624.             if (array[givenIndex] < array[i])
  625.             {
  626.                 biggestIndex = i;
  627.             }
  628.         }
  629.         return array[biggestIndex];
  630.     }
  631.  
  632.     static void SortArrayAscending(int[] array) //метод, който сортира възходящо
  633.     {
  634.         for (int i = 0; i < array.Length - 1; i++)
  635.         {
  636.             int elementMin = i;
  637.             for (int p = i + 1; p < array.Length; p++)
  638.             {
  639.                 if (array[p] < array[elementMin])
  640.                 {
  641.                     elementMin = p;
  642.                 }
  643.             }
  644.             if (elementMin != i)
  645.             {
  646.                 int temp = 0;
  647.                 temp = array[i];
  648.                 array[i] = array[elementMin];
  649.                 array[elementMin] = temp;
  650.             }
  651.        }
  652.     }
  653.  
  654.     static void SortArrayDescending(int[] array)//метод, който сортира низходящо
  655.     {
  656.         for (int i = 0; i < array.Length - 1; i++)
  657.         {
  658.             int elementMin = i;
  659.             for (int p = i + 1; p < array.Length; p++)
  660.             {
  661.                 if (array[p] < array[elementMin])
  662.                 {
  663.                     elementMin = p;
  664.                 }
  665.             }
  666.             if (elementMin != i)
  667.             {
  668.                 int temp = 0;
  669.                 temp = array[i];
  670.                 array[i] = array[elementMin];
  671.                 array[elementMin] = temp;
  672.             }
  673.         }
  674.         Array.Reverse(array);
  675.     }
  676.  
  677.     static void PrintArray(int[] array)
  678.     {
  679.         for (int i = 0; i < array.Length; i++)
  680.         {
  681.             Console.Write(array[i] + " ");
  682.         }
  683.         Console.WriteLine();
  684.     }
  685.    
  686.     static void Main(string[] args)
  687.     {
  688.         Console.WriteLine("Enter the length of the array");
  689.         int n = int.Parse(Console.ReadLine());
  690.         int[] array = new int[n];
  691.  
  692.         Console.WriteLine("Enter the Array indexes:");
  693.         for (int i = 0; i < n; i++)
  694.         {
  695.             Console.Write("Array[{0}] ", i);
  696.             array[i] = int.Parse(Console.ReadLine());
  697.         }
  698.  
  699.         Console.WriteLine("Enter the array index to start the check: ");
  700.         int givenIndex = int.Parse(Console.ReadLine());
  701.         Console.WriteLine("Maximal element in this array portion is: {0}", MaxElementInArrPortion(array, givenIndex));
  702.         Console.WriteLine("Enter number 1 if you want to sort the array in Ascending order: ");
  703.         Console.WriteLine("Enter number 2 if you want to sort the array in Descending order: ");
  704.         int howToSort = int.Parse(Console.ReadLine());
  705.  
  706.         if (howToSort == 1)
  707.         {
  708.             SortArrayAscending(array);
  709.             PrintArray(array);
  710.         }
  711.  
  712.         if (howToSort == 2)
  713.         {
  714.             SortArrayDescending(array);
  715.             PrintArray(array);
  716.         }
  717.  
  718.         else if (howToSort != 1 && howToSort !=2)
  719.         {
  720.             Console.WriteLine("Error! Try Again!");
  721.         }
  722.     }
  723.   }
  724. }
  725.  
  726. //ОБЯСНЕНИЕ: Създаваме си един масив и му въвеждаме ръчно стойности. Посочваме и някакъв индекс от масива, от който индекс до края на масива ще се опитаме да намерим индекса с най-големия елемент. За да намерим най-големия елемент от някакъв отрязък от елементи в масива ще използваме метода MaxElementInArrPortion.
  727. //Идеята му е, че приемаме първоначално, че индекса, който сме посочили за начало на отрязъка от елементи е именно индексът, на чиято позиция се съдържа най-големия елемент. С помощта на един лесен for Цикъл с if условие в MaxElementInArrPortion провеяваме това дали наистина е така, като сравняваме първоначално зададения индекс
  728. //с всички останали елементи до края на масива. Ако намерим по голям елемент, просто if цикъла го заместваме в променливата biggestIndex и метода накрая ни връща на кой точно индекс се намира търсения от нас най-голям елемент в отрязъка.
  729.  
  730. //За сортирането на масива ще използваме SelectionSort алгоритъма, с който се запознахме в лекциите за многомерни масиви. Създаваме си класическия за целта SelectionSort медот с класическия за алгоритъма код, който можете да си копирате директно от предишните задачи.
  731. //Ако потребителят въведе цифрата 1, ще се изпълни SortArrayAscending метода, който ще сортира масива възходящо и съответно, въведе 2 - ще се изпълни метода SortArrayDescending, който ще сортира низходящо. Между другото кодът при SortArrayDescending е същия с SortArrayAscending с разликата, че накрая reverse-ваме сортирания масив.
  732.  
  733.  
  734. Problem 10. N Factorial //////////////////////////////////////////////////////////////////////////
  735.  
  736. using System;
  737. using System.Collections.Generic;
  738. using System.Linq;
  739. using System.Text;
  740. using System.Threading.Tasks;
  741. using System.Numerics;
  742.  
  743. namespace _10_FacturielNumber
  744. {
  745.     class FactorialNumber
  746.     {
  747.         static BigInteger CalcualteFactorial(int[] array, int n)
  748.         {
  749.             BigInteger result = 1;
  750.             for (int i = 1; i <= n; i++)
  751.             {
  752.                 result = result * array[i];
  753.             }
  754.             return result;
  755.         }
  756.  
  757.         static void Main()
  758.         {
  759.             int[] hundredNumbers = new int[100];
  760.             for (int i = 1; i < 100; i++)
  761.             {
  762.                 hundredNumbers[i] = i;
  763.  
  764.             }
  765.             foreach (var item in hundredNumbers)
  766.             {
  767.                 Console.WriteLine(CalcualteFactorial(hundredNumbers, item));
  768.             }
  769.         }
  770.     }
  771. }
  772.  
  773.  
  774.  
  775. //ОБЯСНЕНИЕ: Тук трябва да изчислим фактуриел от 100. Тъй като големината на числата ще нарастнат доста бързо, изчисляването на фактуриел изисква да ползваме BigInteger (виж задача 08, как се извикват). Формулата за фактуриел е ясна още от задачите в C#1,
  776. //можете оттам да си  я припомните. Особеното тук е че просто изнасяме формулата в отделен метод. И това е.
  777.  
  778.  
  779.  
  780.  
  781. Problem 13. Solve tasks //////////////////////////////////////////////////////////////////////////////////
  782.  
  783.  public static int ReverseNumber(int number)
  784.         {
  785.             int tempNumber = 0;
  786.             while (number > 0)
  787.             {
  788.                 tempNumber = (tempNumber * 10) + (number % 10);
  789.                 number /= 10;
  790.             }
  791.             return tempNumber;
  792.         }
  793.  
  794.         static double GetAverage(int[] array)
  795.         {
  796.             int sum = 0;
  797.             for (int i = 0; i < array.Length; i++)
  798.             {
  799.                 sum += array[i];
  800.             }
  801.             return (double)sum / array.Length;
  802.         }
  803.  
  804.         static double SolveEquation(int a, int b)
  805.         {
  806.             return (double)-b / a;
  807.         }
  808.  
  809.         static void PrintReverseDigits()
  810.         {
  811.             Console.WriteLine("Enter number:");
  812.             int n = int.Parse(Console.ReadLine());
  813.             if (n > 0)
  814.             {
  815.                 Console.WriteLine("The reversed number is: " + ReverseNumber(n));
  816.             }
  817.             else
  818.             {
  819.                 Console.WriteLine("The number should be positive");
  820.             }
  821.         }
  822.  
  823.         static void PrintAverage()
  824.         {
  825.             Console.WriteLine("The the length of the array");
  826.             int[] array = new int[int.Parse(Console.ReadLine())];
  827.             for (int i = 0; i < array.Length; i++)
  828.             {
  829.                 array[i] = int.Parse(Console.ReadLine());
  830.             }
  831.             if (array.Length > 0)
  832.             {
  833.                 Console.WriteLine("Get Average: " + GetAverage(array));
  834.             }
  835.             else
  836.             {
  837.                 Console.WriteLine("You have entered blank or invalid input");
  838.             }
  839.         }
  840.  
  841.         static void PrintEquation()
  842.         {
  843.             Console.WriteLine("Enter a and b");
  844.             int a = int.Parse(Console.ReadLine());
  845.             int b = int.Parse(Console.ReadLine());
  846.             if (a != 0)
  847.             {
  848.                 Console.WriteLine("Solve equation" + SolveEquation(a, b));
  849.             }
  850.             else
  851.             {
  852.                 Console.WriteLine("Coefficient 'a' should bi different from zero");
  853.             }
  854.  
  855.         }
  856.         static void Main()
  857.         {
  858.             Console.WriteLine("1: ReverseDigits 2: GetAverage 3: SolveEquation");
  859.  
  860.             int n = int.Parse(Console.ReadLine());
  861.             if (n == 1)
  862.             {
  863.                 PrintReverseDigits();
  864.             }
  865.             else if (n == 2)
  866.             {
  867.                 PrintAverage();
  868.             }
  869.             else if (n == 3)
  870.             {
  871.                 PrintEquation();
  872.             }
  873.         }
  874.     }
  875. }
  876.  
  877. //ОБЯСНЕНИЕ: Сравнително лесна задача, като за 13 :) Просто може да се разгледа като три малки подзадачки събрани в една.
  878. //Няма нищо кой знае колко сложно за обясняване тук - формулата за квадратно уравнение е вече добре позната от C#1, намирането на средната стойност също, а пък кодът за
  879. //разместването на цифрите в ведно число можете направо да си го копи-пейстнете от решенета по-горе 7-ма задача на Методи.
  880. //Правите си и нужните проверки със стандартните if и else условия и готово. Начини за решението на тази задача бол, така че както и да го напишете няма значение, стига да работи :)
  881.  
  882.  
  883.  
  884. Problem 14. Integer calculations  //////////////////////////////////////////////////////////////////////
  885.  
  886. static int FindMax(params int[] array)
  887.     {
  888.         int biggestNum = array[0];
  889.         int length = array.Length;
  890.         for (int i = 0; i < length; i++)
  891.         {
  892.             if (length > 0)
  893.             {
  894.                 if (array[i] > biggestNum)
  895.                 {
  896.                     biggestNum = array[i];
  897.                 }
  898.             }
  899.             else
  900.             {
  901.                 return 0;
  902.             }
  903.            
  904.         }
  905.         return biggestNum;
  906.     }
  907.  
  908.     static int FindMin(params int[] array)
  909.     {
  910.         int smallestNumber = array[0];
  911.         int length = array.Length;
  912.         for (int i = 0; i < length; i++)
  913.         {
  914.             if(length > 0)
  915.             {
  916.                 if (array[i] < smallestNumber)
  917.                 {
  918.                     smallestNumber = array[i];
  919.  
  920.                 }
  921.             }
  922.             else
  923.             {
  924.                 return 0;
  925.             }
  926.         }
  927.         return smallestNumber;
  928.     }
  929.  
  930.     static double GetAverage(params int[] array)
  931.     {
  932.         int sum = 0;
  933.         for (int i = 0; i < array.Length; i++)
  934.         {
  935.             sum += array[i];
  936.         }
  937.         return (double)sum / array.Length;
  938.     }
  939.     static int GetSum (int[] array)
  940.     {
  941.         int sum = 0;
  942.  
  943.         for (int i = 0; i < array.Length; i++) sum += array[i];
  944.  
  945.         return sum;
  946.     }
  947.  
  948.     static int FindProduct(params int[] array)
  949.     {
  950.         int product = 1;
  951.         foreach (var number in array)
  952.         {
  953.             product *= number;
  954.         }
  955.         return product;
  956.     }
  957.         static void Main(string[] args)
  958.         {
  959.             Console.WriteLine("Enter the length of the array");
  960.             int n = int.Parse(Console.ReadLine());
  961.             int[] array = new int[n];
  962.  
  963.             Console.WriteLine("Enter the Array indexes:");
  964.             for (int i = 0; i < n; i++)
  965.             {
  966.                 Console.Write("Array[{0}] ", i);
  967.                 array[i] = int.Parse(Console.ReadLine());
  968.             }
  969.  
  970.         Console.WriteLine("Min = {0}", FindMin(array));
  971.         Console.WriteLine("Max = {0}", FindMax(array));
  972.         Console.WriteLine("Sum = {0}", GetSum(array));
  973.         Console.WriteLine("Average = {0}", GetAverage(array));
  974.         Console.WriteLine("Product = {0}", FindProduct(array));
  975.         Console.WriteLine();
  976.         }
  977.     }
  978. }
  979.  
  980.  
  981. //ОБЯСНЕНИЕ: Също лесна задача, подобна на предишната 13. Трябва да намери минимална, среднна, максимална стойност, сума и произведение на числата в един масив.
  982. //Някой от кодовете дори могат да се вземат и от предишните задачи тук, други пък от по-стари задачи. Обръщам внимание само, че за метода с произведението на числата в масива
  983. //ползваме отново BigInteger, за да се затраховаме от евентуално препълване.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement