Как вывести массив в обратном порядке на Си?
size как отдельная переменная не нужна. Можно же подсчитать. #define ASZ(a) (sizeof(a)/sizeof(a[0])) .
31 окт 2020 в 19:13
И второй вариант (когда i лишняя, да и вообще много букв в оригинале) size_t size = ASZ(a); while (size—) printf(. a[size]); .
31 окт 2020 в 19:16
#include int main(void) < int arr[5] = ; for (int i = 5; i > 0; --i) printf("%d ", arr[i-1]); >
Отслеживать
ответ дан 31 окт 2020 в 15:50
Джонни Кэтсвилл Джонни Кэтсвилл
356 1 1 серебряный знак 6 6 бронзовых знаков
Смотри комментарии к другому ответу.
31 окт 2020 в 19:19
- c
- массивы
- сортировка
- вывод
-
Важное на Мете
Похожие
Подписаться на ленту
Лента вопроса
Для подписки на ленту скопируйте и вставьте эту ссылку в вашу программу для чтения RSS.
Дизайн сайта / логотип © 2023 Stack Exchange Inc; пользовательские материалы лицензированы в соответствии с CC BY-SA . rev 2023.11.15.1019
Нажимая «Принять все файлы cookie» вы соглашаетесь, что Stack Exchange может хранить файлы cookie на вашем устройстве и раскрывать информацию в соответствии с нашей Политикой в отношении файлов cookie.
Как вывести массив в обратном порядке си шарп
Познакомившись с циклами, переменными, условными конструкциями и массивами, рассмотрим несколько задач для работы с массивами.
Количество положительных чисел
Найдем количество положительных чисел в массиве:
int[] numbers = < -4, -3, -2, -1, 0, 1, 2, 3, 4 >; int result = 0; foreach(int number in numbers) < if(number >0) < result++; >> Console.WriteLine($"Число элементов больше нуля: ");
Здесь создаем вспомогательную переменную result , которая будет содержать количество положительных чисел. В цикле прохожим по массиву и, если его элемент больше нуля, добавляем к переменной result единицу.
Инверсия массива
Вторая задача — инверсия массива, то есть переворот его в обратном порядке:
int[] numbers = < -4, -3, -2, -1,0, 1, 2, 3, 4 >; int n = numbers.Length; // длина массива int k = n / 2; // середина массива int temp; // вспомогательный элемент для обмена значениями for(int i=0; i < k; i++) < temp = numbers[i]; numbers[i] = numbers[n - i - 1]; numbers[n - i - 1] = temp; >foreach(int i in numbers) < Console.Write($"\t"); >
Поскольку нам надо изменять элементы массива, то для этого используется цикл for. Алгоритм решения задачи подразумевает перебор элементов до середины массива, которая в программе представлена переменной k, и обмен значений элемента, который имеет индекс i, и элемента с индексом n-i-1.
Программа сортировки массива
Теперь возьмем задачу посложнее — простейшую сортировку массива:
int[] nums = < 54, 7, -41, 2, 4, 2, 89, 33, -5, 12 >; // сортировка int temp; for (int i = 0; i < nums.Length - 1; i++) < for (int j = i + 1; j < nums.Length; j++) < if (nums[i] >nums[j]) < temp = nums[i]; nums[i] = nums[j]; nums[j] = temp; >> > // вывод Console.WriteLine(«Вывод отсортированного массива»); for (int i = 0; i
Для сортировки массива выполняем проходы по массиву и сравниваем элементы. Поскольку нам надо последовательно сравнивать каждый элемент массива с каждым (за исключением сравния с самим собой), то здесь применятся вложенный цикл.
Во внешнем цикле мы берем элемент, который будем сравнивать:
for (int i = 0; i < nums.Length - 1; i++)
Далее запускаем вложенный цикл, который начинается, со следующего элемента, и из которого извлекаем элементы, с которыми будем сравнивать тот элемент, которые берется из массива во внешнем цикле:
for (int j = i + 1; j < nums.Length; j++)
Если элемент с меньшим индексом больше элемента с большим индексом, то меняем элементы местами.
if (nums[i] > nums[j])
В конце выводим все элементы.
Как вывести массив в обратном порядке си шарп
Все массивы в C# построены на основе класса Array из пространства имен System. Этот класс определяет ряд свойств и методов, которые мы можем использовать при работе с массивами. Основные свойства и методы:
- Свойство Length возвращает длину массива
- Свойство Rank возвращает размерность массива
- int BinarySearch (Array array, object? value) выполняет бинарный поиск в отсортированном массиве и возвращает индекс найденного элемента
- void Clear (Array array) очищает массив, устанавливая для всех его элементов значение по умолчанию
- void Copy (Array sourceArray, int sourceIndex, Array destinationArray, int destinationIndex, int length) копирует из массива sourceArray начиная с индекс sourceIndex length элементов в массив destinationArray начиная с индекса destinationIndex
- bool Exists (T[] array, Predicate match) проверяет, содержит ли массив array элементы, которые удовлеворяют условию делегата match
- void Fill (T[] array, T value) заполняет массив array значением value
- T? Find (T[] array, Predicate match) находит первый элемент, который удовлеворяет определенному условию из делегата match. Если элемент не найден, то возвращается null
- T? FindLast (T[] array, Predicate match) находит последний элемент, который удовлеворяет определенному условию из делегата match. Если элемент не найден, то возвращается null
- int FindIndex (T[] array, Predicate match) возвращает индекс первого вхождения элемента, который удовлеворяет определенному условию делегата match
- int FindLastIndex (T[] array, Predicate match) возвращает индекс последнего вхождения элемента, который удовлеворяет определенному условию
- T[] FindAll (T[] array, Predicate match) возвращает все элементы в виде массива, которые удовлеворяет определенному условию из делегата match
- int IndexOf (Array array, object? value) возвращает индекс первого вхождения элемента в массив
- int LastIndexOf (Array array, object? value) возвращает индекс последнего вхождения элемента в массив
- void Resize (ref T[]? array, int newSize) изменяет размер одномерного массива
- void Reverse (Array array) располагает элементы массива в обратном порядке
- void Sort (Array array) сортирует элементы одномерного массива
Разберем самые используемые методы.
Поиск индекса элемента
string[] people = < "Tom", "Sam", "Bob", "Kate", "Tom", "Alice" >; // находим индекс элемента "Bob" int bobIndex = Array.BinarySearch(people, "Bob"); // находим индекс первого элемента "Tom" int tomFirstIndex = Array.IndexOf(people, "Tom"); // находим индекс последнего элемента "Tom" int tomLastIndex = Array.LastIndexOf(people, "Tom"); // находим индекс первого элемента, у которого длина строки больше 3 int lengthFirstIndex = Array.FindIndex(people, person => person.Length > 3); // находим индекс последнего элемента, у которого длина строки больше 3 int lengthLastIndex = Array.FindLastIndex(people, person => person.Length > 3); Console.WriteLine($"bobIndex: "); // 2 Console.WriteLine($"tomFirstIndex: "); // 0 Console.WriteLine($"tomLastIndex: "); // 4 Console.WriteLine($"lengthFirstIndex: "); // 3 Console.WriteLine($"lengthLastIndex: "); // 5
Если элемент не найден в массиве, то методы возвращают -1.
Поиск элемента по условию
string[] people = < "Tom", "Sam", "Bob", "Kate", "Tom", "Alice" >; // находим первый и последний элементы // где длина строки больше 3 символов string? first = Array.Find(people, person => person.Length > 3); Console.WriteLine(first); // Kate string? last = Array.FindLast(people, person => person.Length > 3); Console.WriteLine(last); // Alice // находим элементы, у которых длина строки равна 3 string[] group = Array.FindAll(people, person => person.Length == 3); foreach (var person in group) Console.WriteLine(person); // Tom Sam Bob Tom
Изменение порядка элементов массива
Например, изменим порядок элементов:
string[] people = < "Tom", "Sam", "Bob", "Kate", "Tom", "Alice" >; Array.Reverse(people); foreach (var person in people) Console.Write($" "); // "Alice", "Tom", "Kate", "Bob", "Sam", "Tom"
Также можно изменить порядок только части элементов:
string[] people = < "Tom", "Sam", "Bob", "Kate", "Tom", "Alice" >; // изменяем порядок 3 элементов начиная c индекса 1 Array.Reverse(people, 1, 3); foreach (var person in people) Console.Write($" "); // "Tom", "Kate", "Bob", "Sam", "Tom", "Alice"
В данном случае изменяем порядок только 3 элементов начиная c индекса 1.
Изменение размера массива
Для изменения размера массива применяется метод Resize. Его первый параметр - изменяемый массив, а второй параметр - количество элементов, которые должны быть в массиве. Если второй параметр меньше длины массива, то массив усекается. Если значение параметра, наоборот, больше, то массив дополняется дополнительными элементами, которые имеют значение по умолчанию. Причем первый параметр передается по ссылке:
string[] people = < "Tom", "Sam", "Bob", "Kate", "Tom", "Alice" >; // уменьшим массив до 4 элементов Array.Resize(ref people, 4); foreach (var person in people) Console.Write($" "); // "Tom", "Sam", "Bob", "Kate"
Копирование массива
Метод Copy копирует часть одного массива в другой:
string[] people = < "Tom", "Sam", "Bob", "Kate", "Tom", "Alice" >; var employees = new string[3]; // копируем 3 элемента из массива people c индекса 1 // и вставляем их в массив employees начиная с индекса 0 Array.Copy(people,1, employees,0, 3); foreach (var person in employees) Console.Write($" "); // Sam Bob Kate
В данном случае копируем 3 элемента из массива people начиная c индекса 1 и вставляем их в массив employees начиная с индекса 0.
Сортировка массива
Отсортируем массив с помощью метода Sort() :
string[] people = < "Tom", "Sam", "Bob", "Kate", "Tom", "Alice" >; Array.Sort(people); foreach (var person in people) Console.Write($" "); // Alice Bob Kate Sam Tom Tom
Этот метод имеет много перегрузок. Например, одна из версий позволяет отсортировать только часть массива:
string[] people = < "Tom", "Sam", "Bob", "Kate", "Tom", "Alice" >; // сортируем с 1 индекса 3 элемента Array.Sort(people, 1, 3); foreach (var person in people) Console.Write($" "); // Tom Bob Kate Sam Tom Alice
Array. Reverse Method
Some information relates to prerelease product that may be substantially modified before it’s released. Microsoft makes no warranties, express or implied, with respect to the information provided here.
Reverses the order of the elements in a one-dimensional Array or in a portion of the Array.
Overloads
Reverses the sequence of a subset of the elements in the one-dimensional Array.
Reverses the sequence of the elements in the entire one-dimensional Array.
Reverses the sequence of the elements in the one-dimensional generic array.
Reverses the sequence of a subset of the elements in the one-dimensional generic array.
Reverse(Array, Int32, Int32)
Reverses the sequence of a subset of the elements in the one-dimensional Array.
public: static void Reverse(Array ^ array, int index, int length);
public static void Reverse (Array array, int index, int length);
static member Reverse : Array * int * int -> unit
Public Shared Sub Reverse (array As Array, index As Integer, length As Integer)
Parameters
The one-dimensional Array to reverse.
The starting index of the section to reverse.
The number of elements in the section to reverse.
Exceptions
array is multidimensional.
index is less than the lower bound of array .
length is less than zero.
index and length do not specify a valid range in array .
Examples
The following code example shows how to reverse the sort of the values in a range of elements in an Array.
using namespace System; void PrintIndexAndValues( Array^ myArray ); void main() < // Creates and initializes a new Array instance. Array^ myArray = Array::CreateInstance( String::typeid, 9 ); myArray->SetValue( "The", 0 ); myArray->SetValue( "QUICK", 1 ); myArray->SetValue( "BROWN", 2 ); myArray->SetValue( "FOX", 3 ); myArray->SetValue( "jumps", 4 ); myArray->SetValue( "over", 5 ); myArray->SetValue( "the", 6 ); myArray->SetValue( "lazy", 7 ); myArray->SetValue( "dog", 8 ); // Displays the values of the Array. Console::WriteLine( "The Array instance initially contains the following values:" ); PrintIndexAndValues( myArray ); // Reverses the sort of the values of the Array. Array::Reverse( myArray, 1, 3 ); // Displays the values of the Array. Console::WriteLine( "After reversing:" ); PrintIndexAndValues( myArray ); > void PrintIndexAndValues( Array^ myArray ) < for ( int i = myArray->GetLowerBound( 0 ); i GetUpperBound( 0 ); i++ ) Console::WriteLine( "\t[]:\t", i, myArray->GetValue( i ) ); > /* This code produces the following output. The Array instance initially contains the following values: [0]: The [1]: QUICK [2]: BROWN [3]: FOX [4]: jumps [5]: over [6]: the [7]: lazy [8]: dog After reversing: [0]: The [1]: FOX [2]: BROWN [3]: QUICK [4]: jumps [5]: over [6]: the [7]: lazy [8]: dog */
open System let printIndexAndValues (arr: 'a []) = for i = arr.GetLowerBound 0 to arr.GetUpperBound 0 do printfn $"\t[]:\t" // Creates and initializes a new Array. let myArray = [| "The"; "QUICK"; "BROWN"; "FOX" "jumps"; "over"; "the"; "lazy"; "dog" |] // Displays the values of the Array. printfn "The Array initially contains the following values:" printIndexAndValues myArray // Reverses the sort of the values of the Array. Array.Reverse(myArray, 1, 3) // Displays the values of the Array. printfn "After reversing:" printIndexAndValues myArray (* This code produces the following output. The Array initially contains the following values: [0]: The [1]: QUICK [2]: BROWN [3]: FOX [4]: jumps [5]: over [6]: the [7]: lazy [8]: dog After reversing: [0]: The [1]: FOX [2]: BROWN [3]: QUICK [4]: jumps [5]: over [6]: the [7]: lazy [8]: dog *)
using System; public class SamplesArray1 < public static void Main() < // Creates and initializes a new Array. Array myArray=Array.CreateInstance( typeof(string), 9 ); myArray.SetValue( "The", 0 ); myArray.SetValue( "QUICK", 1 ); myArray.SetValue( "BROWN", 2 ); myArray.SetValue( "FOX", 3 ); myArray.SetValue( "jumps", 4 ); myArray.SetValue( "over", 5 ); myArray.SetValue( "the", 6 ); myArray.SetValue( "lazy", 7 ); myArray.SetValue( "dog", 8 ); // Displays the values of the Array. Console.WriteLine( "The Array initially contains the following values:" ); PrintIndexAndValues( myArray ); // Reverses the sort of the values of the Array. Array.Reverse( myArray, 1, 3 ); // Displays the values of the Array. Console.WriteLine( "After reversing:" ); PrintIndexAndValues( myArray ); >public static void PrintIndexAndValues( Array myArray ) < for ( int i = myArray.GetLowerBound(0); i ]:\t", i, myArray.GetValue( i ) ); > > /* This code produces the following output. The Array initially contains the following values: [0]: The [1]: QUICK [2]: BROWN [3]: FOX [4]: jumps [5]: over [6]: the [7]: lazy [8]: dog After reversing: [0]: The [1]: FOX [2]: BROWN [3]: QUICK [4]: jumps [5]: over [6]: the [7]: lazy [8]: dog */
Public Class SamplesArray Public Shared Sub Main() ' Creates and initializes a new Array. Dim myArray As Array = Array.CreateInstance(GetType(String), 9) myArray.SetValue("The", 0) myArray.SetValue("QUICK", 1) myArray.SetValue("BROWN", 2) myArray.SetValue("FOX", 3) myArray.SetValue("jumps", 4) myArray.SetValue("over", 5) myArray.SetValue("the", 6) myArray.SetValue("lazy", 7) myArray.SetValue("dog", 8) ' Displays the values of the Array. Console.WriteLine("The Array initially contains the " _ + "following values:") PrintIndexAndValues(myArray) ' Reverses the sort of the values of the Array. Array.Reverse(myArray, 1, 3) ' Displays the values of the Array. Console.WriteLine("After reversing:") PrintIndexAndValues(myArray) End Sub Public Shared Sub PrintIndexAndValues(myArray As Array) Dim i As Integer For i = myArray.GetLowerBound(0) To myArray.GetUpperBound(0) Console.WriteLine(ControlChars.Tab + "[]:" + ControlChars.Tab _ + "", i, myArray.GetValue(i)) Next i End Sub End Class ' This code produces the following output. ' ' The Array initially contains the following values: ' [0]: The ' [1]: QUICK ' [2]: BROWN ' [3]: FOX ' [4]: jumps ' [5]: over ' [6]: the ' [7]: lazy ' [8]: dog ' After reversing: ' [0]: The ' [1]: FOX ' [2]: BROWN ' [3]: QUICK ' [4]: jumps ' [5]: over ' [6]: the ' [7]: lazy ' [8]: dog
Remarks
After a call to this method, the element at myArray[i] , where i is any index in the array, moves to myArray[j] , where j equals (myArray.Length + myArray.GetLowerBound(0)) - (i - myArray.GetLowerBound(0)) - 1 .
The Reverse method can be used to reverse a jagged array.
This method is an O( n ) operation, where n is length .
Applies to
Reverse(Array)
Reverses the sequence of the elements in the entire one-dimensional Array.
public: static void Reverse(Array ^ array);
public static void Reverse (Array array);
static member Reverse : Array -> unit
Public Shared Sub Reverse (array As Array)
Parameters
The one-dimensional Array to reverse.
Exceptions
array is multidimensional.
Examples
The following code example shows how to reverse the sort of the values in an Array.
using namespace System; void PrintIndexAndValues( Array^ myArray ); void main() < // Creates and initializes a new Array instance. Array^ myArray = Array::CreateInstance( String::typeid, 9 ); myArray->SetValue( "The", 0 ); myArray->SetValue( "quick", 1 ); myArray->SetValue( "brown", 2 ); myArray->SetValue( "fox", 3 ); myArray->SetValue( "jumps", 4 ); myArray->SetValue( "over", 5 ); myArray->SetValue( "the", 6 ); myArray->SetValue( "lazy", 7 ); myArray->SetValue( "dog", 8 ); // Displays the values of the Array. Console::WriteLine( "The Array instance initially contains the following values:" ); PrintIndexAndValues( myArray ); // Reverses the sort of the values of the Array. Array::Reverse( myArray ); // Displays the values of the Array. Console::WriteLine( "After reversing:" ); PrintIndexAndValues( myArray ); > void PrintIndexAndValues( Array^ myArray ) < for ( int i = myArray->GetLowerBound( 0 ); i GetUpperBound( 0 ); i++ ) Console::WriteLine( "\t[]:\t", i, myArray->GetValue( i ) ); > /* This code produces the following output. The Array instance initially contains the following values: [0]: The [1]: quick [2]: brown [3]: fox [4]: jumps [5]: over [6]: the [7]: lazy [8]: dog After reversing: [0]: dog [1]: lazy [2]: the [3]: over [4]: jumps [5]: fox [6]: brown [7]: quick [8]: The */
open System let printIndexAndValues (arr: 'a []) = for i = arr.GetLowerBound 0 to arr.GetUpperBound 0 do printfn $"\t[]:\t" // Creates and initializes a new Array. let myArray = [| "The"; "quick"; "brown"; "fox" "jumps"; "over"; "the"; "lazy"; "dog" |] // Displays the values of the Array. printfn "The Array initially contains the following values:" printIndexAndValues myArray // Reverses the sort of the values of the Array. Array.Reverse myArray // Displays the values of the Array. printfn "After reversing:" printIndexAndValues myArray (* This code produces the following output. The Array initially contains the following values: [0]: The [1]: quick [2]: brown [3]: fox [4]: jumps [5]: over [6]: the [7]: lazy [8]: dog After reversing: [0]: dog [1]: lazy [2]: the [3]: over [4]: jumps [5]: fox [6]: brown [7]: quick [8]: The *)
using System; public class SamplesArray < public static void Main() < // Creates and initializes a new Array. Array myArray=Array.CreateInstance( typeof(string), 9 ); myArray.SetValue( "The", 0 ); myArray.SetValue( "quick", 1 ); myArray.SetValue( "brown", 2 ); myArray.SetValue( "fox", 3 ); myArray.SetValue( "jumps", 4 ); myArray.SetValue( "over", 5 ); myArray.SetValue( "the", 6 ); myArray.SetValue( "lazy", 7 ); myArray.SetValue( "dog", 8 ); // Displays the values of the Array. Console.WriteLine( "The Array initially contains the following values:" ); PrintIndexAndValues( myArray ); // Reverses the sort of the values of the Array. Array.Reverse( myArray ); // Displays the values of the Array. Console.WriteLine( "After reversing:" ); PrintIndexAndValues( myArray ); >public static void PrintIndexAndValues( Array myArray ) < for ( int i = myArray.GetLowerBound(0); i ]:\t", i, myArray.GetValue( i ) ); > > /* This code produces the following output. The Array initially contains the following values: [0]: The [1]: quick [2]: brown [3]: fox [4]: jumps [5]: over [6]: the [7]: lazy [8]: dog After reversing: [0]: dog [1]: lazy [2]: the [3]: over [4]: jumps [5]: fox [6]: brown [7]: quick [8]: The */
Public Class SamplesArray Public Shared Sub Main() ' Creates and initializes a new Array. Dim myArray As Array = Array.CreateInstance(GetType(String), 9) myArray.SetValue("The", 0) myArray.SetValue("quick", 1) myArray.SetValue("brown", 2) myArray.SetValue("fox", 3) myArray.SetValue("jumps", 4) myArray.SetValue("over", 5) myArray.SetValue("the", 6) myArray.SetValue("lazy", 7) myArray.SetValue("dog", 8) ' Displays the values of the Array. Console.WriteLine("The Array initially contains the " _ + "following values:") PrintIndexAndValues(myArray) ' Reverses the sort of the values of the Array. Array.Reverse(myArray) ' Displays the values of the Array. Console.WriteLine("After reversing:") PrintIndexAndValues(myArray) End Sub Public Shared Sub PrintIndexAndValues(myArray As Array) Dim i As Integer For i = myArray.GetLowerBound(0) To myArray.GetUpperBound(0) Console.WriteLine(ControlChars.Tab + "[]:" + ControlChars.Tab _ + "", i, myArray.GetValue(i)) Next i End Sub End Class ' This code produces the following output. ' ' The Array initially contains the following values: ' [0]: The ' [1]: quick ' [2]: brown ' [3]: fox ' [4]: jumps ' [5]: over ' [6]: the ' [7]: lazy ' [8]: dog ' After reversing: ' [0]: dog ' [1]: lazy ' [2]: the ' [3]: over ' [4]: jumps ' [5]: fox ' [6]: brown ' [7]: quick ' [8]: The
Remarks
After a call to this method, the element at myArray[i] , where i is any index in the array, moves to myArray[j] , where j equals (myArray.Length + myArray.GetLowerBound(0)) - (i - myArray.GetLowerBound(0)) - 1 .
This method is an O( n ) operation, where n is the Length of array .
In F#, the Array.rev function can be used instead.
As the following example shows, the Reverse method can be used to reverse a jagged array. It initializes a jagged array with one element for each month of the current year in the current culture's calendar. Each element contains an array with as many elements as that month has days. The example displays the contents of the array, calls the Reverse method, and then displays the contents of the reversed array.
using System; using System.Globalization; public class Example < public static void Main() < int nMonths = DateTimeFormatInfo.CurrentInfo.Calendar.GetMonthsInYear(DateTime.Now.Year); int[][] months = new int[nMonths][]; // Populate elements with number of days in month. for (int ctr = 0; ctr foreach (var month in months) < foreach (var day in month) Console.Write("", day); Console.WriteLine(); > Console.WriteLine(); Console.WriteLine("About to reverse array.\n"); Array.Reverse(months); foreach (var month in months) < foreach (var day in month) Console.Write("", day); Console.WriteLine(); > > > // The example displays output similar to the following: // 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 // 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 // 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 // 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 // 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 // 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 // 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 // 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 // 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 // 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 // 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 // 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 // // About to reverse array. // // 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 // 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 // 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 // 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 // 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 // 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 // 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 // 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 // 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 // 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 // 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 // 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
open System open System.Globalization let nMonths = DateTimeFormatInfo.CurrentInfo.Calendar.GetMonthsInYear DateTime.Now.Year let months = Array.init nMonths (fun i -> // Populate elements with number of days in month. let daysInMonth = DateTime.DaysInMonth(DateTime.Now.Year, i + 1) Array.init daysInMonth (fun i -> i + 1 ) ) for month in months do for day in month do printf $" " printfn "" printfn "\nAbout to reverse array.\n" Array.Reverse months for month in months do for day in month do printf $" " printfn "" // The example displays output similar to the following: // 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 // 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 // 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 // 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 // 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 // 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 // 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 // 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 // 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 // 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 // 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 // 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 // // About to reverse array. // // 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 // 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 // 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 // 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 // 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 // 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 // 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 // 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 // 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 // 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 // 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 // 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
Imports System.Globalization Module Example Public Sub Main() Dim nMonths As Integer = DateTimeFormatInfo.CurrentInfo.Calendar.GetMonthsInYear(Date.Now.Year) Dim months()() As Integer = New Integer(nMonths - 1)() <> ' Populate elements with number of days in month. For ctr As Integer = 0 To months.GetUpperBound(0) Dim daysInMonth As Integer = DateTime.DaysInMonth(Date.Now.Year, ctr + 1) months(ctr) = New Integer(daysInMonth - 1) <> For ctr2 As Integer = 1 To daysInMonth months(ctr)(ctr2 - 1) = ctr2 Next Next For Each _month In months For each _day In _month Console.Write(" ", _day) Next Console.WriteLine() Next Console.WriteLine() Console.WriteLine("About to reverse array.") Console.WriteLine() Array.Reverse(months) For Each _month In months For each _day In _month Console.Write(" ", _day) Next Console.WriteLine() Next End Sub End Module ' The example displays output similar to the following: ' 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 ' 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 ' 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 ' 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 ' 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 ' 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 ' 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 ' 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 ' 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 ' 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 ' 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 ' 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 ' ' About to reverse array. ' ' 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 ' 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 ' 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 ' 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 ' 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 ' 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 ' 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 ' 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 ' 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 ' 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 ' 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 ' 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
