w3resource

C# Sharp Exercises: Check the numbers of a given array are consecutive or not

C# Sharp Array: Exercise-36 with Solution

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

Sample Solution:-

C# Sharp Code:

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;
        }
    }
} 

Sample Output:

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
 

Flowchart:

Flowchart: Check the numbers of a given array are consecutive or not.

C# Sharp Code Editor:

Contribute your code and comments through Disqus.

Previous C# Sharp: Calculate the sum of two lowest negative numbers of a given array of integers.
Next C# Sharp: Smallest gap between the numbers in an array

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Share this Tutorial / Exercise on : Facebook and Twitter