Write a C# Sharp program to re-arrange the elements in a given array of numbers and check the numbers are consecutive or not

  • برمجة سي شارب
  • برمجة

Write a C# Sharp program to re-arrange the elements in a given array of numbers and check the numbers are consecutive or not. 
From Wikipedia,
Consecutive numbers are numbers that follow each other in order. They have a difference of 1 between every two numbers. In a set of consecutive numbers, the mean and the median are equal.
If n is a number, then the next numbers will be n+1 and n+2.
Examples:
Consecutive numbers that follow each other in order:

  • 1, 2, 3, 4, 5
  • -3, −2, −1, 0, 1, 2, 3, 4
  • 6, 7, 8, 9, 10, 11, 12, 13

Test Data :
Original array elements:
-10 -11 -12 -13 -14 15 16 17 18 19 20
Check the numbers of the said array are consecutive or not! False
Original array elements:
-1 -2 -3 0 1 4 3 2
Check the numbers of the said array are consecutive or not! True

الأجوبة

using System;
using System.Linq;
namespace exercises
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] nums = { -10, -11, -12, -13, -14, 15, 16, 17, 18, 19, 20 };
            Console.WriteLine("Original array elements:");
            for (int i = 0; i < nums.Length; i++)
            {
                Console.Write(nums[i] + " ");
            }
            Console.WriteLine("\nCheck the numbers of the said array are consecutive or not! " + test(nums));
            int[] nums1 = { -1, -2, -3, 0, 1, 4, 3, 2 };
            Console.WriteLine("\nOriginal array elements:");
            for (int i = 0; i < nums1.Length; i++)
            {
                Console.Write(nums1[i] + " ");
            }
            Console.WriteLine("\nCheck the numbers of the said array are consecutive or not! " + test(nums1));
        }
        public static bool test(int[] nums)
        {
            Array.Sort(nums);
            for (int i = 1; i < nums.Length; i++)
                if (nums[i] - nums[i - 1] != 1)
                    return false;
            return true;
        }
    }
} 
هل كان المحتوى مفيد؟

تبحث عن مدرس اونلاين؟

محتاج مساعدة باختيار المدرس الافضل؟ تواصل مع فريقنا الان لمساعدتك بتأمين افضل مدرس
ماهو التخصص الذي تبحث عنه؟
اكتب هنا...