Наибольшее и наименьшее число в массиве
Это работает отлично … но когда я использую foreach
а не for
этого, это не работает. Я не могу понять, for
и foreach
одинаковы.
namespace ConsoleApplication2 { class Program { static void Main(string[] args) { int[] array = new int[10]; Console.WriteLine("enter the array elements to b sorted"); for(int i=0;i<10;i++) { array[i] = Convert.ToInt32(Console.ReadLine()); } int smallest = array[0]; for(int i=0;i<10;i++) { if(array[i]<smallest) { smallest=array[i]; } } int largest = array[9]; for(int i=0;i largest) { largest = array[i]; } } Console.WriteLine("the smallest no is {0}", smallest); Console.WriteLine("the largest no is {0}", largest); Console.Read(); } } }
- Рекомендация для библиотеки матриц C #
- Внедрить IDispatch :: Invoke для вызова с помощью элемента управления WebBrowser
- Форматирование JSON в C #?
- Когда `PostAuthenticateRequest` получает выполнение?
- Тип для представления байта в ANSI (C89 / 90) C?
- Передайте двумерный массив функции постоянного параметра
- Является ли stream генератора случайных чисел C # безопасным?
- SSE, внутренности и выравнивание
- Почему строки в C должны быть пустыми?
- Постоянный ресурс ссылки C ++ (контейнерный адаптер)
- Инъекция зависимостей - требуется новый экземпляр для нескольких методов classов
- Исключение исключений нарушения доступа?
- C ++ шаблоны Turing-complete?
Почему вы не используете это?
int[] array = { 12, 56, 89, 65, 61, 36, 45, 23 }; int max = array.Max(); int min = array.Min();
Если вам нужно использовать foreach (по какой-то причине) и не хотите использовать функции bult-in, вот fragment кода:
int minint = array[0]; int maxint = array[0]; foreach (int value in array) { if (value < minint) minint = value; if (value > maxint) maxint = value; }
static void PrintSmallestLargest(int[] arr) { if (arr.Length > 0) { int small = arr[0]; int large = arr[0]; for (int i = 0; i < arr.Length; i++) { if (large < arr[i]) { int tmp = large; large = arr[i]; arr[i] = large; } if (small > arr[i]) { int tmp = small; small = arr[i]; arr[i] = small; } } Console.WriteLine("Smallest is {0}", small); Console.WriteLine("Largest is {0}", large); } }
Таким образом, вы можете иметь наименьшее и наибольшее число в одном цикле.
Вы (обычно) не можете изменять коллекцию, которую вы выполняете при использовании foreach.
Хотя для и foreach кажутся похожими с точки зрения разработчика, они сильно отличаются от перспективы реализации.
Foreach
использует Iterator
для доступа к отдельным объектам, а for
не знает (или не заботится) о базовой последовательности объектов.
using System; namespace greatest { class Greatest { public static void Main(String[] args) { //get the number of elements Console.WriteLine("enter the number of elements"); int i; i=Convert.ToInt32(Console.ReadLine()); int[] abc = new int[i]; //accept the elements for(int size=-1; size
Int[] number ={1,2,3,4,5,6,7,8,9,10}; Int? Result = null; foreach(Int i in number) { If(!Result.HasValue || i< Result) { Result =i; } } Console.WriteLine(Result); }
public int MinimumValue { get; private set; } public int MaxmimumValue { get; private set; } public void num() { int[] array = { 12, 56, 89, 65, 61, 36, 45, 23 }; MaxmimumValue = array[0]; MinimumValue = array[0]; foreach (int num in array) { if (num > MaxmimumValue) MaxmimumValue = num; if (num < MinimumValue) MinimumValue = num; } Console.WriteLine(MinimumValue); Console.WriteLine(MaxmimumValue); }
Вот полная программа, приведенная ниже `
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Threading; using System.Diagnostics; namespace oops3 { public class Demo { static void Main(string[] args) { Console.WriteLine("Enter the size of the array"); int x = Convert.ToInt32(Console.ReadLine()); int[] arr = new int[x]; Console.WriteLine("Enter the elements of the array"); for(int i=0;iarr[i]) { smallest = arr[i]; } } for (int i = 0; i < x; i++) { if (Largest< arr[i]) { Largest = arr[i]; } } Console.WriteLine("The greater No in the array:" + Largest); Console.WriteLine("The smallest No in the array:" + smallest); Console.ReadLine(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Array_Small_and_lagest { class Program { static void Main(string[] args) { int[] array = new int[10]; Console.WriteLine("enter the array elements to b sorted"); for (int i = 0; i < 10; i++) { array[i] = Convert.ToInt32(Console.ReadLine()); } int smallest = array[0]; foreach (int i in array) { if (i < smallest) { smallest = i; } } int largest = array[9]; foreach (int i in array) { if (i > largest) { largest = i; } } Console.WriteLine("the smallest no is {0}", smallest); Console.WriteLine("the largest no is {0}", largest); Console.Read(); } } }
Это долгое время. Может быть, вот так:
public int smallestValue(int[] values) { int smallest = int.MaxValue; for (int i = 0; i < values.Length; i++) { smallest = (values[i] < smallest ? values[i] : smallest); } return smallest; } public static int largestvalue(int[] values) { int largest = int.MinValue; for (int i = 0; i < values.Length; i++) { largest = (values[i] > largest ? values[i] : largest); } return largest; }