w3resource

C#: Create a new array taking the first and last elements of a given array of integers and length 1 or more


First and Last Elements of Array

Write a C# Sharp program to create an array taking the first and last elements of a given array of integers and length 1 or more.

Visual Presentation:

C# Sharp: Basic Algorithm Exercises - Create a new array taking the first and last elements of a given array of integers and length 1 or more.

Sample Solution:-

C# Sharp Code:

using System; // Importing the System namespace

namespace exercises // Defining a namespace called 'exercises'
{
    class Program // Defining a class named 'Program'
    {
        static void Main(string[] args) // The entry point of the program
        {         
            // Calling the 'test' method with an integer array as an argument and assigning the result to the 'item' array
            int[] item = test(new[] { 10, 20, -30, -40, 30 }); 
            //int[] item = test(new[] { 10 }); // Example of using 'test' method with a single-element array

            // Outputting text to indicate the start of displaying the new array
            Console.Write("New array: ");

            // Looping through each element of the 'item' array and displaying them
            foreach(var i in item)
            {
                Console.Write(i.ToString()+" "); // Displaying each element of the 'item' array separated by a space
            }
        }        

        // Method to create a new array containing the first and last elements of the input array
        public static int[]  test(int[] nums)
        {
            // Returning a new array with the first and last elements of the 'nums' array
            return new int[] { nums[0], nums[nums.Length - 1] };
        } 
    }
}

Sample Output:

New array: 10 30

Flowchart:

C# Sharp: Flowchart: Create a new array taking the first and last elements of a given array of integers and length 1 or more.

Go to:


PREV : Middle Elements from Two Arrays.
NEXT : Array of Length 2 Contains 15 or 20.

C# Sharp Code Editor:



Improve this sample solution and post your code through Disqus

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.